From 18e93c70773141b9a43857300b89a69e543cfdea Mon Sep 17 00:00:00 2001 From: Serge Zaitsev Date: Fri, 8 Apr 2022 16:15:06 +0200 Subject: [PATCH] Chore: Remove bus (#47511) * Chore: Remove bus * remove unused const --- pkg/api/admin_users_test.go | 28 ---- pkg/api/alerting_test.go | 7 - pkg/api/annotations_test.go | 9 -- pkg/api/common_test.go | 4 - pkg/api/dashboard_snapshot_test.go | 8 -- pkg/api/dashboard_test.go | 20 --- pkg/api/folder_permission_test.go | 3 - pkg/api/folder_test.go | 4 - pkg/api/pluginproxy/ds_proxy_test.go | 13 -- pkg/api/plugins_test.go | 3 - pkg/api/short_url_test.go | 3 - pkg/api/user_test.go | 19 --- pkg/api/user_token_test.go | 15 -- pkg/bus/bus.go | 107 -------------- pkg/bus/bus_test.go | 135 ------------------ pkg/expr/service_test.go | 7 - pkg/login/auth.go | 2 - pkg/middleware/middleware_basic_auth_test.go | 16 --- pkg/middleware/middleware_jwt_auth_test.go | 9 -- pkg/middleware/middleware_test.go | 3 - pkg/middleware/org_redirect_test.go | 5 - pkg/middleware/recovery_test.go | 3 - pkg/services/alerting/notifier_test.go | 9 -- pkg/services/alerting/service.go | 14 -- .../manager/dashboard_service_test.go | 3 - .../dashboardsnapshots/dashboardsnapshots.go | 6 - .../datasources/service/datasource_service.go | 8 -- .../authinfoservice/database/database.go | 9 -- .../login/loginservice/loginservice.go | 1 - .../login/loginservice/loginservice_test.go | 2 - pkg/services/notifications/notifications.go | 7 - .../notifications/notifications_test.go | 37 +++-- .../service/dashboard_updater_test.go | 2 - pkg/services/search/service.go | 1 - pkg/services/sqlstore/alert.go | 11 -- pkg/services/sqlstore/alert_notification.go | 5 - .../sqlstore/alert_notification_test.go | 9 +- pkg/services/sqlstore/apikey.go | 9 -- pkg/services/sqlstore/dashboard.go | 13 -- pkg/services/sqlstore/dashboard_acl.go | 5 - pkg/services/sqlstore/dashboard_version.go | 7 - pkg/services/sqlstore/login_attempt.go | 7 - pkg/services/sqlstore/org.go | 11 -- pkg/services/sqlstore/org_users.go | 8 -- pkg/services/sqlstore/playlist.go | 10 -- pkg/services/sqlstore/preferences.go | 8 -- pkg/services/sqlstore/quota.go | 11 -- pkg/services/sqlstore/sqlstore.go | 22 --- pkg/services/sqlstore/star.go | 8 -- pkg/services/sqlstore/stats.go | 10 -- pkg/services/sqlstore/team.go | 14 -- pkg/services/sqlstore/temp_user.go | 10 -- pkg/services/sqlstore/user.go | 20 --- 53 files changed, 19 insertions(+), 701 deletions(-) diff --git a/pkg/api/admin_users_test.go b/pkg/api/admin_users_test.go index b2d331eb213..0ba11679d3c 100644 --- a/pkg/api/admin_users_test.go +++ b/pkg/api/admin_users_test.go @@ -1,7 +1,6 @@ package api import ( - "context" "fmt" "testing" @@ -49,11 +48,6 @@ func TestAdminAPIEndpoint(t *testing.T) { mock := mockstore.NewSQLStoreMock() adminLogoutUserScenario(t, "Should not be allowed when calling POST on", "/api/admin/users/1/logout", "/api/admin/users/:id/logout", func(sc *scenarioContext) { - bus.AddHandler("test", func(ctx context.Context, cmd *models.GetUserByIdQuery) error { - cmd.Result = &models.User{Id: testUserID} - return nil - }) - sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() assert.Equal(t, 400, sc.resp.Code) }, mock) @@ -182,8 +176,6 @@ func TestAdminAPIEndpoint(t *testing.T) { } adminCreateUserScenario(t, "Should create the user", "/api/admin/users", "/api/admin/users", createCmd, func(sc *scenarioContext) { - bus.ClearBusHandlers() - sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() assert.Equal(t, 200, sc.resp.Code) @@ -202,8 +194,6 @@ func TestAdminAPIEndpoint(t *testing.T) { } adminCreateUserScenario(t, "Should create the user", "/api/admin/users", "/api/admin/users", createCmd, func(sc *scenarioContext) { - bus.ClearBusHandlers() - sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() assert.Equal(t, 200, sc.resp.Code) @@ -222,8 +212,6 @@ func TestAdminAPIEndpoint(t *testing.T) { } adminCreateUserScenario(t, "Should create the user", "/api/admin/users", "/api/admin/users", createCmd, func(sc *scenarioContext) { - bus.ClearBusHandlers() - sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() assert.Equal(t, 400, sc.resp.Code) @@ -241,8 +229,6 @@ func TestAdminAPIEndpoint(t *testing.T) { } adminCreateUserScenario(t, "Should return an error", "/api/admin/users", "/api/admin/users", createCmd, func(sc *scenarioContext) { - bus.ClearBusHandlers() - sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() assert.Equal(t, 412, sc.resp.Code) @@ -256,8 +242,6 @@ func TestAdminAPIEndpoint(t *testing.T) { func putAdminScenario(t *testing.T, desc string, url string, routePattern string, role models.RoleType, cmd dtos.AdminUpdateUserPermissionsForm, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - hs := &HTTPServer{ Cfg: setting.NewCfg(), SQLStore: sqlStore, @@ -284,8 +268,6 @@ func putAdminScenario(t *testing.T, desc string, url string, routePattern string func adminLogoutUserScenario(t *testing.T, desc string, url string, routePattern string, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - hs := HTTPServer{ Bus: bus.GetBus(), AuthTokenService: auth.NewFakeUserAuthTokenService(), @@ -312,8 +294,6 @@ func adminLogoutUserScenario(t *testing.T, desc string, url string, routePattern func adminRevokeUserAuthTokenScenario(t *testing.T, desc string, url string, routePattern string, cmd models.RevokeAuthTokenCmd, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - fakeAuthTokenService := auth.NewFakeUserAuthTokenService() hs := HTTPServer{ @@ -343,8 +323,6 @@ func adminRevokeUserAuthTokenScenario(t *testing.T, desc string, url string, rou func adminGetUserAuthTokensScenario(t *testing.T, desc string, url string, routePattern string, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - fakeAuthTokenService := auth.NewFakeUserAuthTokenService() hs := HTTPServer{ @@ -372,8 +350,6 @@ func adminGetUserAuthTokensScenario(t *testing.T, desc string, url string, route func adminDisableUserScenario(t *testing.T, desc string, action string, url string, routePattern string, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - fakeAuthTokenService := auth.NewFakeUserAuthTokenService() authInfoService := &logintest.AuthInfoServiceFake{} @@ -410,8 +386,6 @@ func adminDeleteUserScenario(t *testing.T, desc string, url string, routePattern SQLStore: mockstore.NewSQLStoreMock(), } t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - sc := setupScenarioContext(t, url) sc.sqlStore = hs.SQLStore sc.authInfoService = &logintest.AuthInfoServiceFake{} @@ -430,8 +404,6 @@ func adminDeleteUserScenario(t *testing.T, desc string, url string, routePattern func adminCreateUserScenario(t *testing.T, desc string, url string, routePattern string, cmd dtos.AdminCreateUserForm, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - hs := HTTPServer{ Bus: bus.GetBus(), Login: loginservice.LoginServiceMock{ diff --git a/pkg/api/alerting_test.go b/pkg/api/alerting_test.go index 1f09ca06a19..12deadcc9d5 100644 --- a/pkg/api/alerting_test.go +++ b/pkg/api/alerting_test.go @@ -9,7 +9,6 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/search" @@ -124,18 +123,12 @@ func TestAlertingAPIEndpoint(t *testing.T) { } func callPauseAlert(sc *scenarioContext) { - bus.AddHandler("test", func(ctx context.Context, cmd *models.PauseAlertCommand) error { - return nil - }) - sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() } func postAlertScenario(t *testing.T, hs *HTTPServer, desc string, url string, routePattern string, role models.RoleType, cmd dtos.PauseAlertCommand, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - sc := setupScenarioContext(t, url) sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { c.Req.Body = mockRequestBody(cmd) diff --git a/pkg/api/annotations_test.go b/pkg/api/annotations_test.go index 30b0af8b746..300a751454a 100644 --- a/pkg/api/annotations_test.go +++ b/pkg/api/annotations_test.go @@ -13,7 +13,6 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/routing" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/annotations" @@ -293,8 +292,6 @@ var fakeAnnoRepo *fakeAnnotationsRepo func postAnnotationScenario(t *testing.T, desc string, url string, routePattern string, role models.RoleType, cmd dtos.PostAnnotationsCmd, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - hs := setupSimpleHTTPServer(nil) store := sqlstore.InitTestDB(t) store.Cfg = hs.Cfg @@ -324,8 +321,6 @@ func postAnnotationScenario(t *testing.T, desc string, url string, routePattern func putAnnotationScenario(t *testing.T, desc string, url string, routePattern string, role models.RoleType, cmd dtos.UpdateAnnotationsCmd, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - hs := setupSimpleHTTPServer(nil) store := sqlstore.InitTestDB(t) store.Cfg = hs.Cfg @@ -354,8 +349,6 @@ func putAnnotationScenario(t *testing.T, desc string, url string, routePattern s func patchAnnotationScenario(t *testing.T, desc string, url string, routePattern string, role models.RoleType, cmd dtos.PatchAnnotationsCmd, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - hs := setupSimpleHTTPServer(nil) store := sqlstore.InitTestDB(t) store.Cfg = hs.Cfg @@ -385,8 +378,6 @@ func patchAnnotationScenario(t *testing.T, desc string, url string, routePattern func deleteAnnotationsScenario(t *testing.T, desc string, url string, routePattern string, role models.RoleType, cmd dtos.MassDeleteAnnotationsCmd, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - hs := setupSimpleHTTPServer(nil) store := sqlstore.InitTestDB(t) store.Cfg = hs.Cfg diff --git a/pkg/api/common_test.go b/pkg/api/common_test.go index f1870cca517..41ccf6ddd1c 100644 --- a/pkg/api/common_test.go +++ b/pkg/api/common_test.go @@ -53,8 +53,6 @@ func loggedInUserScenario(t *testing.T, desc string, url string, routePattern st func loggedInUserScenarioWithRole(t *testing.T, desc string, method string, url string, routePattern string, role models.RoleType, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - sc := setupScenarioContext(t, url) sc.sqlStore = sqlStore sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { @@ -82,8 +80,6 @@ func loggedInUserScenarioWithRole(t *testing.T, desc string, method string, url func anonymousUserScenario(t *testing.T, desc string, method string, url string, routePattern string, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - sc := setupScenarioContext(t, url) sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.context = c diff --git a/pkg/api/dashboard_snapshot_test.go b/pkg/api/dashboard_snapshot_test.go index a6d1bcef985..d34d285c46d 100644 --- a/pkg/api/dashboard_snapshot_test.go +++ b/pkg/api/dashboard_snapshot_test.go @@ -1,7 +1,6 @@ package api import ( - "context" "fmt" "net/http" "net/http/httptest" @@ -9,7 +8,6 @@ import ( "testing" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/dashboardsnapshots" @@ -52,12 +50,6 @@ func TestDashboardSnapshotAPIEndpoint_singleSnapshot(t *testing.T) { sqlmock.ExpectedDashboardAclInfoList = aclMockResp sqlmock.ExpectedTeamsByUser = []*models.TeamDTO{} - // we need it here for now for the guadian service to work - bus.AddHandler("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error { - query.Result = aclMockResp - return nil - }) - return mockSnapshotResult } diff --git a/pkg/api/dashboard_test.go b/pkg/api/dashboard_test.go index 54b77fbb520..24ec9479b2d 100644 --- a/pkg/api/dashboard_test.go +++ b/pkg/api/dashboard_test.go @@ -957,31 +957,17 @@ func (hs *HTTPServer) callGetDashboard(sc *scenarioContext) { } func (hs *HTTPServer) callGetDashboardVersion(sc *scenarioContext) { - bus.AddHandler("test", func(ctx context.Context, query *models.GetDashboardVersionQuery) error { - query.Result = &models.DashboardVersion{} - return nil - }) - sc.handlerFunc = hs.GetDashboardVersion sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() } func (hs *HTTPServer) callGetDashboardVersions(sc *scenarioContext) { - bus.AddHandler("test", func(ctx context.Context, query *models.GetDashboardVersionsQuery) error { - query.Result = []*models.DashboardVersionDTO{} - return nil - }) - sc.handlerFunc = hs.GetDashboardVersions sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() } func (hs *HTTPServer) callDeleteDashboardByUID(t *testing.T, sc *scenarioContext, mockDashboard *dashboards.FakeDashboardService) { - bus.AddHandler("test", func(ctx context.Context, cmd *models.DeleteDashboardCommand) error { - return nil - }) - hs.dashboardService = mockDashboard sc.handlerFunc = hs.DeleteDashboardByUID sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec() @@ -1003,8 +989,6 @@ func callPostDashboardShouldReturnSuccess(sc *scenarioContext) { func postDashboardScenario(t *testing.T, desc string, url string, routePattern string, cmd models.SaveDashboardCommand, dashboardService dashboards.DashboardService, folderService dashboards.FolderService, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - cfg := setting.NewCfg() hs := HTTPServer{ Bus: bus.GetBus(), @@ -1040,8 +1024,6 @@ func postDashboardScenario(t *testing.T, desc string, url string, routePattern s func postDiffScenario(t *testing.T, desc string, url string, routePattern string, cmd dtos.CalculateDiffOptions, role models.RoleType, fn scenarioFunc, sqlmock sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - cfg := setting.NewCfg() hs := HTTPServer{ Cfg: cfg, @@ -1076,8 +1058,6 @@ func postDiffScenario(t *testing.T, desc string, url string, routePattern string func restoreDashboardVersionScenario(t *testing.T, desc string, url string, routePattern string, mock *dashboards.FakeDashboardService, cmd dtos.RestoreDashboardVersionCommand, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - cfg := setting.NewCfg() mockSQLStore := mockstore.NewSQLStoreMock() hs := HTTPServer{ diff --git a/pkg/api/folder_permission_test.go b/pkg/api/folder_permission_test.go index 18b45c069cb..9198f15e55b 100644 --- a/pkg/api/folder_permission_test.go +++ b/pkg/api/folder_permission_test.go @@ -15,7 +15,6 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/routing" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/dashboards" service "github.com/grafana/grafana/pkg/services/dashboards/manager" @@ -355,8 +354,6 @@ func callUpdateFolderPermissions(t *testing.T, sc *scenarioContext) { func updateFolderPermissionScenario(t *testing.T, ctx updatePermissionContext, hs *HTTPServer) { t.Run(fmt.Sprintf("%s %s", ctx.desc, ctx.url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - sc := setupScenarioContext(t, ctx.url) sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { diff --git a/pkg/api/folder_test.go b/pkg/api/folder_test.go index e61f232c1f3..aa437ea2cf5 100644 --- a/pkg/api/folder_test.go +++ b/pkg/api/folder_test.go @@ -138,8 +138,6 @@ func callCreateFolder(sc *scenarioContext) { func createFolderScenario(t *testing.T, desc string, url string, routePattern string, folderService dashboards.FolderService, cmd models.CreateFolderCommand, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - hs := HTTPServer{ Bus: bus.GetBus(), Cfg: setting.NewCfg(), @@ -170,8 +168,6 @@ func callUpdateFolder(sc *scenarioContext) { func updateFolderScenario(t *testing.T, desc string, url string, routePattern string, folderService dashboards.FolderService, cmd models.UpdateFolderCommand, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - hs := HTTPServer{ Cfg: setting.NewCfg(), folderService: folderService, diff --git a/pkg/api/pluginproxy/ds_proxy_test.go b/pkg/api/pluginproxy/ds_proxy_test.go index 370cf09883f..9af527368de 100644 --- a/pkg/api/pluginproxy/ds_proxy_test.go +++ b/pkg/api/pluginproxy/ds_proxy_test.go @@ -462,19 +462,6 @@ func TestDataSourceProxy_routeRule(t *testing.T) { }) t.Run("When proxying a datasource that has OAuth token pass-through enabled", func(t *testing.T) { - bus.AddHandler("test", func(ctx context.Context, query *models.GetAuthInfoQuery) error { - query.Result = &models.UserAuth{ - Id: 1, - UserId: 1, - AuthModule: "generic_oauth", - OAuthAccessToken: "testtoken", - OAuthRefreshToken: "testrefreshtoken", - OAuthTokenType: "Bearer", - OAuthExpiry: time.Now().AddDate(0, 0, 1), - } - return nil - }) - ds := &models.DataSource{ Type: "custom-datasource", Url: "http://host/root/", diff --git a/pkg/api/plugins_test.go b/pkg/api/plugins_test.go index 8c8674fd6c4..3504d51e4cf 100644 --- a/pkg/api/plugins_test.go +++ b/pkg/api/plugins_test.go @@ -15,7 +15,6 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/grafana-plugin-sdk-go/backend" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" @@ -218,8 +217,6 @@ func callGetPluginAsset(sc *scenarioContext) { func pluginAssetScenario(t *testing.T, desc string, url string, urlPattern string, pluginStore plugins.Store, logger log.Logger, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - hs := HTTPServer{ Cfg: setting.NewCfg(), pluginStore: pluginStore, diff --git a/pkg/api/short_url_test.go b/pkg/api/short_url_test.go index 752004738f2..bb592a9d30a 100644 --- a/pkg/api/short_url_test.go +++ b/pkg/api/short_url_test.go @@ -9,7 +9,6 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/routing" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/shorturls" @@ -54,8 +53,6 @@ func callCreateShortURL(sc *scenarioContext) { func createShortURLScenario(t *testing.T, desc string, url string, routePattern string, cmd dtos.CreateShortURLCmd, shortURLService shorturls.Service, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - defer bus.ClearBusHandlers() - hs := HTTPServer{ Cfg: setting.NewCfg(), ShortURLService: shortURLService, diff --git a/pkg/api/user_test.go b/pkg/api/user_test.go index bc4df9b7ec9..fbf77357ad7 100644 --- a/pkg/api/user_test.go +++ b/pkg/api/user_test.go @@ -107,25 +107,6 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) { }, mock) loggedInUserScenario(t, "When calling GET on", "/api/users/lookup", "/api/users/lookup", func(sc *scenarioContext) { - fakeNow := time.Date(2019, 2, 11, 17, 30, 40, 0, time.UTC) - bus.AddHandler("test", func(ctx context.Context, query *models.GetUserByLoginQuery) error { - require.Equal(t, "danlee", query.LoginOrEmail) - - query.Result = &models.User{ - Id: int64(1), - Email: "daniel@grafana.com", - Name: "Daniel", - Login: "danlee", - Theme: "light", - IsAdmin: true, - OrgId: int64(2), - IsDisabled: false, - Updated: fakeNow, - Created: fakeNow, - } - - return nil - }) createUserCmd := models.CreateUserCommand{ Email: fmt.Sprint("admin", "@test.com"), Name: "admin", diff --git a/pkg/api/user_token_test.go b/pkg/api/user_token_test.go index 37766385f13..4a07a6b737e 100644 --- a/pkg/api/user_token_test.go +++ b/pkg/api/user_token_test.go @@ -79,11 +79,6 @@ func TestUserTokenAPIEndpoint(t *testing.T) { token := &models.UserToken{Id: 2} mock := mockstore.NewSQLStoreMock() revokeUserAuthTokenInternalScenario(t, "Should not be successful", cmd, testUserID, token, func(sc *scenarioContext) { - bus.AddHandler("test", func(ctx context.Context, cmd *models.GetUserByIdQuery) error { - cmd.Result = &models.User{Id: testUserID} - return nil - }) - sc.userAuthTokenService.GetUserTokenProvider = func(ctx context.Context, userId, userTokenId int64) (*models.UserToken, error) { return token, nil } @@ -153,8 +148,6 @@ func TestUserTokenAPIEndpoint(t *testing.T) { func revokeUserAuthTokenScenario(t *testing.T, desc string, url string, routePattern string, cmd models.RevokeAuthTokenCmd, userId int64, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - fakeAuthTokenService := auth.NewFakeUserAuthTokenService() hs := HTTPServer{ @@ -183,8 +176,6 @@ func revokeUserAuthTokenScenario(t *testing.T, desc string, url string, routePat func getUserAuthTokensScenario(t *testing.T, desc string, url string, routePattern string, userId int64, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - fakeAuthTokenService := auth.NewFakeUserAuthTokenService() hs := HTTPServer{ @@ -212,8 +203,6 @@ func getUserAuthTokensScenario(t *testing.T, desc string, url string, routePatte func logoutUserFromAllDevicesInternalScenario(t *testing.T, desc string, userId int64, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(desc, func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - hs := HTTPServer{ Bus: bus.GetBus(), AuthTokenService: auth.NewFakeUserAuthTokenService(), @@ -239,8 +228,6 @@ func logoutUserFromAllDevicesInternalScenario(t *testing.T, desc string, userId func revokeUserAuthTokenInternalScenario(t *testing.T, desc string, cmd models.RevokeAuthTokenCmd, userId int64, token *models.UserToken, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(desc, func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - fakeAuthTokenService := auth.NewFakeUserAuthTokenService() hs := HTTPServer{ @@ -267,8 +254,6 @@ func revokeUserAuthTokenInternalScenario(t *testing.T, desc string, cmd models.R func getUserAuthTokensInternalScenario(t *testing.T, desc string, token *models.UserToken, fn scenarioFunc, sqlStore sqlstore.Store) { t.Run(desc, func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - fakeAuthTokenService := auth.NewFakeUserAuthTokenService() hs := HTTPServer{ diff --git a/pkg/bus/bus.go b/pkg/bus/bus.go index e3f207ef814..28fdc4b002e 100644 --- a/pkg/bus/bus.go +++ b/pkg/bus/bus.go @@ -21,41 +21,17 @@ type Msg interface{} // ErrHandlerNotFound defines an error if a handler is not found var ErrHandlerNotFound = errors.New("handler not found") -// TransactionManager defines a transaction interface -type TransactionManager interface { - InTransaction(ctx context.Context, fn func(ctx context.Context) error) error -} - // Bus type defines the bus interface structure type Bus interface { - Dispatch(ctx context.Context, msg Msg) error - Publish(ctx context.Context, msg Msg) error - - // InTransaction starts a transaction and store it in the context. - // The caller can then pass a function with multiple DispatchCtx calls that - // all will be executed in the same transaction. InTransaction will rollback if the - // callback returns an error. - InTransaction(ctx context.Context, fn func(ctx context.Context) error) error - - AddHandler(handler HandlerFunc) - AddEventListener(handler HandlerFunc) - - // SetTransactionManager allows the user to replace the internal - // noop TransactionManager that is responsible for managing - // transactions in `InTransaction` - SetTransactionManager(tm TransactionManager) } // InProcBus defines the bus structure type InProcBus struct { logger log.Logger - handlers map[string]HandlerFunc - handlersWithCtx map[string]HandlerFunc listeners map[string][]HandlerFunc listenersWithCtx map[string][]HandlerFunc - txMng TransactionManager tracer tracing.Tracer } @@ -64,11 +40,6 @@ func ProvideBus(tracer tracing.Tracer) *InProcBus { return globalBus } -// InTransaction defines an in transaction function -func (b *InProcBus) InTransaction(ctx context.Context, fn func(ctx context.Context) error) error { - return b.txMng.InTransaction(ctx, fn) -} - // temp stuff, not sure how to handle bus instance, and init yet var globalBus = New() @@ -76,11 +47,8 @@ var globalBus = New() func New() *InProcBus { bus := &InProcBus{ logger: log.New("bus"), - handlers: make(map[string]HandlerFunc), - handlersWithCtx: make(map[string]HandlerFunc), listeners: make(map[string][]HandlerFunc), listenersWithCtx: make(map[string][]HandlerFunc), - txMng: &noopTransactionManager{}, } bus.tracer = tracing.InitializeForBus() return bus @@ -91,46 +59,6 @@ func GetBus() Bus { return globalBus } -// SetTransactionManager function assign a transaction manager to the bus. -func (b *InProcBus) SetTransactionManager(tm TransactionManager) { - b.txMng = tm -} - -// DispatchCtx function dispatch a message to the bus context. -func (b *InProcBus) Dispatch(ctx context.Context, msg Msg) error { - var msgName = reflect.TypeOf(msg).Elem().Name() - - ctx, span := b.tracer.Start(ctx, "bus - "+msgName) - defer span.End() - - span.SetAttributes("msg", msgName, attribute.Key("msg").String(msgName)) - - withCtx := true - var handler = b.handlersWithCtx[msgName] - if handler == nil { - withCtx = false - handler = b.handlers[msgName] - if handler == nil { - return ErrHandlerNotFound - } - } - - var params = []reflect.Value{} - if withCtx { - params = append(params, reflect.ValueOf(ctx)) - } else if setting.Env == setting.Dev { - b.logger.Warn("DispatchCtx called with message handler registered using AddHandler and should be changed to use AddHandler", "msgName", msgName) - } - params = append(params, reflect.ValueOf(msg)) - - ret := reflect.ValueOf(handler).Call(params) - err := ret[0].Interface() - if err == nil { - return nil - } - return err.(error) -} - // PublishCtx function publish a message to the bus listener. func (b *InProcBus) Publish(ctx context.Context, msg Msg) error { var msgName = reflect.TypeOf(msg).Elem().Name() @@ -176,17 +104,6 @@ func callListeners(listeners []HandlerFunc, params []reflect.Value) error { return nil } -func (b *InProcBus) AddHandler(handler HandlerFunc) { - handlerType := reflect.TypeOf(handler) - queryTypeName := handlerType.In(1).Elem().Name() - b.handlersWithCtx[queryTypeName] = handler -} - -// GetHandlerCtx returns the handler function for the given struct name. -func (b *InProcBus) GetHandlerCtx(name string) HandlerFunc { - return b.handlersWithCtx[name] -} - func (b *InProcBus) AddEventListener(handler HandlerFunc) { handlerType := reflect.TypeOf(handler) eventName := handlerType.In(1).Elem().Name() @@ -197,36 +114,12 @@ func (b *InProcBus) AddEventListener(handler HandlerFunc) { b.listenersWithCtx[eventName] = append(b.listenersWithCtx[eventName], handler) } -// AddHandler attaches a handler function to the global bus context. -// Package level function. -func AddHandler(implName string, handler HandlerFunc) { - globalBus.AddHandler(handler) -} - // AddEventListenerCtx attaches a handler function to the event listener. // Package level function. func AddEventListener(handler HandlerFunc) { globalBus.AddEventListener(handler) } -func Dispatch(ctx context.Context, msg Msg) error { - return globalBus.Dispatch(ctx, msg) -} - func Publish(ctx context.Context, msg Msg) error { return globalBus.Publish(ctx, msg) } - -func GetHandlerCtx(name string) HandlerFunc { - return globalBus.GetHandlerCtx(name) -} - -func ClearBusHandlers() { - globalBus = New() -} - -type noopTransactionManager struct{} - -func (*noopTransactionManager) InTransaction(ctx context.Context, fn func(ctx context.Context) error) error { - return fn(ctx) -} diff --git a/pkg/bus/bus_test.go b/pkg/bus/bus_test.go index 05789ef1f8b..3bb6a6bb86e 100644 --- a/pkg/bus/bus_test.go +++ b/pkg/bus/bus_test.go @@ -2,7 +2,6 @@ package bus import ( "context" - "errors" "testing" "github.com/grafana/grafana/pkg/infra/tracing" @@ -14,140 +13,6 @@ type testQuery struct { Resp string } -func TestDispatch(t *testing.T) { - bus := New() - tracer, err := tracing.InitializeTracerForTest() - require.NoError(t, err) - bus.tracer = tracer - - var invoked bool - - bus.AddHandler(func(ctx context.Context, query *testQuery) error { - invoked = true - return nil - }) - - require.NoError(t, err) - err = bus.Dispatch(context.Background(), &testQuery{}) - require.NoError(t, err) - - require.True(t, invoked, "expected handler to be called") -} - -func TestDispatch_NoRegisteredHandler(t *testing.T) { - bus := New() - tracer, err := tracing.InitializeTracerForTest() - require.NoError(t, err) - bus.tracer = tracer - - err = bus.Dispatch(context.Background(), &testQuery{}) - require.Equal(t, err, ErrHandlerNotFound, - "expected bus to return HandlerNotFound since no handler is registered") -} - -func TestDispatch_ContextHandler(t *testing.T) { - bus := New() - tracer, err := tracing.InitializeTracerForTest() - require.NoError(t, err) - bus.tracer = tracer - - var invoked bool - - bus.AddHandler(func(ctx context.Context, query *testQuery) error { - invoked = true - return nil - }) - - err = bus.Dispatch(context.Background(), &testQuery{}) - require.NoError(t, err) - - require.True(t, invoked, "expected handler to be called") -} - -func TestDispatchCtx(t *testing.T) { - bus := New() - tracer, err := tracing.InitializeTracerForTest() - require.NoError(t, err) - bus.tracer = tracer - - var invoked bool - - bus.AddHandler(func(ctx context.Context, query *testQuery) error { - invoked = true - return nil - }) - - err = bus.Dispatch(context.Background(), &testQuery{}) - require.NoError(t, err) - - require.True(t, invoked, "expected handler to be called") -} - -func TestDispatchCtx_NoContextHandler(t *testing.T) { - bus := New() - tracer, err := tracing.InitializeTracerForTest() - require.NoError(t, err) - bus.tracer = tracer - - var invoked bool - - bus.AddHandler(func(ctx context.Context, query *testQuery) error { - invoked = true - return nil - }) - - err = bus.Dispatch(context.Background(), &testQuery{}) - require.NoError(t, err) - - require.True(t, invoked, "expected handler to be called") -} - -func TestDispatchCtx_NoRegisteredHandler(t *testing.T) { - bus := New() - tracer, err := tracing.InitializeTracerForTest() - require.NoError(t, err) - bus.tracer = tracer - - err = bus.Dispatch(context.Background(), &testQuery{}) - require.Equal(t, err, ErrHandlerNotFound, - "expected bus to return HandlerNotFound since no handler is registered") -} - -func TestQuery(t *testing.T) { - bus := New() - tracer, err := tracing.InitializeTracerForTest() - require.NoError(t, err) - bus.tracer = tracer - - want := "hello from handler" - - bus.AddHandler(func(ctx context.Context, q *testQuery) error { - q.Resp = want - return nil - }) - - q := &testQuery{} - - err = bus.Dispatch(context.Background(), q) - require.NoError(t, err, "unable to dispatch query") - - require.Equal(t, want, q.Resp) -} - -func TestQuery_HandlerReturnsError(t *testing.T) { - bus := New() - tracer, err := tracing.InitializeTracerForTest() - require.NoError(t, err) - bus.tracer = tracer - - bus.AddHandler(func(ctx context.Context, query *testQuery) error { - return errors.New("handler error") - }) - - err = bus.Dispatch(context.Background(), &testQuery{}) - require.Error(t, err, "expected error but got none") -} - func TestEventPublish(t *testing.T) { bus := New() tracer, err := tracing.InitializeTracerForTest() diff --git a/pkg/expr/service_test.go b/pkg/expr/service_test.go index 0449a98a4cc..6741174baad 100644 --- a/pkg/expr/service_test.go +++ b/pkg/expr/service_test.go @@ -10,8 +10,6 @@ import ( "github.com/google/go-cmp/cmp" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/data" - "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/secrets/fakes" secretsManager "github.com/grafana/grafana/pkg/services/secrets/manager" @@ -38,11 +36,6 @@ func TestService(t *testing.T) { secretsService: secretsService, } - bus.AddHandler("test", func(_ context.Context, query *models.GetDataSourceQuery) error { - query.Result = &models.DataSource{Uid: "1", OrgId: 1, Type: "test", JsonData: simplejson.New()} - return nil - }) - queries := []Query{ { RefID: "A", diff --git a/pkg/login/auth.go b/pkg/login/auth.go index ae76ee3bec5..d75b1cd8ad2 100644 --- a/pkg/login/auth.go +++ b/pkg/login/auth.go @@ -4,7 +4,6 @@ import ( "context" "errors" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/ldap" @@ -41,7 +40,6 @@ func ProvideService(store sqlstore.Store, loginService login.Service) *Authentic store: store, loginService: loginService, } - bus.AddHandler("auth", a.AuthenticateUser) return a } diff --git a/pkg/middleware/middleware_basic_auth_test.go b/pkg/middleware/middleware_basic_auth_test.go index dda1b609269..5836a0d315b 100644 --- a/pkg/middleware/middleware_basic_auth_test.go +++ b/pkg/middleware/middleware_basic_auth_test.go @@ -1,11 +1,9 @@ package middleware import ( - "context" "encoding/json" "testing" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/contexthandler" @@ -42,22 +40,8 @@ func TestMiddlewareBasicAuth(t *testing.T) { middlewareScenario(t, "Handle auth", func(t *testing.T, sc *scenarioContext) { const password = "MyPass" - const salt = "Salt" const orgID int64 = 2 - bus.AddHandler("grafana-auth", func(ctx context.Context, query *models.LoginUserQuery) error { - t.Log("Handling LoginUserQuery") - encoded, err := util.EncodePassword(password, salt) - if err != nil { - return err - } - query.User = &models.User{ - Password: encoded, - Salt: salt, - } - return nil - }) - sc.mockSQLStore.ExpectedSignedInUser = &models.SignedInUser{OrgId: orgID, UserId: id} authHeader := util.GetBasicAuthHeader("myUser", password) diff --git a/pkg/middleware/middleware_jwt_auth_test.go b/pkg/middleware/middleware_jwt_auth_test.go index 02d4075201d..31403464d69 100644 --- a/pkg/middleware/middleware_jwt_auth_test.go +++ b/pkg/middleware/middleware_jwt_auth_test.go @@ -7,7 +7,6 @@ import ( "github.com/stretchr/testify/assert" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/contexthandler" "github.com/grafana/grafana/pkg/setting" @@ -109,14 +108,6 @@ func TestMiddlewareJWTAuth(t *testing.T) { }, nil } sc.mockSQLStore.ExpectedSignedInUser = &models.SignedInUser{UserId: id, OrgId: orgID, Email: myEmail} - bus.AddHandler("upsert-user", func(ctx context.Context, command *models.UpsertUserCommand) error { - command.Result = &models.User{ - Id: id, - Name: command.ExternalUser.Name, - Email: command.ExternalUser.Email, - } - return nil - }) sc.fakeReq("GET", "/").withJWTAuthHeader(token).exec() assert.Equal(t, verifiedToken, token) diff --git a/pkg/middleware/middleware_test.go b/pkg/middleware/middleware_test.go index b52083dbeed..76dbd87b1be 100644 --- a/pkg/middleware/middleware_test.go +++ b/pkg/middleware/middleware_test.go @@ -14,7 +14,6 @@ import ( "github.com/grafana/grafana-plugin-sdk-go/backend/gtime" "github.com/grafana/grafana/pkg/api/dtos" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/fs" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/remotecache" @@ -570,8 +569,6 @@ func middlewareScenario(t *testing.T, desc string, fn scenarioFunc, cbs ...func( t.Helper() t.Run(desc, func(t *testing.T) { - t.Cleanup(bus.ClearBusHandlers) - logger := log.New("test") loginMaxLifetime, err := gtime.ParseDuration("30d") diff --git a/pkg/middleware/org_redirect_test.go b/pkg/middleware/org_redirect_test.go index 22450ec880e..f943d12bd0a 100644 --- a/pkg/middleware/org_redirect_test.go +++ b/pkg/middleware/org_redirect_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/stretchr/testify/require" ) @@ -47,10 +46,6 @@ func TestOrgRedirectMiddleware(t *testing.T) { middlewareScenario(t, tc.desc, func(t *testing.T, sc *scenarioContext) { sc.withTokenSessionCookie("token") sc.mockSQLStore.ExpectedSignedInUser = &models.SignedInUser{OrgId: 1, UserId: 12} - bus.AddHandler("test", func(ctx context.Context, query *models.SetUsingOrgCommand) error { - return nil - }) - sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*models.UserToken, error) { return &models.UserToken{ UserId: 0, diff --git a/pkg/middleware/recovery_test.go b/pkg/middleware/recovery_test.go index 7e3e4a5939f..251558056dc 100644 --- a/pkg/middleware/recovery_test.go +++ b/pkg/middleware/recovery_test.go @@ -5,7 +5,6 @@ import ( "strings" "testing" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" @@ -48,8 +47,6 @@ func panicHandler(c *models.ReqContext) { func recoveryScenario(t *testing.T, desc string, url string, fn scenarioFunc) { t.Run(desc, func(t *testing.T) { - defer bus.ClearBusHandlers() - cfg := setting.NewCfg() cfg.ErrTemplateName = "error-template" sc := &scenarioContext{ diff --git a/pkg/services/alerting/notifier_test.go b/pkg/services/alerting/notifier_test.go index 558697083c8..c921908c6b8 100644 --- a/pkg/services/alerting/notifier_test.go +++ b/pkg/services/alerting/notifier_test.go @@ -13,7 +13,6 @@ import ( "github.com/grafana/grafana/pkg/setting" "github.com/stretchr/testify/assert" - "github.com/grafana/grafana/pkg/bus" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/components/imguploader" @@ -205,14 +204,6 @@ func notificationServiceScenario(t *testing.T, name string, evalCtx *EvalContext return nil } - bus.AddHandler("test", func(ctx context.Context, cmd *models.SetAlertNotificationStateToPendingCommand) error { - return nil - }) - - bus.AddHandler("test", func(ctx context.Context, cmd *models.SetAlertNotificationStateToCompleteCommand) error { - return nil - }) - setting.AlertingNotificationTimeout = 30 * time.Second scenarioCtx := &scenarioContext{ diff --git a/pkg/services/alerting/service.go b/pkg/services/alerting/service.go index 5031b4cb9cc..8db32e18728 100644 --- a/pkg/services/alerting/service.go +++ b/pkg/services/alerting/service.go @@ -28,20 +28,6 @@ func ProvideService(bus bus.Bus, store *sqlstore.SQLStore, encryptionService enc NotificationService: notificationService, } - s.Bus.AddHandler(s.GetAlertNotifications) - s.Bus.AddHandler(s.CreateAlertNotificationCommand) - s.Bus.AddHandler(s.UpdateAlertNotification) - s.Bus.AddHandler(s.DeleteAlertNotification) - s.Bus.AddHandler(s.GetAllAlertNotifications) - s.Bus.AddHandler(s.GetOrCreateAlertNotificationState) - s.Bus.AddHandler(s.SetAlertNotificationStateToCompleteCommand) - s.Bus.AddHandler(s.SetAlertNotificationStateToPendingCommand) - s.Bus.AddHandler(s.GetAlertNotificationsWithUid) - s.Bus.AddHandler(s.UpdateAlertNotificationWithUid) - s.Bus.AddHandler(s.DeleteAlertNotificationWithUid) - s.Bus.AddHandler(s.GetAlertNotificationsWithUidToSend) - s.Bus.AddHandler(s.HandleNotificationTestCommand) - return s } diff --git a/pkg/services/dashboards/manager/dashboard_service_test.go b/pkg/services/dashboards/manager/dashboard_service_test.go index 7e303d70471..b1a11805674 100644 --- a/pkg/services/dashboards/manager/dashboard_service_test.go +++ b/pkg/services/dashboards/manager/dashboard_service_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" @@ -22,8 +21,6 @@ import ( func TestDashboardService(t *testing.T) { t.Run("Dashboard service tests", func(t *testing.T) { - bus.ClearBusHandlers() - fakeStore := m.FakeDashboardStore{} defer fakeStore.AssertExpectations(t) service := &DashboardServiceImpl{ diff --git a/pkg/services/dashboardsnapshots/dashboardsnapshots.go b/pkg/services/dashboardsnapshots/dashboardsnapshots.go index 990e60bb818..88745a181ed 100644 --- a/pkg/services/dashboardsnapshots/dashboardsnapshots.go +++ b/pkg/services/dashboardsnapshots/dashboardsnapshots.go @@ -23,12 +23,6 @@ func ProvideService(bus bus.Bus, store sqlstore.Store, secretsService secrets.Se SecretsService: secretsService, } - s.Bus.AddHandler(s.CreateDashboardSnapshot) - s.Bus.AddHandler(s.GetDashboardSnapshot) - s.Bus.AddHandler(s.DeleteDashboardSnapshot) - s.Bus.AddHandler(s.SearchDashboardSnapshots) - s.Bus.AddHandler(s.DeleteExpiredSnapshots) - return s } diff --git a/pkg/services/datasources/service/datasource_service.go b/pkg/services/datasources/service/datasource_service.go index 52ffe634707..30381852578 100644 --- a/pkg/services/datasources/service/datasource_service.go +++ b/pkg/services/datasources/service/datasource_service.go @@ -79,14 +79,6 @@ func ProvideService( permissionsService: permissionsServices.GetDataSourceService(), } - s.Bus.AddHandler(s.GetDataSources) - s.Bus.AddHandler(s.GetDataSourcesByType) - s.Bus.AddHandler(s.GetDataSource) - s.Bus.AddHandler(s.AddDataSource) - s.Bus.AddHandler(s.DeleteDataSource) - s.Bus.AddHandler(s.UpdateDataSource) - s.Bus.AddHandler(s.GetDefaultDataSource) - ac.RegisterAttributeScopeResolver(NewNameScopeResolver(store)) ac.RegisterAttributeScopeResolver(NewIDScopeResolver(store)) diff --git a/pkg/services/login/authinfoservice/database/database.go b/pkg/services/login/authinfoservice/database/database.go index 5fa3ee4a89e..2ac7ad076e1 100644 --- a/pkg/services/login/authinfoservice/database/database.go +++ b/pkg/services/login/authinfoservice/database/database.go @@ -28,18 +28,9 @@ func ProvideAuthInfoStore(sqlStore sqlstore.Store, bus bus.Bus, secretsService s secretsService: secretsService, logger: log.New("login.authinfo.store"), } - store.registerBusHandlers() return store } -func (s *AuthInfoStore) registerBusHandlers() { - s.bus.AddHandler(s.GetExternalUserInfoByLogin) - s.bus.AddHandler(s.GetAuthInfo) - s.bus.AddHandler(s.SetAuthInfo) - s.bus.AddHandler(s.UpdateAuthInfo) - s.bus.AddHandler(s.DeleteAuthInfo) -} - func (s *AuthInfoStore) GetExternalUserInfoByLogin(ctx context.Context, query *models.GetExternalUserInfoByLoginQuery) error { userQuery := models.GetUserByLoginQuery{LoginOrEmail: query.LoginOrEmail} err := s.sqlStore.GetUserByLogin(ctx, &userQuery) diff --git a/pkg/services/login/loginservice/loginservice.go b/pkg/services/login/loginservice/loginservice.go index db5ccf002cb..a8f4f30837b 100644 --- a/pkg/services/login/loginservice/loginservice.go +++ b/pkg/services/login/loginservice/loginservice.go @@ -23,7 +23,6 @@ func ProvideService(sqlStore sqlstore.Store, bus bus.Bus, quotaService *quota.Qu QuotaService: quotaService, AuthInfoService: authInfoService, } - bus.AddHandler(s.UpsertUser) return s } diff --git a/pkg/services/login/loginservice/loginservice_test.go b/pkg/services/login/loginservice/loginservice_test.go index 4bace3556f9..924506e5845 100644 --- a/pkg/services/login/loginservice/loginservice_test.go +++ b/pkg/services/login/loginservice/loginservice_test.go @@ -80,8 +80,6 @@ func Test_teamSync(t *testing.T) { Login: "test_user", } authInfoMock.ExpectedUser = expectedUser - bus.ClearBusHandlers() - t.Cleanup(func() { bus.ClearBusHandlers() }) var actualUser *models.User var actualExternalUser *models.ExternalUserInfo diff --git a/pkg/services/notifications/notifications.go b/pkg/services/notifications/notifications.go index 221b3223891..7c86ebb8348 100644 --- a/pkg/services/notifications/notifications.go +++ b/pkg/services/notifications/notifications.go @@ -45,13 +45,6 @@ func ProvideService(bus bus.Bus, cfg *setting.Cfg, mailer Mailer, store TempUser store: store, } - ns.Bus.AddHandler(ns.SendResetPasswordEmail) - ns.Bus.AddHandler(ns.ValidateResetPasswordCode) - ns.Bus.AddHandler(ns.SendEmailCommandHandler) - - ns.Bus.AddHandler(ns.SendEmailCommandHandlerSync) - ns.Bus.AddHandler(ns.SendWebhookSync) - ns.Bus.AddEventListener(ns.signUpStartedHandler) ns.Bus.AddEventListener(ns.signUpCompletedHandler) diff --git a/pkg/services/notifications/notifications_test.go b/pkg/services/notifications/notifications_test.go index bd07a4dd291..0244c7df558 100644 --- a/pkg/services/notifications/notifications_test.go +++ b/pkg/services/notifications/notifications_test.go @@ -35,7 +35,7 @@ func TestSendEmailSync(t *testing.T) { bus := bus.New() t.Run("When sending emails synchronously", func(t *testing.T) { - _, mailer := createSut(t, bus) + ns, mailer := createSut(t, bus) cmd := &models.SendEmailCommandSync{ SendEmailCommand: models.SendEmailCommand{ Subject: "subject", @@ -44,8 +44,7 @@ func TestSendEmailSync(t *testing.T) { Template: "welcome_on_signup", }, } - - err := bus.Dispatch(context.Background(), cmd) + err := ns.SendEmailCommandHandlerSync(context.Background(), cmd) require.NoError(t, err) require.NotEmpty(t, mailer.Sent) @@ -55,7 +54,7 @@ func TestSendEmailSync(t *testing.T) { }) t.Run("When using Single Email mode with multiple recipients", func(t *testing.T) { - _, mailer := createSut(t, bus) + ns, mailer := createSut(t, bus) cmd := &models.SendEmailCommandSync{ SendEmailCommand: models.SendEmailCommand{ Subject: "subject", @@ -65,14 +64,14 @@ func TestSendEmailSync(t *testing.T) { }, } - err := bus.Dispatch(context.Background(), cmd) + err := ns.SendEmailCommandHandlerSync(context.Background(), cmd) require.NoError(t, err) require.Len(t, mailer.Sent, 1) }) t.Run("When using Multi Email mode with multiple recipients", func(t *testing.T) { - _, mailer := createSut(t, bus) + ns, mailer := createSut(t, bus) cmd := &models.SendEmailCommandSync{ SendEmailCommand: models.SendEmailCommand{ Subject: "subject", @@ -82,14 +81,14 @@ func TestSendEmailSync(t *testing.T) { }, } - err := bus.Dispatch(context.Background(), cmd) + err := ns.SendEmailCommandHandlerSync(context.Background(), cmd) require.NoError(t, err) require.Len(t, mailer.Sent, 3) }) t.Run("When attaching files to emails", func(t *testing.T) { - _, mailer := createSut(t, bus) + ns, mailer := createSut(t, bus) cmd := &models.SendEmailCommandSync{ SendEmailCommand: models.SendEmailCommand{ Subject: "subject", @@ -105,7 +104,7 @@ func TestSendEmailSync(t *testing.T) { }, } - err := bus.Dispatch(context.Background(), cmd) + err := ns.SendEmailCommandHandlerSync(context.Background(), cmd) require.NoError(t, err) require.NotEmpty(t, mailer.Sent) @@ -119,7 +118,7 @@ func TestSendEmailSync(t *testing.T) { t.Run("When SMTP disabled in configuration", func(t *testing.T) { cfg := createSmtpConfig() cfg.Smtp.Enabled = false - _, mailer, err := createSutWithConfig(t, bus, cfg) + ns, mailer, err := createSutWithConfig(t, bus, cfg) require.NoError(t, err) cmd := &models.SendEmailCommandSync{ SendEmailCommand: models.SendEmailCommand{ @@ -130,7 +129,7 @@ func TestSendEmailSync(t *testing.T) { }, } - err = bus.Dispatch(context.Background(), cmd) + err = ns.SendEmailCommandHandlerSync(context.Background(), cmd) require.ErrorIs(t, err, models.ErrSmtpNotEnabled) require.Empty(t, mailer.Sent) @@ -139,7 +138,7 @@ func TestSendEmailSync(t *testing.T) { t.Run("When invalid content type in configuration", func(t *testing.T) { cfg := createSmtpConfig() cfg.Smtp.ContentTypes = append(cfg.Smtp.ContentTypes, "multipart/form-data") - _, mailer, err := createSutWithConfig(t, bus, cfg) + ns, mailer, err := createSutWithConfig(t, bus, cfg) require.NoError(t, err) cmd := &models.SendEmailCommandSync{ SendEmailCommand: models.SendEmailCommand{ @@ -150,14 +149,14 @@ func TestSendEmailSync(t *testing.T) { }, } - err = bus.Dispatch(context.Background(), cmd) + err = ns.SendEmailCommandHandlerSync(context.Background(), cmd) require.Error(t, err) require.Empty(t, mailer.Sent) }) t.Run("When SMTP dialer is disconnected", func(t *testing.T) { - _ = createDisconnectedSut(t, bus) + ns := createDisconnectedSut(t, bus) cmd := &models.SendEmailCommandSync{ SendEmailCommand: models.SendEmailCommand{ Subject: "subject", @@ -167,7 +166,7 @@ func TestSendEmailSync(t *testing.T) { }, } - err := bus.Dispatch(context.Background(), cmd) + err := ns.SendEmailCommandHandlerSync(context.Background(), cmd) require.Error(t, err) }) @@ -210,7 +209,7 @@ func TestSendEmailAsync(t *testing.T) { t.Run("When invalid content type in configuration", func(t *testing.T) { cfg := createSmtpConfig() cfg.Smtp.ContentTypes = append(cfg.Smtp.ContentTypes, "multipart/form-data") - _, mailer, err := createSutWithConfig(t, bus, cfg) + ns, mailer, err := createSutWithConfig(t, bus, cfg) require.NoError(t, err) cmd := &models.SendEmailCommand{ Subject: "subject", @@ -219,14 +218,14 @@ func TestSendEmailAsync(t *testing.T) { Template: "welcome_on_signup", } - err = bus.Dispatch(context.Background(), cmd) + err = ns.SendEmailCommandHandler(context.Background(), cmd) require.Error(t, err) require.Empty(t, mailer.Sent) }) t.Run("When SMTP dialer is disconnected", func(t *testing.T) { - _ = createDisconnectedSut(t, bus) + ns := createDisconnectedSut(t, bus) cmd := &models.SendEmailCommand{ Subject: "subject", To: []string{"1@grafana.com", "2@grafana.com", "3@grafana.com"}, @@ -234,7 +233,7 @@ func TestSendEmailAsync(t *testing.T) { Template: "welcome_on_signup", } - err := bus.Dispatch(context.Background(), cmd) + err := ns.SendEmailCommandHandler(context.Background(), cmd) // The async version should not surface connection errors via Bus. It should only log them. require.NoError(t, err) diff --git a/pkg/services/plugindashboards/service/dashboard_updater_test.go b/pkg/services/plugindashboards/service/dashboard_updater_test.go index 5648bb613be..05a0e33630e 100644 --- a/pkg/services/plugindashboards/service/dashboard_updater_test.go +++ b/pkg/services/plugindashboards/service/dashboard_updater_test.go @@ -569,8 +569,6 @@ func scenario(t *testing.T, desc string, input scenarioInput, f func(ctx *scenar sCtx.dashboardService, ) - t.Cleanup(bus.ClearBusHandlers) - t.Run(desc, func(t *testing.T) { f(sCtx) }) diff --git a/pkg/services/search/service.go b/pkg/services/search/service.go index d8b3eb2e95a..1656f6ee123 100644 --- a/pkg/services/search/service.go +++ b/pkg/services/search/service.go @@ -21,7 +21,6 @@ func ProvideService(cfg *setting.Cfg, bus bus.Bus, sqlstore *sqlstore.SQLStore) }, sqlstore: sqlstore, } - s.Bus.AddHandler(s.SearchHandler) return s } diff --git a/pkg/services/sqlstore/alert.go b/pkg/services/sqlstore/alert.go index 7e79cb6d24c..d4b07cb64db 100644 --- a/pkg/services/sqlstore/alert.go +++ b/pkg/services/sqlstore/alert.go @@ -7,23 +7,12 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) // timeNow makes it possible to test usage of time var timeNow = time.Now -func (ss *SQLStore) addAlertQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.HandleAlertsQuery) - bus.AddHandler("sql", ss.GetAlertById) - bus.AddHandler("sql", ss.GetAllAlertQueryHandler) - bus.AddHandler("sql", ss.SetAlertState) - bus.AddHandler("sql", ss.GetAlertStatesForDashboard) - bus.AddHandler("sql", ss.PauseAlert) - bus.AddHandler("sql", ss.PauseAllAlerts) -} - func (ss *SQLStore) GetAlertById(ctx context.Context, query *models.GetAlertByIdQuery) error { return ss.WithDbSession(ctx, func(sess *DBSession) error { alert := models.Alert{} diff --git a/pkg/services/sqlstore/alert_notification.go b/pkg/services/sqlstore/alert_notification.go index 0d6bd261415..c8c515e81ee 100644 --- a/pkg/services/sqlstore/alert_notification.go +++ b/pkg/services/sqlstore/alert_notification.go @@ -8,7 +8,6 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/util" ) @@ -79,10 +78,6 @@ func (ss *SQLStore) GetAlertNotifications(ctx context.Context, query *models.Get return getAlertNotificationInternal(ctx, query, newSession(ctx)) } -func (ss *SQLStore) addAlertNotificationUidByIdHandler() { - bus.AddHandler("sql", ss.GetAlertNotificationUidWithId) -} - func (ss *SQLStore) GetAlertNotificationUidWithId(ctx context.Context, query *models.GetAlertNotificationUidQuery) error { cacheKey := newAlertNotificationUidCacheKey(query.OrgId, query.Id) diff --git a/pkg/services/sqlstore/alert_notification_test.go b/pkg/services/sqlstore/alert_notification_test.go index 6fae4142bab..6d2b7a3d9b7 100644 --- a/pkg/services/sqlstore/alert_notification_test.go +++ b/pkg/services/sqlstore/alert_notification_test.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/models" @@ -19,13 +18,7 @@ import ( func TestAlertNotificationSQLAccess(t *testing.T) { var sqlStore *SQLStore - setup := func() { - sqlStore = InitTestDB(t) - // Set up bus handlers - bus.AddHandler("deleteAlertNotification", func(ctx context.Context, cmd *models.DeleteAlertNotificationCommand) error { - return sqlStore.DeleteAlertNotification(ctx, cmd) - }) - } + setup := func() { sqlStore = InitTestDB(t) } t.Run("Alert notification state", func(t *testing.T) { setup() diff --git a/pkg/services/sqlstore/apikey.go b/pkg/services/sqlstore/apikey.go index eb31a56efaf..876d41382d2 100644 --- a/pkg/services/sqlstore/apikey.go +++ b/pkg/services/sqlstore/apikey.go @@ -6,18 +6,9 @@ import ( "xorm.io/xorm" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) -func (ss *SQLStore) addAPIKeysQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.GetAPIKeys) - bus.AddHandler("sql", ss.GetApiKeyById) - bus.AddHandler("sql", ss.GetApiKeyByName) - bus.AddHandler("sql", ss.DeleteApiKey) - bus.AddHandler("sql", ss.AddAPIKey) -} - // GetAPIKeys queries the database based // on input on GetApiKeysQuery func (ss *SQLStore) GetAPIKeys(ctx context.Context, query *models.GetApiKeysQuery) error { diff --git a/pkg/services/sqlstore/dashboard.go b/pkg/services/sqlstore/dashboard.go index c53c577a886..4017e8d8872 100644 --- a/pkg/services/sqlstore/dashboard.go +++ b/pkg/services/sqlstore/dashboard.go @@ -6,7 +6,6 @@ import ( "github.com/prometheus/client_golang/prometheus" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/sqlstore/permissions" @@ -26,18 +25,6 @@ func init() { prometheus.MustRegister(shadowSearchCounter) } -func (ss *SQLStore) addDashboardQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.GetDashboard) - bus.AddHandler("sql", ss.GetDashboardUIDById) - bus.AddHandler("sql", ss.GetDashboardTags) - bus.AddHandler("sql", ss.SearchDashboards) - bus.AddHandler("sql", ss.GetDashboards) - bus.AddHandler("sql", ss.HasEditPermissionInFolders) - bus.AddHandler("sql", ss.GetDashboardPermissionsForUser) - bus.AddHandler("sql", ss.GetDashboardSlugById) - bus.AddHandler("sql", ss.HasAdminPermissionInFolders) -} - var generateNewUid func() string = util.GenerateShortUID func (ss *SQLStore) GetDashboard(ctx context.Context, query *models.GetDashboardQuery) error { diff --git a/pkg/services/sqlstore/dashboard_acl.go b/pkg/services/sqlstore/dashboard_acl.go index bcc04b2a17a..df4a4fcf129 100644 --- a/pkg/services/sqlstore/dashboard_acl.go +++ b/pkg/services/sqlstore/dashboard_acl.go @@ -3,14 +3,9 @@ package sqlstore import ( "context" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) -func (ss *SQLStore) addDashboardACLQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.GetDashboardAclInfoList) -} - // GetDashboardAclInfoList returns a list of permissions for a dashboard. They can be fetched from three // different places. // 1) Permissions for the dashboard diff --git a/pkg/services/sqlstore/dashboard_version.go b/pkg/services/sqlstore/dashboard_version.go index 3c6c6832ef8..e8bd87b6461 100644 --- a/pkg/services/sqlstore/dashboard_version.go +++ b/pkg/services/sqlstore/dashboard_version.go @@ -4,17 +4,10 @@ import ( "context" "strings" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) -func (ss *SQLStore) addDashboardVersionQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.GetDashboardVersion) - bus.AddHandler("sql", ss.GetDashboardVersions) - bus.AddHandler("sql", ss.DeleteExpiredVersions) -} - // GetDashboardVersion gets the dashboard version for the given dashboard ID and version number. func (ss *SQLStore) GetDashboardVersion(ctx context.Context, query *models.GetDashboardVersionQuery) error { return ss.WithDbSession(ctx, func(sess *DBSession) error { diff --git a/pkg/services/sqlstore/login_attempt.go b/pkg/services/sqlstore/login_attempt.go index fbbf85d786b..dd93a249552 100644 --- a/pkg/services/sqlstore/login_attempt.go +++ b/pkg/services/sqlstore/login_attempt.go @@ -5,18 +5,11 @@ import ( "strconv" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) var getTimeNow = time.Now -func (ss *SQLStore) addLoginAttemptQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.CreateLoginAttempt) - bus.AddHandler("sql", ss.DeleteOldLoginAttempts) - bus.AddHandler("sql", ss.GetUserLoginAttemptCount) -} - func (ss *SQLStore) CreateLoginAttempt(ctx context.Context, cmd *models.CreateLoginAttemptCommand) error { return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error { loginAttempt := models.LoginAttempt{ diff --git a/pkg/services/sqlstore/org.go b/pkg/services/sqlstore/org.go index 6cac1cea15f..1cdd72a938a 100644 --- a/pkg/services/sqlstore/org.go +++ b/pkg/services/sqlstore/org.go @@ -5,7 +5,6 @@ import ( "fmt" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/events" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" @@ -15,16 +14,6 @@ import ( // MainOrgName is the name of the main organization. const MainOrgName = "Main Org." -func (ss *SQLStore) addOrgQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.GetOrgById) - bus.AddHandler("sql", CreateOrg) - bus.AddHandler("sql", ss.UpdateOrg) - bus.AddHandler("sql", ss.UpdateOrgAddress) - bus.AddHandler("sql", ss.GetOrgByNameHandler) - bus.AddHandler("sql", ss.SearchOrgs) - bus.AddHandler("sql", ss.DeleteOrg) -} - func (ss *SQLStore) SearchOrgs(ctx context.Context, query *models.SearchOrgsQuery) error { return ss.WithDbSession(ctx, func(dbSession *DBSession) error { query.Result = make([]*models.OrgDTO, 0) diff --git a/pkg/services/sqlstore/org_users.go b/pkg/services/sqlstore/org_users.go index 24f1a9e8119..60d7e5ca8f7 100644 --- a/pkg/services/sqlstore/org_users.go +++ b/pkg/services/sqlstore/org_users.go @@ -6,20 +6,12 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/util" ) -func (ss *SQLStore) addOrgUsersQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.AddOrgUser) - bus.AddHandler("sql", ss.RemoveOrgUser) - bus.AddHandler("sql", ss.GetOrgUsers) - bus.AddHandler("sql", ss.UpdateOrgUser) -} - func (ss *SQLStore) AddOrgUser(ctx context.Context, cmd *models.AddOrgUserCommand) error { return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error { // check if user exists diff --git a/pkg/services/sqlstore/playlist.go b/pkg/services/sqlstore/playlist.go index b0d8e96652d..49f3aa311c8 100644 --- a/pkg/services/sqlstore/playlist.go +++ b/pkg/services/sqlstore/playlist.go @@ -3,19 +3,9 @@ package sqlstore import ( "context" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) -func (ss *SQLStore) addPlaylistQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.CreatePlaylist) - bus.AddHandler("sql", ss.UpdatePlaylist) - bus.AddHandler("sql", ss.DeletePlaylist) - bus.AddHandler("sql", ss.SearchPlaylists) - bus.AddHandler("sql", ss.GetPlaylist) - bus.AddHandler("sql", ss.GetPlaylistItem) -} - func (ss *SQLStore) CreatePlaylist(ctx context.Context, cmd *models.CreatePlaylistCommand) error { return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error { playlist := models.Playlist{ diff --git a/pkg/services/sqlstore/preferences.go b/pkg/services/sqlstore/preferences.go index 1fccba8adc3..da3a5388ef1 100644 --- a/pkg/services/sqlstore/preferences.go +++ b/pkg/services/sqlstore/preferences.go @@ -5,17 +5,9 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) -func (ss *SQLStore) addPreferencesQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.GetPreferences) - bus.AddHandler("sql", ss.GetPreferencesWithDefaults) - bus.AddHandler("sql", ss.SavePreferences) - bus.AddHandler("sql", ss.PatchPreferences) -} - func (ss *SQLStore) GetPreferencesWithDefaults(ctx context.Context, query *models.GetPreferencesWithDefaultsQuery) error { return ss.WithDbSession(ctx, func(dbSession *DBSession) error { params := make([]interface{}, 0) diff --git a/pkg/services/sqlstore/quota.go b/pkg/services/sqlstore/quota.go index abc0c39b98c..3ed4428fa71 100644 --- a/pkg/services/sqlstore/quota.go +++ b/pkg/services/sqlstore/quota.go @@ -5,7 +5,6 @@ import ( "fmt" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) @@ -15,16 +14,6 @@ const ( dashboardTarget = "dashboard" ) -func (ss *SQLStore) addQuotaQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.GetOrgQuotaByTarget) - bus.AddHandler("sql", ss.GetOrgQuotas) - bus.AddHandler("sql", ss.UpdateOrgQuota) - bus.AddHandler("sql", ss.GetUserQuotaByTarget) - bus.AddHandler("sql", ss.GetUserQuotas) - bus.AddHandler("sql", ss.UpdateUserQuota) - bus.AddHandler("sql", ss.GetGlobalQuotaByTarget) -} - type targetCount struct { Count int64 } diff --git a/pkg/services/sqlstore/sqlstore.go b/pkg/services/sqlstore/sqlstore.go index 792ce846329..ca6ec8d6135 100644 --- a/pkg/services/sqlstore/sqlstore.go +++ b/pkg/services/sqlstore/sqlstore.go @@ -111,28 +111,6 @@ func newSQLStore(cfg *setting.Cfg, cacheService *localcache.CacheService, b bus. // Init repo instances annotations.SetRepository(&SQLAnnotationRepo{sql: ss}) annotations.SetAnnotationCleaner(&AnnotationCleanupService{batchSize: ss.Cfg.AnnotationCleanupJobBatchSize, log: log.New("annotationcleaner")}) - ss.Bus.SetTransactionManager(ss) - - // Register handlers - ss.addStatsQueryAndCommandHandlers() - ss.addUserQueryAndCommandHandlers() - ss.addAlertNotificationUidByIdHandler() - ss.addPreferencesQueryAndCommandHandlers() - ss.addDashboardQueryAndCommandHandlers() - ss.addDashboardACLQueryAndCommandHandlers() - ss.addQuotaQueryAndCommandHandlers() - ss.addOrgUsersQueryAndCommandHandlers() - ss.addStarQueryAndCommandHandlers() - ss.addAlertQueryAndCommandHandlers() - ss.addTempUserQueryAndCommandHandlers() - ss.addDashboardVersionQueryAndCommandHandlers() - ss.addAPIKeysQueryAndCommandHandlers() - ss.addPlaylistQueryAndCommandHandlers() - ss.addLoginAttemptQueryAndCommandHandlers() - ss.addTeamQueryAndCommandHandlers() - ss.addOrgQueryAndCommandHandlers() - - bus.AddHandler("sql", ss.GetDBHealthQuery) // if err := ss.Reset(); err != nil { // return nil, err diff --git a/pkg/services/sqlstore/star.go b/pkg/services/sqlstore/star.go index fef91f9e9b4..847fdfec6e0 100644 --- a/pkg/services/sqlstore/star.go +++ b/pkg/services/sqlstore/star.go @@ -3,17 +3,9 @@ package sqlstore import ( "context" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) -func (ss *SQLStore) addStarQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.StarDashboard) - bus.AddHandler("sql", ss.UnstarDashboard) - bus.AddHandler("sql", ss.GetUserStars) - bus.AddHandler("sql", ss.IsStarredByUserCtx) -} - func (ss *SQLStore) IsStarredByUserCtx(ctx context.Context, query *models.IsStarredByUserQuery) error { return ss.WithDbSession(ctx, func(sess *DBSession) error { rawSQL := "SELECT 1 from star where user_id=? and dashboard_id=?" diff --git a/pkg/services/sqlstore/stats.go b/pkg/services/sqlstore/stats.go index 43777190fe3..e1e1500994e 100644 --- a/pkg/services/sqlstore/stats.go +++ b/pkg/services/sqlstore/stats.go @@ -5,20 +5,10 @@ import ( "strconv" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/sqlstore/migrator" ) -func (ss *SQLStore) addStatsQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.GetAdminStats) - bus.AddHandler("sql", ss.GetSystemUserCountStats) - bus.AddHandler("sql", ss.GetAlertNotifiersUsageStats) - bus.AddHandler("sql", ss.GetDataSourceAccessStats) - bus.AddHandler("sql", ss.GetDataSourceStats) - bus.AddHandler("sql", ss.GetSystemStats) -} - const activeUserTimeLimit = time.Hour * 24 * 30 const dailyActiveUserTimeLimit = time.Hour * 24 diff --git a/pkg/services/sqlstore/team.go b/pkg/services/sqlstore/team.go index abedc2110b3..6e266fed697 100644 --- a/pkg/services/sqlstore/team.go +++ b/pkg/services/sqlstore/team.go @@ -7,25 +7,11 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ac "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/featuremgmt" ) -func (ss *SQLStore) addTeamQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.UpdateTeam) - bus.AddHandler("sql", ss.DeleteTeam) - bus.AddHandler("sql", ss.SearchTeams) - bus.AddHandler("sql", ss.GetTeamById) - bus.AddHandler("sql", ss.GetTeamsByUser) - - bus.AddHandler("sql", ss.UpdateTeamMember) - bus.AddHandler("sql", ss.RemoveTeamMember) - bus.AddHandler("sql", ss.GetTeamMembers) - bus.AddHandler("sql", IsAdminOfTeams) -} - type TeamStore interface { UpdateTeam(ctx context.Context, cmd *models.UpdateTeamCommand) error DeleteTeam(ctx context.Context, cmd *models.DeleteTeamCommand) error diff --git a/pkg/services/sqlstore/temp_user.go b/pkg/services/sqlstore/temp_user.go index 97f32f77a41..80115ade956 100644 --- a/pkg/services/sqlstore/temp_user.go +++ b/pkg/services/sqlstore/temp_user.go @@ -4,19 +4,9 @@ import ( "context" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) -func (ss *SQLStore) addTempUserQueryAndCommandHandlers() { - bus.AddHandler("sql", ss.CreateTempUser) - bus.AddHandler("sql", ss.GetTempUsersQuery) - bus.AddHandler("sql", ss.UpdateTempUserStatus) - bus.AddHandler("sql", ss.GetTempUserByCode) - bus.AddHandler("sql", ss.UpdateTempUserWithEmailSent) - bus.AddHandler("sql", ss.ExpireOldUserInvites) -} - func (ss *SQLStore) UpdateTempUserStatus(ctx context.Context, cmd *models.UpdateTempUserStatusCommand) error { return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error { var rawSQL = "UPDATE temp_user SET status=? WHERE code=?" diff --git a/pkg/services/sqlstore/user.go b/pkg/services/sqlstore/user.go index c9ce4d9b098..b159dcd6bf8 100644 --- a/pkg/services/sqlstore/user.go +++ b/pkg/services/sqlstore/user.go @@ -8,7 +8,6 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/events" "github.com/grafana/grafana/pkg/models" ac "github.com/grafana/grafana/pkg/services/accesscontrol" @@ -16,25 +15,6 @@ import ( "github.com/grafana/grafana/pkg/util" ) -func (ss *SQLStore) addUserQueryAndCommandHandlers() { - ss.Bus.AddHandler(ss.GetSignedInUserWithCacheCtx) - - bus.AddHandler("sql", ss.GetUserById) - bus.AddHandler("sql", ss.UpdateUser) - bus.AddHandler("sql", ss.ChangeUserPassword) - bus.AddHandler("sql", ss.GetUserByLogin) - bus.AddHandler("sql", ss.GetUserByEmail) - bus.AddHandler("sql", ss.SetUsingOrg) - bus.AddHandler("sql", ss.UpdateUserLastSeenAt) - bus.AddHandler("sql", ss.GetUserProfile) - bus.AddHandler("sql", ss.SearchUsers) - bus.AddHandler("sql", ss.GetUserOrgList) - bus.AddHandler("sql", ss.DisableUser) - bus.AddHandler("sql", ss.BatchDisableUsers) - bus.AddHandler("sql", ss.DeleteUser) - bus.AddHandler("sql", ss.SetUserHelpFlag) -} - func getOrgIdForNewUser(sess *DBSession, cmd models.CreateUserCommand) (int64, error) { if cmd.SkipOrgSetup { return -1, nil