Migrate store methods to use request.Context instead of context.Context (#24836)

Этот коммит содержится в:
Ben Schumacher
2023-10-11 13:08:55 +02:00
коммит произвёл GitHub
родитель 0d5a8b8841
Коммит 13c05a571f
127 изменённых файлов: 1030 добавлений и 921 удалений

Просмотреть файл

@@ -12,6 +12,7 @@ import (
"github.com/stretchr/testify/mock"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/store"
"github.com/mattermost/mattermost/server/v8/channels/store/storetest/mocks"
"github.com/mattermost/mattermost/server/v8/channels/testlib"
@@ -20,6 +21,7 @@ import (
)
type TestHelper struct {
Context *request.Context
Service *PlatformService
Suite SuiteIFace
@@ -52,7 +54,7 @@ func (ms *mockSuite) GetSession(token string) (*model.Session, *model.AppError)
return &model.Session{}, nil
}
func (ms *mockSuite) RolesGrantPermission(roleNames []string, permissionId string) bool { return true }
func (ms *mockSuite) UserCanSeeOtherUser(userID string, otherUserId string) (bool, *model.AppError) {
func (ms *mockSuite) UserCanSeeOtherUser(c request.CTX, userID string, otherUserId string) (bool, *model.AppError) {
return true, nil
}
@@ -158,6 +160,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo
}
th := &TestHelper{
Context: request.TestContext(tb),
Service: ps,
Suite: &mockSuite{},
}

Просмотреть файл

@@ -5,7 +5,6 @@ package platform
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
@@ -17,6 +16,7 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/jobs"
"github.com/mattermost/mattermost/server/v8/channels/store/sqlstore"
"github.com/mattermost/mattermost/server/v8/channels/utils"
@@ -49,6 +49,8 @@ func (ps *PlatformService) License() *model.License {
}
func (ps *PlatformService) LoadLicense() {
c := request.EmptyContext(ps.logger)
// ENV var overrides all other sources of license.
licenseStr := os.Getenv(LicenseEnv)
if licenseStr != "" {
@@ -97,7 +99,7 @@ func (ps *PlatformService) LoadLicense() {
}
}
record, nErr := ps.Store.License().Get(sqlstore.WithMaster(context.Background()), licenseId)
record, nErr := ps.Store.License().Get(sqlstore.RequestContextWithMaster(c), licenseId)
if nErr != nil {
ps.logger.Error("License key from https://mattermost.com required to unlock enterprise features.", mlog.Err(nErr))
ps.SetLicense(nil)

Просмотреть файл

@@ -7,6 +7,8 @@ package mocks
import (
model "github.com/mattermost/mattermost/server/public/model"
mock "github.com/stretchr/testify/mock"
request "github.com/mattermost/mattermost/server/public/shared/request"
)
// SuiteIFace is an autogenerated mock type for the SuiteIFace type
@@ -56,23 +58,23 @@ func (_m *SuiteIFace) RolesGrantPermission(roleNames []string, permissionId stri
return r0
}
// UserCanSeeOtherUser provides a mock function with given fields: userID, otherUserId
func (_m *SuiteIFace) UserCanSeeOtherUser(userID string, otherUserId string) (bool, *model.AppError) {
ret := _m.Called(userID, otherUserId)
// UserCanSeeOtherUser provides a mock function with given fields: c, userID, otherUserId
func (_m *SuiteIFace) UserCanSeeOtherUser(c request.CTX, userID string, otherUserId string) (bool, *model.AppError) {
ret := _m.Called(c, userID, otherUserId)
var r0 bool
var r1 *model.AppError
if rf, ok := ret.Get(0).(func(string, string) (bool, *model.AppError)); ok {
return rf(userID, otherUserId)
if rf, ok := ret.Get(0).(func(request.CTX, string, string) (bool, *model.AppError)); ok {
return rf(c, userID, otherUserId)
}
if rf, ok := ret.Get(0).(func(string, string) bool); ok {
r0 = rf(userID, otherUserId)
if rf, ok := ret.Get(0).(func(request.CTX, string, string) bool); ok {
r0 = rf(c, userID, otherUserId)
} else {
r0 = ret.Get(0).(bool)
}
if rf, ok := ret.Get(1).(func(string, string) *model.AppError); ok {
r1 = rf(userID, otherUserId)
if rf, ok := ret.Get(1).(func(request.CTX, string, string) *model.AppError); ok {
r1 = rf(c, userID, otherUserId)
} else {
if ret.Get(1) != nil {
r1 = ret.Get(1).(*model.AppError)

Просмотреть файл

@@ -4,13 +4,12 @@
package platform
import (
"context"
"fmt"
"time"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/v8/channels/store/sqlstore"
"github.com/mattermost/mattermost/server/public/shared/request"
)
func (ps *PlatformService) ReturnSessionToPool(session *model.Session) {
@@ -20,10 +19,10 @@ func (ps *PlatformService) ReturnSessionToPool(session *model.Session) {
}
}
func (ps *PlatformService) CreateSession(session *model.Session) (*model.Session, error) {
func (ps *PlatformService) CreateSession(c *request.Context, session *model.Session) (*model.Session, error) {
session.Token = ""
session, err := ps.Store.Session().Save(session)
session, err := ps.Store.Session().Save(c, session)
if err != nil {
return nil, err
}
@@ -33,12 +32,12 @@ func (ps *PlatformService) CreateSession(session *model.Session) (*model.Session
return session, nil
}
func (ps *PlatformService) GetSessionContext(ctx context.Context, token string) (*model.Session, error) {
return ps.Store.Session().Get(ctx, token)
func (ps *PlatformService) GetSessionContext(c *request.Context, token string) (*model.Session, error) {
return ps.Store.Session().Get(c, token)
}
func (ps *PlatformService) GetSessions(userID string) ([]*model.Session, error) {
return ps.Store.Session().GetSessions(userID)
func (ps *PlatformService) GetSessions(c *request.Context, userID string) ([]*model.Session, error) {
return ps.Store.Session().GetSessions(c, userID)
}
func (ps *PlatformService) AddSessionToCache(session *model.Session) {
@@ -97,7 +96,7 @@ func (ps *PlatformService) ClearAllUsersSessionCache() {
}
}
func (ps *PlatformService) GetSession(token string) (*model.Session, error) {
func (ps *PlatformService) GetSession(c *request.Context, token string) (*model.Session, error) {
var session = ps.sessionPool.Get().(*model.Session)
if err := ps.sessionCache.Get(token, session); err == nil {
if m := ps.metricsIFace; m != nil {
@@ -113,11 +112,11 @@ func (ps *PlatformService) GetSession(token string) (*model.Session, error) {
return session, nil
}
return ps.GetSessionContext(sqlstore.WithMaster(context.Background()), token)
return ps.GetSessionContext(c, token)
}
func (ps *PlatformService) GetSessionByID(sessionID string) (*model.Session, error) {
return ps.Store.Session().Get(context.Background(), sessionID)
func (ps *PlatformService) GetSessionByID(c *request.Context, sessionID string) (*model.Session, error) {
return ps.Store.Session().Get(c, sessionID)
}
func (ps *PlatformService) RevokeSessionsFromAllUsers() error {
@@ -135,16 +134,16 @@ func (ps *PlatformService) RevokeSessionsFromAllUsers() error {
return nil
}
func (ps *PlatformService) RevokeSessionsForDeviceId(userID string, deviceID string, currentSessionId string) error {
sessions, err := ps.Store.Session().GetSessions(userID)
func (ps *PlatformService) RevokeSessionsForDeviceId(c *request.Context, userID string, deviceID string, currentSessionId string) error {
sessions, err := ps.Store.Session().GetSessions(c, userID)
if err != nil {
return err
}
for _, session := range sessions {
if session.DeviceId == deviceID && session.Id != currentSessionId {
mlog.Debug("Revoking sessionId for userId. Re-login with the same device Id", mlog.String("session_id", session.Id), mlog.String("user_id", userID))
if err := ps.RevokeSession(session); err != nil {
mlog.Warn("Could not revoke session for device", mlog.String("device_id", deviceID), mlog.Err(err))
c.Logger().Debug("Revoking sessionId for userId. Re-login with the same device Id", mlog.String("session_id", session.Id), mlog.String("user_id", userID))
if err := ps.RevokeSession(c, session); err != nil {
c.Logger().Warn("Could not revoke session for device", mlog.String("device_id", deviceID), mlog.Err(err))
}
}
}
@@ -152,9 +151,9 @@ func (ps *PlatformService) RevokeSessionsForDeviceId(userID string, deviceID str
return nil
}
func (ps *PlatformService) RevokeSession(session *model.Session) error {
func (ps *PlatformService) RevokeSession(c *request.Context, session *model.Session) error {
if session.IsOAuth {
if err := ps.RevokeAccessToken(session.Token); err != nil {
if err := ps.RevokeAccessToken(c, session.Token); err != nil {
return err
}
} else {
@@ -168,8 +167,8 @@ func (ps *PlatformService) RevokeSession(session *model.Session) error {
return nil
}
func (ps *PlatformService) RevokeAccessToken(token string) error {
session, _ := ps.GetSession(token)
func (ps *PlatformService) RevokeAccessToken(c *request.Context, token string) error {
session, _ := ps.GetSession(c, token)
defer ps.ReturnSessionToPool(session)
@@ -223,8 +222,8 @@ func (ps *PlatformService) ExtendSessionExpiry(session *model.Session, newExpiry
return nil
}
func (ps *PlatformService) UpdateSessionsIsGuest(userID string, isGuest bool) error {
sessions, err := ps.GetSessions(userID)
func (ps *PlatformService) UpdateSessionsIsGuest(c *request.Context, userID string, isGuest bool) error {
sessions, err := ps.GetSessions(c, userID)
if err != nil {
return err
}
@@ -241,14 +240,14 @@ func (ps *PlatformService) UpdateSessionsIsGuest(userID string, isGuest bool) er
return nil
}
func (ps *PlatformService) RevokeAllSessions(userID string) error {
sessions, err := ps.Store.Session().GetSessions(userID)
func (ps *PlatformService) RevokeAllSessions(c *request.Context, userID string) error {
sessions, err := ps.Store.Session().GetSessions(c, userID)
if err != nil {
return fmt.Errorf("%s: %w", err.Error(), GetSessionError)
}
for _, session := range sessions {
if session.IsOAuth {
ps.RevokeAccessToken(session.Token)
ps.RevokeAccessToken(c, session.Token)
} else {
if err := ps.Store.Session().Remove(session.Id); err != nil {
return fmt.Errorf("%s: %w", err.Error(), DeleteSessionError)

Просмотреть файл

@@ -105,7 +105,7 @@ func TestOAuthRevokeAccessToken(t *testing.T) {
th := Setup(t)
defer th.TearDown()
err := th.Service.RevokeAccessToken(model.NewRandomString(16))
err := th.Service.RevokeAccessToken(th.Context, model.NewRandomString(16))
require.Error(t, err, "Should have failed due to an incorrect token")
session := &model.Session{}
@@ -115,8 +115,8 @@ func TestOAuthRevokeAccessToken(t *testing.T) {
session.Roles = model.SystemUserRoleId
th.Service.SetSessionExpireInHours(session, 24)
session, _ = th.Service.CreateSession(session)
err = th.Service.RevokeAccessToken(session.Token)
session, _ = th.Service.CreateSession(th.Context, session)
err = th.Service.RevokeAccessToken(th.Context, session.Token)
require.Error(t, err, "Should have failed does not have an access token")
accessData := &model.AccessData{}
@@ -129,6 +129,6 @@ func TestOAuthRevokeAccessToken(t *testing.T) {
_, nErr := th.Service.Store.OAuth().SaveAccessData(accessData)
require.NoError(t, nErr)
err = th.Service.RevokeAccessToken(accessData.Token)
err = th.Service.RevokeAccessToken(th.Context, accessData.Token)
require.NoError(t, err)
}

Просмотреть файл

@@ -24,6 +24,7 @@ import (
"github.com/mattermost/mattermost/server/public/plugin"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
)
const (
@@ -701,7 +702,11 @@ func (wc *WebConn) ShouldSendEventToGuest(msg *model.WebSocketEvent) bool {
return true
}
canSee, err := wc.Suite.UserCanSeeOtherUser(wc.UserId, userID)
// In the future, other methods in WebConn will use a request.Context.
// For now, it's fine to create it here.
c := request.EmptyContext(wc.Platform.logger)
canSee, err := wc.Suite.UserCanSeeOtherUser(c, wc.UserId, userID)
if err != nil {
mlog.Error("webhub.shouldSendEvent.", mlog.Err(err))
return false

Просмотреть файл

@@ -13,6 +13,7 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
)
const (
@@ -23,7 +24,7 @@ const (
type SuiteIFace interface {
GetSession(token string) (*model.Session, *model.AppError)
RolesGrantPermission(roleNames []string, permissionId string) bool
UserCanSeeOtherUser(userID string, otherUserId string) (bool, *model.AppError)
UserCanSeeOtherUser(c request.CTX, userID string, otherUserId string) (bool, *model.AppError)
}
type webConnActivityMessage struct {

Просмотреть файл

@@ -64,7 +64,7 @@ func TestHubStopWithMultipleConnections(t *testing.T) {
s := httptest.NewServer(dummyWebsocketHandler(t))
defer s.Close()
session, err := th.Service.CreateSession(&model.Session{
session, err := th.Service.CreateSession(th.Context, &model.Session{
UserId: th.BasicUser.Id,
})
require.NoError(t, err)
@@ -88,7 +88,7 @@ func TestHubStopRaceCondition(t *testing.T) {
// So we just use this quick hack for the test.
s := httptest.NewServer(dummyWebsocketHandler(t))
session, err := th.Service.CreateSession(&model.Session{
session, err := th.Service.CreateSession(th.Context, &model.Session{
UserId: th.BasicUser.Id,
})
require.NoError(t, err)
@@ -153,8 +153,8 @@ func TestHubSessionRevokeRace(t *testing.T) {
mockSessionStore := mocks.SessionStore{}
mockSessionStore.On("UpdateLastActivityAt", "id1", mock.Anything).Return(nil)
mockSessionStore.On("Save", mock.AnythingOfType("*model.Session")).Return(sess1, nil)
mockSessionStore.On("Get", mock.Anything, "id1").Return(sess1, nil)
mockSessionStore.On("Save", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("*model.Session")).Return(sess1, nil)
mockSessionStore.On("Get", mock.AnythingOfType("*request.Context"), mock.Anything, "id1").Return(sess1, nil)
mockSessionStore.On("Remove", "id1").Return(nil)
mockStatusStore := mocks.StatusStore{}
@@ -179,7 +179,7 @@ func TestHubSessionRevokeRace(t *testing.T) {
s := httptest.NewServer(dummyWebsocketHandler(t))
defer s.Close()
session, err := th.Service.CreateSession(&model.Session{
session, err := th.Service.CreateSession(th.Context, &model.Session{
UserId: "testid",
})
require.NoError(t, err)
@@ -464,7 +464,7 @@ func TestHubIsRegistered(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
session, err := th.Service.CreateSession(&model.Session{
session, err := th.Service.CreateSession(th.Context, &model.Session{
UserId: th.BasicUser.Id,
})
require.NoError(t, err)
@@ -488,7 +488,7 @@ func TestHubIsRegistered(t *testing.T) {
assert.True(t, th.Service.SessionIsRegistered(*wc2.session.Load()))
assert.True(t, th.Service.SessionIsRegistered(*wc3.session.Load()))
session4, err := th.Service.CreateSession(&model.Session{
session4, err := th.Service.CreateSession(th.Context, &model.Session{
UserId: th.BasicUser2.Id,
})
require.NoError(t, err)