Chore: Remove bus (#47511)

* Chore: Remove bus

* remove unused const
This commit is contained in:
Serge Zaitsev 2022-04-08 16:15:06 +02:00 committed by GitHub
parent 1a88612e82
commit 18e93c7077
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
53 changed files with 19 additions and 701 deletions

View File

@ -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{

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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
}

View File

@ -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{

View File

@ -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 {

View File

@ -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,

View File

@ -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/",

View File

@ -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,

View File

@ -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,

View File

@ -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",

View File

@ -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{

View File

@ -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)
}

View File

@ -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()

View File

@ -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",

View File

@ -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
}

View File

@ -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)

View File

@ -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)

View File

@ -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")

View File

@ -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,

View File

@ -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{

View File

@ -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{

View File

@ -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
}

View File

@ -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{

View File

@ -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
}

View File

@ -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))

View File

@ -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)

View File

@ -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
}

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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)
})

View File

@ -21,7 +21,6 @@ func ProvideService(cfg *setting.Cfg, bus bus.Bus, sqlstore *sqlstore.SQLStore)
},
sqlstore: sqlstore,
}
s.Bus.AddHandler(s.SearchHandler)
return s
}

View File

@ -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{}

View File

@ -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)

View File

@ -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()

View File

@ -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 {

View File

@ -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 {

View File

@ -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

View File

@ -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 {

View File

@ -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{

View File

@ -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)

View File

@ -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

View File

@ -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{

View File

@ -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)

View File

@ -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
}

View File

@ -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

View File

@ -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=?"

View File

@ -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

View File

@ -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

View File

@ -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=?"

View File

@ -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