* Move Channels into App

In this PR, we make Channels as part of App
instead of Server. This is part of the transition period
of moving fields from Server to Channels.

For now, Channels contains Server. So the hierarchy is

App -> Channels -> Server.

And as a first step, we also move httpService to Channels.

```release-note
NONE
```

* Fixing another test

```release-note
NONE
```

* new method

```release-note
NONE
```
Этот коммит содержится в:
Agniva De Sarker
2021-10-12 11:39:49 +05:30
коммит произвёл GitHub
родитель 561bc968c8
Коммит f0ecdcc5f5
57 изменённых файлов: 247 добавлений и 224 удалений

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

@@ -136,7 +136,7 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent
} }
th := &TestHelper{ th := &TestHelper{
App: app.New(app.ServerConnector(s)), App: app.New(app.ServerConnector(s.Channels())),
Server: s, Server: s,
ConfigStore: configStore, ConfigStore: configStore,
IncludeCacheLayer: includeCache, IncludeCacheLayer: includeCache,

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

@@ -24,7 +24,7 @@ import (
// It is a request-scoped struct constructed every time a request hits the server, // It is a request-scoped struct constructed every time a request hits the server,
// and its only purpose is to provide business logic to Server via its methods. // and its only purpose is to provide business logic to Server via its methods.
type App struct { type App struct {
srv *Server ch *Channels
} }
func New(options ...AppOption) *App { func New(options ...AppOption) *App {
@@ -82,56 +82,56 @@ func (s *Server) getFirstServerRunTimestamp() (int64, *model.AppError) {
} }
func (a *App) Srv() *Server { func (a *App) Srv() *Server {
return a.srv return a.ch.srv
} }
func (a *App) Log() *mlog.Logger { func (a *App) Log() *mlog.Logger {
return a.srv.Log return a.ch.srv.Log
} }
func (a *App) NotificationsLog() *mlog.Logger { func (a *App) NotificationsLog() *mlog.Logger {
return a.srv.NotificationsLog return a.ch.srv.NotificationsLog
} }
func (a *App) AccountMigration() einterfaces.AccountMigrationInterface { func (a *App) AccountMigration() einterfaces.AccountMigrationInterface {
return a.srv.AccountMigration return a.ch.srv.AccountMigration
} }
func (a *App) Cluster() einterfaces.ClusterInterface { func (a *App) Cluster() einterfaces.ClusterInterface {
return a.srv.Cluster return a.ch.srv.Cluster
} }
func (a *App) Compliance() einterfaces.ComplianceInterface { func (a *App) Compliance() einterfaces.ComplianceInterface {
return a.srv.Compliance return a.ch.srv.Compliance
} }
func (a *App) DataRetention() einterfaces.DataRetentionInterface { func (a *App) DataRetention() einterfaces.DataRetentionInterface {
return a.srv.DataRetention return a.ch.srv.DataRetention
} }
func (a *App) SearchEngine() *searchengine.Broker { func (a *App) SearchEngine() *searchengine.Broker {
return a.srv.SearchEngine return a.ch.srv.SearchEngine
} }
func (a *App) Ldap() einterfaces.LdapInterface { func (a *App) Ldap() einterfaces.LdapInterface {
return a.srv.Ldap return a.ch.srv.Ldap
} }
func (a *App) MessageExport() einterfaces.MessageExportInterface { func (a *App) MessageExport() einterfaces.MessageExportInterface {
return a.srv.MessageExport return a.ch.srv.MessageExport
} }
func (a *App) Metrics() einterfaces.MetricsInterface { func (a *App) Metrics() einterfaces.MetricsInterface {
return a.srv.Metrics return a.ch.srv.Metrics
} }
func (a *App) Notification() einterfaces.NotificationInterface { func (a *App) Notification() einterfaces.NotificationInterface {
return a.srv.Notification return a.ch.srv.Notification
} }
func (a *App) Saml() einterfaces.SamlInterface { func (a *App) Saml() einterfaces.SamlInterface {
return a.srv.Saml return a.ch.srv.Saml
} }
func (a *App) Cloud() einterfaces.CloudInterface { func (a *App) Cloud() einterfaces.CloudInterface {
return a.srv.Cloud return a.ch.srv.Cloud
} }
func (a *App) HTTPService() httpservice.HTTPService { func (a *App) HTTPService() httpservice.HTTPService {
return a.srv.httpService return a.ch.httpService
} }
func (a *App) ImageProxy() *imageproxy.ImageProxy { func (a *App) ImageProxy() *imageproxy.ImageProxy {
return a.srv.ImageProxy return a.ch.srv.ImageProxy
} }
func (a *App) Timezones() *timezones.Timezones { func (a *App) Timezones() *timezones.Timezones {
return a.srv.timezones return a.ch.srv.timezones
} }
func (a *App) DBHealthCheckWrite() error { func (a *App) DBHealthCheckWrite() error {
@@ -156,8 +156,12 @@ func (a *App) CheckIntegrity() <-chan model.IntegrityCheckResult {
return a.Srv().Store.CheckIntegrity() return a.Srv().Store.CheckIntegrity()
} }
func (a *App) SetChannels(ch *Channels) {
a.ch = ch
}
func (a *App) SetServer(srv *Server) { func (a *App) SetServer(srv *Server) {
a.srv = srv a.ch.srv = srv
} }
func (a *App) UpdateExpiredDNDStatuses() ([]*model.Status, error) { func (a *App) UpdateExpiredDNDStatuses() ([]*model.Status, error) {

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

@@ -990,6 +990,7 @@ type AppIface interface {
SessionHasPermissionToUserOrBot(session model.Session, userID string) bool SessionHasPermissionToUserOrBot(session model.Session, userID string) bool
SetActiveChannel(userID string, channelID string) *model.AppError SetActiveChannel(userID string, channelID string) *model.AppError
SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap) SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap)
SetChannels(ch *Channels)
SetCustomStatus(userID string, cs *model.CustomStatus) *model.AppError SetCustomStatus(userID string, cs *model.CustomStatus) *model.AppError
SetDefaultProfileImage(user *model.User) *model.AppError SetDefaultProfileImage(user *model.User) *model.AppError
SetPhase2PermissionsMigrationStatus(isComplete bool) error SetPhase2PermissionsMigrationStatus(isComplete bool) error

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

@@ -32,13 +32,13 @@ func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError {
return model.NewAppError("SaveBrandImage", "brand.save_brand_image.check_image_limits.app_error", nil, err.Error(), http.StatusBadRequest) return model.NewAppError("SaveBrandImage", "brand.save_brand_image.check_image_limits.app_error", nil, err.Error(), http.StatusBadRequest)
} }
img, _, err := a.srv.imgDecoder.Decode(file) img, _, err := a.ch.srv.imgDecoder.Decode(file)
if err != nil { if err != nil {
return model.NewAppError("SaveBrandImage", "brand.save_brand_image.decode.app_error", nil, err.Error(), http.StatusBadRequest) return model.NewAppError("SaveBrandImage", "brand.save_brand_image.decode.app_error", nil, err.Error(), http.StatusBadRequest)
} }
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
err = a.srv.imgEncoder.EncodePNG(buf, img) err = a.ch.srv.imgEncoder.EncodePNG(buf, img)
if err != nil { if err != nil {
return model.NewAppError("SaveBrandImage", "brand.save_brand_image.encode.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("SaveBrandImage", "brand.save_brand_image.encode.app_error", nil, err.Error(), http.StatusInternalServerError)
} }

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

@@ -1972,12 +1972,12 @@ func TestMarkChannelsAsViewedPanic(t *testing.T) {
mockSessionStore := mocks.SessionStore{} mockSessionStore := mocks.SessionStore{}
mockOAuthStore := mocks.OAuthStore{} mockOAuthStore := mocks.OAuthStore{}
var err error var err error
th.App.srv.userService, err = users.New(users.ServiceConfig{ th.App.ch.srv.userService, err = users.New(users.ServiceConfig{
UserStore: &mockUserStore, UserStore: &mockUserStore,
SessionStore: &mockSessionStore, SessionStore: &mockSessionStore,
OAuthStore: &mockOAuthStore, OAuthStore: &mockOAuthStore,
ConfigFn: th.App.srv.Config, ConfigFn: th.App.ch.srv.Config,
LicenseFn: th.App.srv.License, LicenseFn: th.App.ch.srv.License,
}) })
require.NoError(t, err) require.NoError(t, err)
mockPreferenceStore := mocks.PreferenceStore{} mockPreferenceStore := mocks.PreferenceStore{}

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

@@ -3,9 +3,13 @@
package app package app
import "github.com/mattermost/mattermost-server/v6/services/httpservice"
// Channels contains all channels related state. // Channels contains all channels related state.
type Channels struct { type Channels struct {
s *Server srv *Server
httpService httpservice.HTTPService
} }
func init() { func init() {
@@ -16,7 +20,8 @@ func init() {
func NewChannels(s *Server) (*Channels, error) { func NewChannels(s *Server) (*Channels, error) {
return &Channels{ return &Channels{
s: s, srv: s,
httpService: httpservice.MakeHTTPService(s),
}, nil }, nil
} }
@@ -27,3 +32,7 @@ func (c *Channels) Start() error {
func (c *Channels) Stop() error { func (c *Channels) Stop() error {
return nil return nil
} }
func (c *Channels) HTTPService() httpservice.HTTPService {
return c.httpService
}

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

@@ -19,14 +19,14 @@ const (
func (a *App) NotifySessionsExpired() *model.AppError { func (a *App) NotifySessionsExpired() *model.AppError {
if *a.Config().EmailSettings.SendPushNotifications { if *a.Config().EmailSettings.SendPushNotifications {
pushServer := *a.Config().EmailSettings.PushNotificationServer pushServer := *a.Config().EmailSettings.PushNotificationServer
if license := a.srv.License(); pushServer == model.MHPNS && (license == nil || !*license.Features.MHPNS) { if license := a.ch.srv.License(); pushServer == model.MHPNS && (license == nil || !*license.Features.MHPNS) {
mlog.Warn("Push notifications are disabled. Go to System Console > Notifications > Mobile Push to enable them.") mlog.Warn("Push notifications are disabled. Go to System Console > Notifications > Mobile Push to enable them.")
return nil return nil
} }
} }
// Get all mobile sessions that expired within the last hour. // Get all mobile sessions that expired within the last hour.
sessions, err := a.srv.Store.Session().GetSessionsExpired(OneHourMillis, true, true) sessions, err := a.ch.srv.Store.Session().GetSessionsExpired(OneHourMillis, true, true)
if err != nil { if err != nil {
return model.NewAppError("NotifySessionsExpired", "app.session.analytics_session_count.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("NotifySessionsExpired", "app.session.analytics_session_count.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -66,7 +66,7 @@ func (a *App) NotifySessionsExpired() *model.AppError {
a.Metrics().IncrementPostSentPush() a.Metrics().IncrementPostSentPush()
} }
err = a.srv.Store.Session().UpdateExpiredNotify(session.Id, true) err = a.ch.srv.Store.Session().UpdateExpiredNotify(session.Id, true)
if err != nil { if err != nil {
mlog.Error("Failed to update ExpiredNotify flag", mlog.String("sessionid", session.Id), mlog.Err(err)) mlog.Error("Failed to update ExpiredNotify flag", mlog.String("sessionid", session.Id), mlog.Err(err))
} }

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

@@ -98,7 +98,7 @@ func (a *App) TestFileStoreConnectionWithConfig(cfg *model.FileSettings) *model.
} }
func (a *App) ReadFile(path string) ([]byte, *model.AppError) { func (a *App) ReadFile(path string) ([]byte, *model.AppError) {
return a.srv.ReadFile(path) return a.ch.srv.ReadFile(path)
} }
func (s *Server) fileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) { func (s *Server) fileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) {
@@ -703,8 +703,8 @@ func (a *App) UploadFileX(c *request.Context, channelID, name string, input io.R
Input: input, Input: input,
maxFileSize: *a.Config().FileSettings.MaxFileSize, maxFileSize: *a.Config().FileSettings.MaxFileSize,
maxImageRes: *a.Config().FileSettings.MaxImageResolution, maxImageRes: *a.Config().FileSettings.MaxImageResolution,
imgDecoder: a.srv.imgDecoder, imgDecoder: a.ch.srv.imgDecoder,
imgEncoder: a.srv.imgEncoder, imgEncoder: a.ch.srv.imgEncoder,
} }
for _, o := range opts { for _, o := range opts {
o(t) o(t)
@@ -1040,7 +1040,7 @@ func (a *App) HandleImages(previewPathList []string, thumbnailPathList []string,
wg := new(sync.WaitGroup) wg := new(sync.WaitGroup)
for i := range fileData { for i := range fileData {
img, release, err := prepareImage(a.srv.imgDecoder, bytes.NewReader(fileData[i])) img, release, err := prepareImage(a.ch.srv.imgDecoder, bytes.NewReader(fileData[i]))
if err != nil { if err != nil {
mlog.Debug("Failed to prepare image", mlog.Err(err)) mlog.Debug("Failed to prepare image", mlog.Err(err))
continue continue
@@ -1088,7 +1088,7 @@ func prepareImage(imgDecoder *imaging.Decoder, imgData io.ReadSeeker) (img image
func (a *App) generateThumbnailImage(img image.Image, thumbnailPath string) { func (a *App) generateThumbnailImage(img image.Image, thumbnailPath string) {
var buf bytes.Buffer var buf bytes.Buffer
if err := a.srv.imgEncoder.EncodeJPEG(&buf, imaging.GenerateThumbnail(img, imageThumbnailWidth, imageThumbnailHeight), jpegEncQuality); err != nil { if err := a.ch.srv.imgEncoder.EncodeJPEG(&buf, imaging.GenerateThumbnail(img, imageThumbnailWidth, imageThumbnailHeight), jpegEncQuality); err != nil {
mlog.Error("Unable to encode image as jpeg", mlog.String("path", thumbnailPath), mlog.Err(err)) mlog.Error("Unable to encode image as jpeg", mlog.String("path", thumbnailPath), mlog.Err(err))
return return
} }
@@ -1103,7 +1103,7 @@ func (a *App) generatePreviewImage(img image.Image, previewPath string) {
var buf bytes.Buffer var buf bytes.Buffer
preview := imaging.GeneratePreview(img, imagePreviewWidth) preview := imaging.GeneratePreview(img, imagePreviewWidth)
if err := a.srv.imgEncoder.EncodeJPEG(&buf, preview, jpegEncQuality); err != nil { if err := a.ch.srv.imgEncoder.EncodeJPEG(&buf, preview, jpegEncQuality); err != nil {
mlog.Error("Unable to encode image as preview jpg", mlog.Err(err), mlog.String("path", previewPath)) mlog.Error("Unable to encode image as preview jpg", mlog.Err(err), mlog.String("path", previewPath))
return return
} }
@@ -1124,7 +1124,7 @@ func (a *App) generateMiniPreview(fi *model.FileInfo) {
return return
} }
defer file.Close() defer file.Close()
img, release, err := prepareImage(a.srv.imgDecoder, file) img, release, err := prepareImage(a.ch.srv.imgDecoder, file)
if err != nil { if err != nil {
mlog.Debug("generateMiniPreview: prepareImage failed", mlog.Err(err), mlog.Debug("generateMiniPreview: prepareImage failed", mlog.Err(err),
mlog.String("fileinfo_id", fi.Id), mlog.String("channel_id", fi.ChannelId), mlog.String("fileinfo_id", fi.Id), mlog.String("channel_id", fi.ChannelId),

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

@@ -98,7 +98,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo
} }
th := &TestHelper{ th := &TestHelper{
App: New(ServerConnector(s)), App: New(ServerConnector(s.Channels())),
Context: &request.Context{}, Context: &request.Context{},
Server: s, Server: s,
LogBuffer: buffer, LogBuffer: buffer,

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

@@ -485,7 +485,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
var savedUser *model.User var savedUser *model.User
var err error var err error
if user.Id == "" { if user.Id == "" {
if savedUser, err = a.srv.userService.CreateUser(user, users.UserCreateOptions{FromImport: true}); err != nil { if savedUser, err = a.ch.srv.userService.CreateUser(user, users.UserCreateOptions{FromImport: true}); err != nil {
var appErr *model.AppError var appErr *model.AppError
var invErr *store.ErrInvalidInput var invErr *store.ErrInvalidInput
switch { switch {

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

@@ -423,7 +423,7 @@ func (a *App) doPluginRequest(c *request.Context, method, rawURL string, values
params["plugin_id"] = pluginID params["plugin_id"] = pluginID
r = mux.SetURLVars(r, params) r = mux.SetURLVars(r, params)
a.srv.ServePluginRequest(w, r) a.ch.srv.ServePluginRequest(w, r)
resp := &http.Response{ resp := &http.Response{
StatusCode: w.status, StatusCode: w.status,

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

@@ -177,7 +177,7 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request
session.GenerateCSRF() session.GenerateCSRF()
if deviceID != "" { if deviceID != "" {
a.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthMobileInDays) a.ch.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthMobileInDays)
// A special case where we logout of all other sessions with the same Id // A special case where we logout of all other sessions with the same Id
if err := a.RevokeSessionsForDeviceId(user.Id, deviceID, ""); err != nil { if err := a.RevokeSessionsForDeviceId(user.Id, deviceID, ""); err != nil {
@@ -185,11 +185,11 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request
return err return err
} }
} else if isMobile { } else if isMobile {
a.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthMobileInDays) a.ch.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthMobileInDays)
} else if isOAuthUser || isSaml { } else if isOAuthUser || isSaml {
a.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthSSOInDays) a.ch.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthSSOInDays)
} else { } else {
a.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthWebInDays) a.ch.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthWebInDays)
} }
ua := uasurfer.Parse(r.UserAgent()) ua := uasurfer.Parse(r.UserAgent())

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

@@ -281,7 +281,7 @@ func (s *Server) createPushNotificationsHub() {
buffer := *s.Config().EmailSettings.PushNotificationBuffer buffer := *s.Config().EmailSettings.PushNotificationBuffer
hub := PushNotificationsHub{ hub := PushNotificationsHub{
notificationsChan: make(chan PushNotification, buffer), notificationsChan: make(chan PushNotification, buffer),
app: New(ServerConnector(s)), app: New(ServerConnector(s.Channels())),
wg: new(sync.WaitGroup), wg: new(sync.WaitGroup),
semaWg: new(sync.WaitGroup), semaWg: new(sync.WaitGroup),
sema: make(chan struct{}, runtime.NumCPU()*8), // numCPU * 8 is a good amount of concurrency. sema: make(chan struct{}, runtime.NumCPU()*8), // numCPU * 8 is a good amount of concurrency.

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

@@ -1380,8 +1380,13 @@ func TestPushNotificationRace(t *testing.T) {
s := &Server{ s := &Server{
configStore: memoryStore, configStore: memoryStore,
Store: mockStore, Store: mockStore,
products: make(map[string]Product),
} }
app := New(ServerConnector(s)) ch, err := NewChannels(s)
require.NoError(t, err)
s.products["channels"] = ch
app := New(ServerConnector(s.Channels()))
require.NotPanics(t, func() { require.NotPanics(t, func() {
s.createPushNotificationsHub() s.createPushNotificationsHub()

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

@@ -371,7 +371,7 @@ func (a *App) newSession(appName string, user *model.User) (*model.Session, *mod
// Set new token an session // Set new token an session
session := &model.Session{UserId: user.Id, Roles: user.Roles, IsOAuth: true} session := &model.Session{UserId: user.Id, Roles: user.Roles, IsOAuth: true}
session.GenerateCSRF() session.GenerateCSRF()
a.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthSSOInDays) a.ch.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthSSOInDays)
session.AddProp(model.SessionPropPlatform, appName) session.AddProp(model.SessionPropPlatform, appName)
session.AddProp(model.SessionPropOs, "OAuth2") session.AddProp(model.SessionPropOs, "OAuth2")
session.AddProp(model.SessionPropBrowser, "OAuth2") session.AddProp(model.SessionPropBrowser, "OAuth2")
@@ -381,7 +381,7 @@ func (a *App) newSession(appName string, user *model.User) (*model.Session, *mod
return nil, model.NewAppError("newSession", "api.oauth.get_access_token.internal_session.app_error", nil, "", http.StatusInternalServerError) return nil, model.NewAppError("newSession", "api.oauth.get_access_token.internal_session.app_error", nil, "", http.StatusInternalServerError)
} }
a.srv.userService.AddSessionToCache(session) a.ch.srv.userService.AddSessionToCache(session)
return session, nil return session, nil
} }
@@ -520,7 +520,7 @@ func (a *App) RegenerateOAuthAppSecret(app *model.OAuthApp) (*model.OAuthApp, *m
} }
func (a *App) RevokeAccessToken(token string) *model.AppError { func (a *App) RevokeAccessToken(token string) *model.AppError {
if err := a.srv.userService.RevokeAccessToken(token); err != nil { if err := a.ch.srv.userService.RevokeAccessToken(token); err != nil {
switch { switch {
case errors.Is(err, users.GetTokenError): case errors.Is(err, users.GetTokenError):
return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.get.app_error", nil, err.Error(), http.StatusBadRequest) return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.get.app_error", nil, err.Error(), http.StatusBadRequest)

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

@@ -107,7 +107,7 @@ func TestOAuthDeleteApp(t *testing.T) {
session.Token = model.NewId() session.Token = model.NewId()
session.Roles = model.SystemUserRoleId session.Roles = model.SystemUserRoleId
session.IsOAuth = true session.IsOAuth = true
th.App.srv.userService.SetSessionExpireInDays(session, 1) th.App.ch.srv.userService.SetSessionExpireInDays(session, 1)
session, _ = th.App.CreateSession(session) session, _ = th.App.CreateSession(session)

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

@@ -14692,6 +14692,21 @@ func (a *OpenTracingAppLayer) SetAutoResponderStatus(user *model.User, oldNotify
a.app.SetAutoResponderStatus(user, oldNotifyProps) a.app.SetAutoResponderStatus(user, oldNotifyProps)
} }
func (a *OpenTracingAppLayer) SetChannels(ch *app.Channels) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetChannels")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.SetChannels(ch)
}
func (a *OpenTracingAppLayer) SetCustomStatus(userID string, cs *model.CustomStatus) *model.AppError { func (a *OpenTracingAppLayer) SetCustomStatus(userID string, cs *model.CustomStatus) *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetCustomStatus") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetCustomStatus")

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

@@ -106,8 +106,8 @@ func SkipPostInitializiation() Option {
type AppOption func(a *App) type AppOption func(a *App)
type AppOptionCreator func() []AppOption type AppOptionCreator func() []AppOption
func ServerConnector(s *Server) AppOption { func ServerConnector(ch *Channels) AppOption {
return func(a *App) { return func(a *App) {
a.srv = s a.ch = ch
} }
} }

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

@@ -921,7 +921,7 @@ func (a *App) DoPermissionsMigrations() error {
} }
func (s *Server) doPermissionsMigrations() error { func (s *Server) doPermissionsMigrations() error {
a := New(ServerConnector(s)) a := New(ServerConnector(s.Channels()))
PermissionsMigrations := []struct { PermissionsMigrations := []struct {
Key string Key string
Migration func() (permissionsMap, error) Migration func() (permissionsMap, error)

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

@@ -196,7 +196,7 @@ func (s *Server) initPlugins(c *request.Context, pluginDir, webappPluginDir stri
} }
newAPIFunc := func(manifest *model.Manifest) plugin.API { newAPIFunc := func(manifest *model.Manifest) plugin.API {
return New(ServerConnector(s)).NewPluginAPI(c, manifest) return New(ServerConnector(s.Channels())).NewPluginAPI(c, manifest)
} }
env, err := plugin.NewEnvironment(newAPIFunc, NewDriverImpl(s), pluginDir, webappPluginDir, s.Log, s.Metrics) env, err := plugin.NewEnvironment(newAPIFunc, NewDriverImpl(s), pluginDir, webappPluginDir, s.Log, s.Metrics)

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

@@ -92,7 +92,7 @@ func setupMultiPluginAPITest(t *testing.T, pluginCodes []string, pluginManifests
return app.NewPluginAPI(c, manifest) return app.NewPluginAPI(c, manifest)
} }
env, err := plugin.NewEnvironment(newPluginAPI, NewDriverImpl(app.srv), pluginDir, webappPluginDir, app.Log(), nil) env, err := plugin.NewEnvironment(newPluginAPI, NewDriverImpl(app.Srv()), pluginDir, webappPluginDir, app.Log(), nil)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, len(pluginCodes), len(pluginIDs)) require.Equal(t, len(pluginCodes), len(pluginIDs))
@@ -867,7 +867,7 @@ func TestInstallPlugin(t *testing.T) {
return app.NewPluginAPI(c, manifest) return app.NewPluginAPI(c, manifest)
} }
env, err := plugin.NewEnvironment(newPluginAPI, NewDriverImpl(app.srv), pluginDir, webappPluginDir, app.Log(), nil) env, err := plugin.NewEnvironment(newPluginAPI, NewDriverImpl(app.Srv()), pluginDir, webappPluginDir, app.Log(), nil)
require.NoError(t, err) require.NoError(t, err)
app.SetPluginsEnvironment(env) app.SetPluginsEnvironment(env)
@@ -1066,7 +1066,7 @@ func pluginAPIHookTest(t *testing.T, th *TestHelper, fileName string, id string,
if settingsSchema != "" { if settingsSchema != "" {
schema = settingsSchema schema = settingsSchema
} }
th.App.srv.sqlStore = th.GetSqlStore() th.App.ch.srv.sqlStore = th.GetSqlStore()
setupPluginAPITest(t, code, setupPluginAPITest(t, code,
fmt.Sprintf(`{"id": "%v", "server": {"executable": "backend.exe"}, "settings_schema": %v}`, id, schema), fmt.Sprintf(`{"id": "%v", "server": {"executable": "backend.exe"}, "settings_schema": %v}`, id, schema),
id, th.App, th.Context) id, th.App, th.Context)

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

@@ -34,7 +34,7 @@ func SetAppEnvironmentWithPlugins(t *testing.T, pluginCode []string, app *App, a
webappPluginDir, err := ioutil.TempDir("", "") webappPluginDir, err := ioutil.TempDir("", "")
require.NoError(t, err) require.NoError(t, err)
env, err := plugin.NewEnvironment(apiFunc, NewDriverImpl(app.srv), pluginDir, webappPluginDir, app.Log(), nil) env, err := plugin.NewEnvironment(apiFunc, NewDriverImpl(app.Srv()), pluginDir, webappPluginDir, app.Log(), nil)
require.NoError(t, err) require.NoError(t, err)
app.SetPluginsEnvironment(env) app.SetPluginsEnvironment(env)

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

@@ -141,7 +141,7 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand
r.Header.Del("Mattermost-User-Id") r.Header.Del("Mattermost-User-Id")
if token != "" { if token != "" {
session, err := New(ServerConnector(s)).GetSession(token) session, err := New(ServerConnector(s.Channels())).GetSession(token)
defer s.userService.ReturnSessionToPool(session) defer s.userService.ReturnSessionToPool(session)
csrfCheckPassed := false csrfCheckPassed := false

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

@@ -4,43 +4,27 @@
package app package app
import ( import (
"hash/maphash"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/v6/config"
"github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/model"
) )
func TestServePluginPublicRequest(t *testing.T) { func TestServePluginPublicRequest(t *testing.T) {
t.Run("returns not found when plugins environment is nil", func(t *testing.T) { t.Run("returns not found when plugins environment is nil", func(t *testing.T) {
cfg := model.Config{} th := Setup(t)
cfg.SetDefaults() defer th.TearDown()
configStore := config.NewTestMemoryStore() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true })
configStore.Set(&cfg)
srv := &Server{
goroutineExitSignal: make(chan struct{}, 1),
RootRouter: mux.NewRouter(),
LocalRouter: mux.NewRouter(),
licenseListeners: map[string]func(*model.License, *model.License){},
hashSeed: maphash.MakeSeed(),
uploadLockMap: map[string]bool{},
configStore: configStore,
}
app := New(ServerConnector(srv))
app.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true })
req, err := http.NewRequest("GET", "/plugins", nil) req, err := http.NewRequest("GET", "/plugins", nil)
require.NoError(t, err) require.NoError(t, err)
rr := httptest.NewRecorder() rr := httptest.NewRecorder()
handler := http.HandlerFunc(srv.ServePluginPublicRequest) handler := http.HandlerFunc(th.App.Srv().ServePluginPublicRequest)
handler.ServeHTTP(rr, req) handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusNotFound, rr.Code) assert.Equal(t, http.StatusNotFound, rr.Code)

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

@@ -342,7 +342,7 @@ func TestServePluginRequest(t *testing.T) {
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/plugins/foo/bar", nil) r := httptest.NewRequest("GET", "/plugins/foo/bar", nil)
th.App.srv.ServePluginRequest(w, r) th.App.ch.srv.ServePluginRequest(w, r)
assert.Equal(t, http.StatusNotImplemented, w.Result().StatusCode) assert.Equal(t, http.StatusNotImplemented, w.Result().StatusCode)
} }
@@ -386,7 +386,7 @@ func TestPrivateServePluginRequest(t *testing.T) {
request = mux.SetURLVars(request, map[string]string{"plugin_id": "id"}) request = mux.SetURLVars(request, map[string]string{"plugin_id": "id"})
th.App.srv.servePluginRequest(recorder, request, handler) th.App.ch.srv.servePluginRequest(recorder, request, handler)
}) })
} }
@@ -409,7 +409,7 @@ func TestHandlePluginRequest(t *testing.T) {
var assertions func(*http.Request) var assertions func(*http.Request)
router := mux.NewRouter() router := mux.NewRouter()
router.HandleFunc("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}/{anything:.*}", func(_ http.ResponseWriter, r *http.Request) { router.HandleFunc("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}/{anything:.*}", func(_ http.ResponseWriter, r *http.Request) {
th.App.srv.servePluginRequest(nil, r, func(_ *plugin.Context, _ http.ResponseWriter, r *http.Request) { th.App.ch.srv.servePluginRequest(nil, r, func(_ *plugin.Context, _ http.ResponseWriter, r *http.Request) {
assertions(r) assertions(r)
}) })
}) })

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

@@ -606,8 +606,10 @@ func TestMaxPostSize(t *testing.T) {
mockStore.PostStore.On("GetMaxPostSize").Return(testCase.StoreMaxPostSize) mockStore.PostStore.On("GetMaxPostSize").Return(testCase.StoreMaxPostSize)
app := App{ app := App{
srv: &Server{ ch: &Channels{
Store: mockStore, srv: &Server{
Store: mockStore,
},
}, },
} }
@@ -2360,7 +2362,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) {
defer th.TearDown() defer th.TearDown()
remoteClusterService := NewMockSharedChannelService(nil) remoteClusterService := NewMockSharedChannelService(nil)
th.App.srv.sharedChannelService = remoteClusterService th.App.ch.srv.sharedChannelService = remoteClusterService
testCluster := &testlib.FakeClusterInterface{} testCluster := &testlib.FakeClusterInterface{}
th.Server.Cluster = testCluster th.Server.Cluster = testCluster
@@ -2384,7 +2386,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) {
defer th.TearDown() defer th.TearDown()
remoteClusterService := NewMockSharedChannelService(nil) remoteClusterService := NewMockSharedChannelService(nil)
th.App.srv.sharedChannelService = remoteClusterService th.App.ch.srv.sharedChannelService = remoteClusterService
testCluster := &testlib.FakeClusterInterface{} testCluster := &testlib.FakeClusterInterface{}
th.Server.Cluster = testCluster th.Server.Cluster = testCluster
@@ -2412,7 +2414,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) {
defer th.TearDown() defer th.TearDown()
remoteClusterService := NewMockSharedChannelService(nil) remoteClusterService := NewMockSharedChannelService(nil)
th.App.srv.sharedChannelService = remoteClusterService th.App.ch.srv.sharedChannelService = remoteClusterService
testCluster := &testlib.FakeClusterInterface{} testCluster := &testlib.FakeClusterInterface{}
th.Server.Cluster = testCluster th.Server.Cluster = testCluster

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

@@ -18,7 +18,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
sharedChannelService := NewMockSharedChannelService(nil) sharedChannelService := NewMockSharedChannelService(nil)
th.App.srv.sharedChannelService = sharedChannelService th.App.ch.srv.sharedChannelService = sharedChannelService
testCluster := &testlib.FakeClusterInterface{} testCluster := &testlib.FakeClusterInterface{}
th.Server.Cluster = testCluster th.Server.Cluster = testCluster
@@ -53,7 +53,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
sharedChannelService := NewMockSharedChannelService(nil) sharedChannelService := NewMockSharedChannelService(nil)
th.App.srv.sharedChannelService = sharedChannelService th.App.ch.srv.sharedChannelService = sharedChannelService
testCluster := &testlib.FakeClusterInterface{} testCluster := &testlib.FakeClusterInterface{}
th.Server.Cluster = testCluster th.Server.Cluster = testCluster

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

@@ -288,7 +288,7 @@ func (a *App) ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs
appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented) appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented)
return return
} }
numAffected, err := a.srv.Store.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, userIDs, includeDeleted, dryRun) numAffected, err := a.Srv().Store.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, userIDs, includeDeleted, dryRun)
if err != nil { if err != nil {
appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.failure_reset_authdata_to_email.app_error", nil, err.Error(), http.StatusInternalServerError) appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.failure_reset_authdata_to_email.app_error", nil, err.Error(), http.StatusInternalServerError)
return return

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

@@ -32,7 +32,7 @@ func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError {
} }
func (a *App) SetSearchEngine(se *searchengine.Broker) { func (a *App) SetSearchEngine(se *searchengine.Broker) {
a.srv.SearchEngine = se a.ch.srv.SearchEngine = se
} }
func (a *App) PurgeElasticsearchIndexes() *model.AppError { func (a *App) PurgeElasticsearchIndexes() *model.AppError {

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

@@ -162,8 +162,6 @@ type Server struct {
phase2PermissionsMigrationComplete bool phase2PermissionsMigrationComplete bool
httpService httpservice.HTTPService
ImageProxy *imageproxy.ImageProxy ImageProxy *imageproxy.ImageProxy
Audit *audit.Audit Audit *audit.Audit
@@ -267,9 +265,19 @@ func NewServer(options ...Option) (*Server, error) {
// This is called after initLogging() to avoid a race condition. // This is called after initLogging() to avoid a race condition.
mlog.Info("Server is initializing...", mlog.String("go_version", runtime.Version())) mlog.Info("Server is initializing...", mlog.String("go_version", runtime.Version()))
// Initialize products
for name, initializer := range products {
prod, err := initializer(s)
if err != nil {
return nil, errors.Wrapf(err, "error initializing product: %s", name)
}
s.products[name] = prod
}
// It is important to initialize the hub only after the global logger is set // It is important to initialize the hub only after the global logger is set
// to avoid race conditions while logging from inside the hub. // to avoid race conditions while logging from inside the hub.
app := New(ServerConnector(s)) app := New(ServerConnector(s.Channels()))
app.HubStart() app.HubStart()
if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry { if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry {
@@ -304,8 +312,7 @@ func NewServer(options ...Option) (*Server, error) {
s.tracer = tracer s.tracer = tracer
} }
s.httpService = httpservice.MakeHTTPService(s) s.pushNotificationClient = s.Channels().HTTPService().MakeClient(true)
s.pushNotificationClient = s.httpService.MakeClient(true)
s.ImageProxy = imageproxy.MakeImageProxy(s, s.HTTPService(), s.Log) s.ImageProxy = imageproxy.MakeImageProxy(s, s.HTTPService(), s.Log)
@@ -349,6 +356,7 @@ func NewServer(options ...Option) (*Server, error) {
return nil, errors.Wrapf(err2, "unable to load Mattermost translation files") return nil, errors.Wrapf(err2, "unable to load Mattermost translation files")
} }
// initEnterprise needs to be called after products initialization.
s.initEnterprise() s.initEnterprise()
if s.newStore == nil { if s.newStore == nil {
@@ -695,16 +703,6 @@ func NewServer(options ...Option) (*Server, error) {
} }
}) })
// Initialize products
for name, initializer := range products {
prod, err := initializer(s)
if err != nil {
return nil, errors.Wrapf(err, "error initializing product: %s", name)
}
s.products[name] = prod
}
s.AddConfigListener(func(oldCfg, newCfg *model.Config) { s.AddConfigListener(func(oldCfg, newCfg *model.Config) {
if !oldCfg.FeatureFlags.TimedDND && newCfg.FeatureFlags.TimedDND { if !oldCfg.FeatureFlags.TimedDND && newCfg.FeatureFlags.TimedDND {
runDNDStatusExpireJob(app) runDNDStatusExpireJob(app)
@@ -788,10 +786,15 @@ func (s *Server) runJobs() {
// Global app options that should be applied to apps created by this server // Global app options that should be applied to apps created by this server
func (s *Server) AppOptions() []AppOption { func (s *Server) AppOptions() []AppOption {
return []AppOption{ return []AppOption{
ServerConnector(s), ServerConnector(s.Channels()),
} }
} }
func (s *Server) Channels() *Channels {
ch, _ := s.products["channels"].(*Channels)
return ch
}
// Return Database type (postgres or mysql) and current version of Mattermost // Return Database type (postgres or mysql) and current version of Mattermost
func (s *Server) DatabaseTypeAndMattermostVersion() (string, string) { func (s *Server) DatabaseTypeAndMattermostVersion() (string, string) {
mattermostVersion, _ := s.Store.System().GetByName("Version") mattermostVersion, _ := s.Store.System().GetByName("Version")
@@ -1957,7 +1960,7 @@ func (s *Server) TelemetryId() string {
} }
func (s *Server) HTTPService() httpservice.HTTPService { func (s *Server) HTTPService() httpservice.HTTPService {
return s.httpService return s.Channels().HTTPService()
} }
func (s *Server) SetLog(l *mlog.Logger) { func (s *Server) SetLog(l *mlog.Logger) {
@@ -2258,18 +2261,18 @@ func (s *Server) ReadFile(path string) ([]byte, *model.AppError) {
// } // }
func createDNDStatusExpirationRecurringTask(a *App) { func createDNDStatusExpirationRecurringTask(a *App) {
a.srv.dndTaskMut.Lock() a.ch.srv.dndTaskMut.Lock()
a.srv.dndTask = model.CreateRecurringTaskFromNextIntervalTime("Unset DND Statuses", a.UpdateDNDStatusOfUsers, 5*time.Minute) a.ch.srv.dndTask = model.CreateRecurringTaskFromNextIntervalTime("Unset DND Statuses", a.UpdateDNDStatusOfUsers, 5*time.Minute)
a.srv.dndTaskMut.Unlock() a.ch.srv.dndTaskMut.Unlock()
} }
func cancelDNDStatusExpirationRecurringTask(a *App) { func cancelDNDStatusExpirationRecurringTask(a *App) {
a.srv.dndTaskMut.Lock() a.ch.srv.dndTaskMut.Lock()
if a.srv.dndTask != nil { if a.ch.srv.dndTask != nil {
a.srv.dndTask.Cancel() a.ch.srv.dndTask.Cancel()
a.srv.dndTask = nil a.ch.srv.dndTask = nil
} }
a.srv.dndTaskMut.Unlock() a.ch.srv.dndTaskMut.Unlock()
} }
func runDNDStatusExpireJob(a *App) { func runDNDStatusExpireJob(a *App) {
@@ -2279,7 +2282,7 @@ func runDNDStatusExpireJob(a *App) {
if a.IsLeader() { if a.IsLeader() {
createDNDStatusExpirationRecurringTask(a) createDNDStatusExpirationRecurringTask(a)
} }
a.srv.AddClusterLeaderChangedListener(func() { a.ch.srv.AddClusterLeaderChangedListener(func() {
mlog.Info("Cluster leader changed. Determining if unset DNS status task should be running", mlog.Bool("isLeader", a.IsLeader())) mlog.Info("Cluster leader changed. Determining if unset DNS status task should be running", mlog.Bool("isLeader", a.IsLeader()))
if a.IsLeader() { if a.IsLeader() {
createDNDStatusExpirationRecurringTask(a) createDNDStatusExpirationRecurringTask(a)

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

@@ -771,7 +771,7 @@ func TestAdminAdvisor(t *testing.T) {
AuthService: "", AuthService: "",
Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId, Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId,
} }
ruser, err := th.App.srv.userService.CreateUser(&user, users.UserCreateOptions{FromImport: true}) ruser, err := th.App.ch.srv.userService.CreateUser(&user, users.UserCreateOptions{FromImport: true})
assert.NoError(t, err, "User should be created") assert.NoError(t, err, "User should be created")
userList = append(userList, ruser) userList = append(userList, ruser)
defer th.App.PermanentDeleteUser(th.Context, ruser) defer th.App.PermanentDeleteUser(th.Context, ruser)

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

@@ -18,7 +18,7 @@ import (
) )
func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppError) { func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppError) {
session, err := a.srv.userService.CreateSession(session) session, err := a.ch.srv.userService.CreateSession(session)
if err != nil { if err != nil {
var invErr *store.ErrInvalidInput var invErr *store.ErrInvalidInput
switch { switch {
@@ -66,13 +66,13 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) {
var session *model.Session var session *model.Session
// We intentionally skip the error check here, we only want to check if the token is valid. // We intentionally skip the error check here, we only want to check if the token is valid.
// If we don't have the session we are going to create one with the token eventually. // If we don't have the session we are going to create one with the token eventually.
if session, _ = a.srv.userService.GetSession(token); session != nil { if session, _ = a.ch.srv.userService.GetSession(token); session != nil {
if session.Token != token { if session.Token != token {
return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "session token is different from the one in DB", http.StatusUnauthorized) return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "session token is different from the one in DB", http.StatusUnauthorized)
} }
if !session.IsExpired() { if !session.IsExpired() {
a.srv.userService.AddSessionToCache(session) a.ch.srv.userService.AddSessionToCache(session)
} }
} }
@@ -124,7 +124,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) {
} }
func (a *App) GetSessions(userID string) ([]*model.Session, *model.AppError) { func (a *App) GetSessions(userID string) ([]*model.Session, *model.AppError) {
sessions, err := a.srv.userService.GetSessions(userID) sessions, err := a.ch.srv.userService.GetSessions(userID)
if err != nil { if err != nil {
return nil, model.NewAppError("GetSessions", "app.session.get_sessions.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetSessions", "app.session.get_sessions.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -133,7 +133,7 @@ func (a *App) GetSessions(userID string) ([]*model.Session, *model.AppError) {
} }
func (a *App) RevokeAllSessions(userID string) *model.AppError { func (a *App) RevokeAllSessions(userID string) *model.AppError {
if err := a.srv.userService.RevokeAllSessions(userID); err != nil { if err := a.ch.srv.userService.RevokeAllSessions(userID); err != nil {
switch { switch {
case errors.Is(err, users.GetSessionError): case errors.Is(err, users.GetSessionError):
return model.NewAppError("RevokeAllSessions", "app.session.get_sessions.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("RevokeAllSessions", "app.session.get_sessions.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -148,13 +148,13 @@ func (a *App) RevokeAllSessions(userID string) *model.AppError {
} }
func (a *App) AddSessionToCache(session *model.Session) { func (a *App) AddSessionToCache(session *model.Session) {
a.srv.userService.AddSessionToCache(session) a.ch.srv.userService.AddSessionToCache(session)
} }
// RevokeSessionsFromAllUsers will go through all the sessions active // RevokeSessionsFromAllUsers will go through all the sessions active
// in the server and revoke them // in the server and revoke them
func (a *App) RevokeSessionsFromAllUsers() *model.AppError { func (a *App) RevokeSessionsFromAllUsers() *model.AppError {
if err := a.srv.userService.RevokeSessionsFromAllUsers(); err != nil { if err := a.ch.srv.userService.RevokeSessionsFromAllUsers(); err != nil {
switch { switch {
case errors.Is(err, users.DeleteAllAccessDataError): case errors.Is(err, users.DeleteAllAccessDataError):
return model.NewAppError("RevokeSessionsFromAllUsers", "app.oauth.remove_access_data.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("RevokeSessionsFromAllUsers", "app.oauth.remove_access_data.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -167,15 +167,15 @@ func (a *App) RevokeSessionsFromAllUsers() *model.AppError {
} }
func (a *App) ReturnSessionToPool(session *model.Session) { func (a *App) ReturnSessionToPool(session *model.Session) {
a.srv.userService.ReturnSessionToPool(session) a.ch.srv.userService.ReturnSessionToPool(session)
} }
func (a *App) ClearSessionCacheForUser(userID string) { func (a *App) ClearSessionCacheForUser(userID string) {
a.srv.userService.ClearUserSessionCache(userID) a.ch.srv.userService.ClearUserSessionCache(userID)
} }
func (a *App) ClearSessionCacheForAllUsers() { func (a *App) ClearSessionCacheForAllUsers() {
a.srv.userService.ClearAllUsersSessionCache() a.ch.srv.userService.ClearAllUsersSessionCache()
} }
func (a *App) ClearSessionCacheForUserSkipClusterSend(userID string) { func (a *App) ClearSessionCacheForUserSkipClusterSend(userID string) {
@@ -187,7 +187,7 @@ func (a *App) ClearSessionCacheForAllUsersSkipClusterSend() {
} }
func (a *App) RevokeSessionsForDeviceId(userID string, deviceID string, currentSessionId string) *model.AppError { func (a *App) RevokeSessionsForDeviceId(userID string, deviceID string, currentSessionId string) *model.AppError {
if err := a.srv.userService.RevokeSessionsForDeviceId(userID, deviceID, currentSessionId); err != nil { if err := a.ch.srv.userService.RevokeSessionsForDeviceId(userID, deviceID, currentSessionId); err != nil {
return model.NewAppError("RevokeSessionsForDeviceId", "app.session.get_sessions.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("RevokeSessionsForDeviceId", "app.session.get_sessions.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -195,7 +195,7 @@ func (a *App) RevokeSessionsForDeviceId(userID string, deviceID string, currentS
} }
func (a *App) GetSessionById(sessionID string) (*model.Session, *model.AppError) { func (a *App) GetSessionById(sessionID string) (*model.Session, *model.AppError) {
session, err := a.srv.userService.GetSessionByID(sessionID) session, err := a.ch.srv.userService.GetSessionByID(sessionID)
if err != nil { if err != nil {
return nil, model.NewAppError("GetSessionById", "app.session.get.app_error", nil, err.Error(), http.StatusBadRequest) return nil, model.NewAppError("GetSessionById", "app.session.get.app_error", nil, err.Error(), http.StatusBadRequest)
} }
@@ -213,7 +213,7 @@ func (a *App) RevokeSessionById(sessionID string) *model.AppError {
} }
func (a *App) RevokeSession(session *model.Session) *model.AppError { func (a *App) RevokeSession(session *model.Session) *model.AppError {
if err := a.srv.userService.RevokeSession(session); err != nil { if err := a.ch.srv.userService.RevokeSession(session); err != nil {
switch { switch {
case errors.Is(err, users.DeleteSessionError): case errors.Is(err, users.DeleteSessionError):
return model.NewAppError("RevokeSession", "app.session.remove.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("RevokeSession", "app.session.remove.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -248,7 +248,7 @@ func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) {
} }
session.LastActivityAt = now session.LastActivityAt = now
a.srv.userService.AddSessionToCache(&session) a.ch.srv.userService.AddSessionToCache(&session)
} }
// ExtendSessionExpiryIfNeeded extends Session.ExpiresAt based on session lengths in config. // ExtendSessionExpiryIfNeeded extends Session.ExpiresAt based on session lengths in config.
@@ -296,7 +296,7 @@ func (a *App) ExtendSessionExpiryIfNeeded(session *model.Session) bool {
// ensures each node will get an extended expiry within the next 10 minutes. // ensures each node will get an extended expiry within the next 10 minutes.
// Worst case is another node may generate a redundant expiry update. // Worst case is another node may generate a redundant expiry update.
session.ExpiresAt = newExpiry session.ExpiresAt = newExpiry
a.srv.userService.AddSessionToCache(session) a.ch.srv.userService.AddSessionToCache(session)
mlog.Debug("Session extended", mlog.String("user_id", session.UserId), mlog.String("session_id", session.Id), mlog.Debug("Session extended", mlog.String("user_id", session.UserId), mlog.String("session_id", session.Id),
mlog.Int64("newExpiry", newExpiry), mlog.Int64("session_length", sessionLength)) mlog.Int64("newExpiry", newExpiry), mlog.Int64("session_length", sessionLength))
@@ -328,11 +328,11 @@ func (a *App) GetSessionLengthInMillis(session *model.Session) int64 {
// relative to either the session creation date or the current time, depending // relative to either the session creation date or the current time, depending
// on the `ExtendSessionOnActivity` config setting. // on the `ExtendSessionOnActivity` config setting.
func (a *App) SetSessionExpireInDays(session *model.Session, days int) { func (a *App) SetSessionExpireInDays(session *model.Session, days int) {
a.srv.userService.SetSessionExpireInDays(session, days) a.ch.srv.userService.SetSessionExpireInDays(session, days)
} }
func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) { func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) {
user, nErr := a.srv.userService.GetUser(token.UserId) user, nErr := a.ch.srv.userService.GetUser(token.UserId)
if nErr != nil { if nErr != nil {
var nfErr *store.ErrNotFound var nfErr *store.ErrNotFound
switch { switch {
@@ -417,7 +417,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio
} else { } else {
session.AddProp(model.SessionPropIsGuest, "false") session.AddProp(model.SessionPropIsGuest, "false")
} }
a.srv.userService.SetSessionExpireInDays(session, model.SessionUserAccessTokenExpiry) a.ch.srv.userService.SetSessionExpireInDays(session, model.SessionUserAccessTokenExpiry)
session, nErr = a.Srv().Store.Session().Save(session) session, nErr = a.Srv().Store.Session().Save(session)
if nErr != nil { if nErr != nil {
@@ -430,7 +430,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio
} }
} }
a.srv.userService.AddSessionToCache(session) a.ch.srv.userService.AddSessionToCache(session)
return session, nil return session, nil
@@ -438,7 +438,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio
func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError { func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError {
var session *model.Session var session *model.Session
session, _ = a.srv.userService.GetSessionContext(context.Background(), token.Token) session, _ = a.ch.srv.userService.GetSessionContext(context.Background(), token.Token)
if err := a.Srv().Store.UserAccessToken().Delete(token.Id); err != nil { if err := a.Srv().Store.UserAccessToken().Delete(token.Id); err != nil {
return model.NewAppError("RevokeUserAccessToken", "app.user_access_token.delete.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("RevokeUserAccessToken", "app.user_access_token.delete.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -453,7 +453,7 @@ func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppErro
func (a *App) DisableUserAccessToken(token *model.UserAccessToken) *model.AppError { func (a *App) DisableUserAccessToken(token *model.UserAccessToken) *model.AppError {
var session *model.Session var session *model.Session
session, _ = a.srv.userService.GetSessionContext(context.Background(), token.Token) session, _ = a.ch.srv.userService.GetSessionContext(context.Background(), token.Token)
if err := a.Srv().Store.UserAccessToken().UpdateTokenDisable(token.Id); err != nil { if err := a.Srv().Store.UserAccessToken().UpdateTokenDisable(token.Id); err != nil {
return model.NewAppError("DisableUserAccessToken", "app.user_access_token.update_token_disable.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("DisableUserAccessToken", "app.user_access_token.update_token_disable.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -468,7 +468,7 @@ func (a *App) DisableUserAccessToken(token *model.UserAccessToken) *model.AppErr
func (a *App) EnableUserAccessToken(token *model.UserAccessToken) *model.AppError { func (a *App) EnableUserAccessToken(token *model.UserAccessToken) *model.AppError {
var session *model.Session var session *model.Session
session, _ = a.srv.userService.GetSessionContext(context.Background(), token.Token) session, _ = a.ch.srv.userService.GetSessionContext(context.Background(), token.Token)
err := a.Srv().Store.UserAccessToken().UpdateTokenEnable(token.Id) err := a.Srv().Store.UserAccessToken().UpdateTokenEnable(token.Id)
if err != nil { if err != nil {

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

@@ -317,7 +317,7 @@ func TestApp_ExtendExpiryIfNeeded(t *testing.T) {
require.False(t, session.IsExpired()) require.False(t, session.IsExpired())
// check cache was updated // check cache was updated
cachedSession, errGet := th.App.srv.userService.GetSession(session.Token) cachedSession, errGet := th.App.ch.srv.userService.GetSession(session.Token)
require.NoError(t, errGet) require.NoError(t, errGet)
require.Equal(t, session.ExpiresAt, cachedSession.ExpiresAt) require.Equal(t, session.ExpiresAt, cachedSession.ExpiresAt)

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

@@ -18,9 +18,9 @@ func TestServerSyncSharedChannelHandler(t *testing.T) {
mockService := NewMockSharedChannelService(nil) mockService := NewMockSharedChannelService(nil)
mockService.active = false mockService.active = false
th.App.srv.SetSharedChannelSyncService(mockService) th.App.ch.srv.SetSharedChannelSyncService(mockService)
th.App.srv.SharedChannelSyncHandler(&model.WebSocketEvent{}) th.App.ch.srv.SharedChannelSyncHandler(&model.WebSocketEvent{})
assert.Empty(t, mockService.channelNotifications) assert.Empty(t, mockService.channelNotifications)
}) })
@@ -30,12 +30,12 @@ func TestServerSyncSharedChannelHandler(t *testing.T) {
mockService := NewMockSharedChannelService(nil) mockService := NewMockSharedChannelService(nil)
mockService.active = true mockService.active = true
th.App.srv.SetSharedChannelSyncService(mockService) th.App.ch.srv.SetSharedChannelSyncService(mockService)
channel := th.CreateChannel(th.BasicTeam, WithShared(true)) channel := th.CreateChannel(th.BasicTeam, WithShared(true))
websocketEvent := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, model.NewId(), channel.Id, "", nil) websocketEvent := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, model.NewId(), channel.Id, "", nil)
th.App.srv.SharedChannelSyncHandler(websocketEvent) th.App.ch.srv.SharedChannelSyncHandler(websocketEvent)
assert.Empty(t, mockService.channelNotifications) assert.Empty(t, mockService.channelNotifications)
}) })
@@ -45,11 +45,11 @@ func TestServerSyncSharedChannelHandler(t *testing.T) {
mockService := NewMockSharedChannelService(nil) mockService := NewMockSharedChannelService(nil)
mockService.active = true mockService.active = true
th.App.srv.SetSharedChannelSyncService(mockService) th.App.ch.srv.SetSharedChannelSyncService(mockService)
websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), model.NewId(), "", nil) websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), model.NewId(), "", nil)
th.App.srv.SharedChannelSyncHandler(websocketEvent) th.App.ch.srv.SharedChannelSyncHandler(websocketEvent)
assert.Empty(t, mockService.channelNotifications) assert.Empty(t, mockService.channelNotifications)
}) })
@@ -59,12 +59,12 @@ func TestServerSyncSharedChannelHandler(t *testing.T) {
mockService := NewMockSharedChannelService(nil) mockService := NewMockSharedChannelService(nil)
mockService.active = true mockService.active = true
th.App.srv.SetSharedChannelSyncService(mockService) th.App.ch.srv.SetSharedChannelSyncService(mockService)
channel := th.CreateChannel(th.BasicTeam, WithShared(true)) channel := th.CreateChannel(th.BasicTeam, WithShared(true))
websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), channel.Id, "", nil) websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), channel.Id, "", nil)
th.App.srv.SharedChannelSyncHandler(websocketEvent) th.App.ch.srv.SharedChannelSyncHandler(websocketEvent)
assert.Len(t, mockService.channelNotifications, 1) assert.Len(t, mockService.channelNotifications, 1)
assert.Equal(t, channel.Id, mockService.channelNotifications[0]) assert.Equal(t, channel.Id, mockService.channelNotifications[0])
}) })

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

@@ -38,10 +38,10 @@ func (a *App) SlackImport(c *request.Context, fileData multipart.File, fileSize
}, },
GenerateThumbnailImage: a.generateThumbnailImage, GenerateThumbnailImage: a.generateThumbnailImage,
GeneratePreviewImage: a.generatePreviewImage, GeneratePreviewImage: a.generatePreviewImage,
InvalidateAllCaches: func() { a.srv.InvalidateAllCaches() }, InvalidateAllCaches: func() { a.ch.srv.InvalidateAllCaches() },
MaxPostSize: func() int { return a.srv.MaxPostSize() }, MaxPostSize: func() int { return a.ch.srv.MaxPostSize() },
PrepareImage: func(fileData []byte) (image.Image, func(), error) { PrepareImage: func(fileData []byte) (image.Image, func(), error) {
img, release, err := prepareImage(a.srv.imgDecoder, bytes.NewReader(fileData)) img, release, err := prepareImage(a.ch.srv.imgDecoder, bytes.NewReader(fileData))
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@@ -49,7 +49,7 @@ func (a *App) SlackImport(c *request.Context, fileData multipart.File, fileSize
}, },
} }
importer := slackimport.New(a.srv.Store, actions, a.Config()) importer := slackimport.New(a.ch.srv.Store, actions, a.Config())
return importer.SlackImport(fileData, fileSize, teamID) return importer.SlackImport(fileData, fileSize, teamID)
} }

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

@@ -90,7 +90,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo
} }
th := &TestHelper{ th := &TestHelper{
App: app.New(app.ServerConnector(s)), App: app.New(app.ServerConnector(s.Channels())),
Context: &request.Context{}, Context: &request.Context{},
Server: s, Server: s,
LogBuffer: buffer, LogBuffer: buffer,

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

@@ -1969,7 +1969,7 @@ func (a *App) SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppEr
img = imaging.FillCenter(img, teamIconWidthAndHeight, teamIconWidthAndHeight) img = imaging.FillCenter(img, teamIconWidthAndHeight, teamIconWidthAndHeight)
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
err = a.srv.imgEncoder.EncodePNG(buf, img) err = a.Srv().imgEncoder.EncodePNG(buf, img)
if err != nil { if err != nil {
return model.NewAppError("SetTeamIcon", "api.team.set_team_icon.encode.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("SetTeamIcon", "api.team.set_team_icon.encode.app_error", nil, err.Error(), http.StatusInternalServerError)
} }

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

@@ -198,7 +198,7 @@ func (a *App) IsUserSignUpAllowed() *model.AppError {
} }
func (a *App) IsFirstUserAccount() bool { func (a *App) IsFirstUserAccount() bool {
return a.srv.userService.IsFirstUserAccount() return a.ch.srv.userService.IsFirstUserAccount()
} }
// CreateUser creates a user and sets several fields of the returned User struct to // CreateUser creates a user and sets several fields of the returned User struct to
@@ -214,7 +214,7 @@ func (a *App) CreateGuest(c *request.Context, user *model.User) (*model.User, *m
} }
func (a *App) createUserOrGuest(c *request.Context, user *model.User, guest bool) (*model.User, *model.AppError) { func (a *App) createUserOrGuest(c *request.Context, user *model.User, guest bool) (*model.User, *model.AppError) {
ruser, nErr := a.srv.userService.CreateUser(user, users.UserCreateOptions{Guest: guest}) ruser, nErr := a.ch.srv.userService.CreateUser(user, users.UserCreateOptions{Guest: guest})
if nErr != nil { if nErr != nil {
var appErr *model.AppError var appErr *model.AppError
var invErr *store.ErrInvalidInput var invErr *store.ErrInvalidInput
@@ -245,7 +245,7 @@ func (a *App) createUserOrGuest(c *request.Context, user *model.User, guest bool
if user.EmailVerified { if user.EmailVerified {
a.InvalidateCacheForUser(ruser.Id) a.InvalidateCacheForUser(ruser.Id)
nUser, err := a.srv.userService.GetUser(ruser.Id) nUser, err := a.ch.srv.userService.GetUser(ruser.Id)
if err != nil { if err != nil {
var nfErr *store.ErrNotFound var nfErr *store.ErrNotFound
switch { switch {
@@ -305,18 +305,18 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re
found := true found := true
count := 0 count := 0
for found { for found {
if found = a.srv.userService.IsUsernameTaken(user.Username); found { if found = a.ch.srv.userService.IsUsernameTaken(user.Username); found {
user.Username = user.Username + strconv.Itoa(count) user.Username = user.Username + strconv.Itoa(count)
count++ count++
} }
} }
userByAuth, _ := a.srv.userService.GetUserByAuth(user.AuthData, service) userByAuth, _ := a.ch.srv.userService.GetUserByAuth(user.AuthData, service)
if userByAuth != nil { if userByAuth != nil {
return userByAuth, nil return userByAuth, nil
} }
userByEmail, _ := a.srv.userService.GetUserByEmail(user.Email) userByEmail, _ := a.ch.srv.userService.GetUserByEmail(user.Email)
if userByEmail != nil { if userByEmail != nil {
if userByEmail.AuthService == "" { if userByEmail.AuthService == "" {
return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]interface{}{"Service": service, "Auth": model.UserAuthServiceEmail}, "email="+user.Email, http.StatusBadRequest) return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]interface{}{"Service": service, "Auth": model.UserAuthServiceEmail}, "email="+user.Email, http.StatusBadRequest)
@@ -354,7 +354,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re
} }
func (a *App) GetUser(userID string) (*model.User, *model.AppError) { func (a *App) GetUser(userID string) (*model.User, *model.AppError) {
user, err := a.srv.userService.GetUser(userID) user, err := a.ch.srv.userService.GetUser(userID)
if err != nil { if err != nil {
var nfErr *store.ErrNotFound var nfErr *store.ErrNotFound
switch { switch {
@@ -369,7 +369,7 @@ func (a *App) GetUser(userID string) (*model.User, *model.AppError) {
} }
func (a *App) GetUserByUsername(username string) (*model.User, *model.AppError) { func (a *App) GetUserByUsername(username string) (*model.User, *model.AppError) {
result, err := a.srv.userService.GetUserByUsername(username) result, err := a.ch.srv.userService.GetUserByUsername(username)
if err != nil { if err != nil {
var nfErr *store.ErrNotFound var nfErr *store.ErrNotFound
switch { switch {
@@ -383,7 +383,7 @@ func (a *App) GetUserByUsername(username string) (*model.User, *model.AppError)
} }
func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) { func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) {
user, err := a.srv.userService.GetUserByEmail(email) user, err := a.ch.srv.userService.GetUserByEmail(email)
if err != nil { if err != nil {
var nfErr *store.ErrNotFound var nfErr *store.ErrNotFound
switch { switch {
@@ -397,7 +397,7 @@ func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) {
} }
func (a *App) GetUserByAuth(authData *string, authService string) (*model.User, *model.AppError) { func (a *App) GetUserByAuth(authData *string, authService string) (*model.User, *model.AppError) {
user, err := a.srv.userService.GetUserByAuth(authData, authService) user, err := a.ch.srv.userService.GetUserByAuth(authData, authService)
if err != nil { if err != nil {
var invErr *store.ErrInvalidInput var invErr *store.ErrInvalidInput
var nfErr *store.ErrNotFound var nfErr *store.ErrNotFound
@@ -415,7 +415,7 @@ func (a *App) GetUserByAuth(authData *string, authService string) (*model.User,
} }
func (a *App) GetUsers(options *model.UserGetOptions) ([]*model.User, *model.AppError) { func (a *App) GetUsers(options *model.UserGetOptions) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsers(options) users, err := a.ch.srv.userService.GetUsers(options)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsers", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsers", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -424,7 +424,7 @@ func (a *App) GetUsers(options *model.UserGetOptions) ([]*model.User, *model.App
} }
func (a *App) GetUsersPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) { func (a *App) GetUsersPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersPage(options, asAdmin) users, err := a.ch.srv.userService.GetUsersPage(options, asAdmin)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersPage", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersPage", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -433,11 +433,11 @@ func (a *App) GetUsersPage(options *model.UserGetOptions, asAdmin bool) ([]*mode
} }
func (a *App) GetUsersEtag(restrictionsHash string) string { func (a *App) GetUsersEtag(restrictionsHash string) string {
return a.srv.userService.GetUsersEtag(restrictionsHash) return a.ch.srv.userService.GetUsersEtag(restrictionsHash)
} }
func (a *App) GetUsersInTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) { func (a *App) GetUsersInTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersInTeam(options) users, err := a.ch.srv.userService.GetUsersInTeam(options)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersInTeam", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersInTeam", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -446,7 +446,7 @@ func (a *App) GetUsersInTeam(options *model.UserGetOptions) ([]*model.User, *mod
} }
func (a *App) GetUsersNotInTeam(teamID string, groupConstrained bool, offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { func (a *App) GetUsersNotInTeam(teamID string, groupConstrained bool, offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersNotInTeam(teamID, groupConstrained, offset, limit, viewRestrictions) users, err := a.ch.srv.userService.GetUsersNotInTeam(teamID, groupConstrained, offset, limit, viewRestrictions)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersNotInTeam", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersNotInTeam", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -455,7 +455,7 @@ func (a *App) GetUsersNotInTeam(teamID string, groupConstrained bool, offset int
} }
func (a *App) GetUsersInTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) { func (a *App) GetUsersInTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersInTeamPage(options, asAdmin) users, err := a.ch.srv.userService.GetUsersInTeamPage(options, asAdmin)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersInTeamPage", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersInTeamPage", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -464,7 +464,7 @@ func (a *App) GetUsersInTeamPage(options *model.UserGetOptions, asAdmin bool) ([
} }
func (a *App) GetUsersNotInTeamPage(teamID string, groupConstrained bool, page int, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { func (a *App) GetUsersNotInTeamPage(teamID string, groupConstrained bool, page int, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersNotInTeamPage(teamID, groupConstrained, page*perPage, perPage, asAdmin, viewRestrictions) users, err := a.ch.srv.userService.GetUsersNotInTeamPage(teamID, groupConstrained, page*perPage, perPage, asAdmin, viewRestrictions)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersNotInTeamPage", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersNotInTeamPage", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -473,11 +473,11 @@ func (a *App) GetUsersNotInTeamPage(teamID string, groupConstrained bool, page i
} }
func (a *App) GetUsersInTeamEtag(teamID string, restrictionsHash string) string { func (a *App) GetUsersInTeamEtag(teamID string, restrictionsHash string) string {
return a.srv.userService.GetUsersInTeamEtag(teamID, restrictionsHash) return a.ch.srv.userService.GetUsersInTeamEtag(teamID, restrictionsHash)
} }
func (a *App) GetUsersNotInTeamEtag(teamID string, restrictionsHash string) string { func (a *App) GetUsersNotInTeamEtag(teamID string, restrictionsHash string) string {
return a.srv.userService.GetUsersNotInTeamEtag(teamID, restrictionsHash) return a.ch.srv.userService.GetUsersNotInTeamEtag(teamID, restrictionsHash)
} }
func (a *App) GetUsersInChannel(options *model.UserGetOptions) ([]*model.User, *model.AppError) { func (a *App) GetUsersInChannel(options *model.UserGetOptions) ([]*model.User, *model.AppError) {
@@ -565,7 +565,7 @@ func (a *App) GetUsersNotInChannelPage(teamID string, channelID string, groupCon
} }
func (a *App) GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) { func (a *App) GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersWithoutTeamPage(options, asAdmin) users, err := a.ch.srv.userService.GetUsersWithoutTeamPage(options, asAdmin)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersWithoutTeamPage", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersWithoutTeamPage", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -574,7 +574,7 @@ func (a *App) GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin boo
} }
func (a *App) GetUsersWithoutTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) { func (a *App) GetUsersWithoutTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersWithoutTeam(options) users, err := a.ch.srv.userService.GetUsersWithoutTeam(options)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersWithoutTeam", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersWithoutTeam", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -603,7 +603,7 @@ func (a *App) GetChannelGroupUsers(channelID string) ([]*model.User, *model.AppE
} }
func (a *App) GetUsersByIds(userIDs []string, options *store.UserGetByIdsOpts) ([]*model.User, *model.AppError) { func (a *App) GetUsersByIds(userIDs []string, options *store.UserGetByIdsOpts) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersByIds(userIDs, options) users, err := a.ch.srv.userService.GetUsersByIds(userIDs, options)
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersByIds", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersByIds", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -624,7 +624,7 @@ func (a *App) GetUsersByGroupChannelIds(c *request.Context, channelIDs []string,
} }
func (a *App) GetUsersByUsernames(usernames []string, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { func (a *App) GetUsersByUsernames(usernames []string, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) {
users, err := a.srv.userService.GetUsersByUsernames(usernames, &model.UserGetOptions{ViewRestrictions: viewRestrictions}) users, err := a.ch.srv.userService.GetUsersByUsernames(usernames, &model.UserGetOptions{ViewRestrictions: viewRestrictions})
if err != nil { if err != nil {
return nil, model.NewAppError("GetUsersByUsernames", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GetUsersByUsernames", "app.user.get_profiles.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -649,7 +649,7 @@ func (a *App) GenerateMfaSecret(userID string) (*model.MfaSecret, *model.AppErro
return nil, model.NewAppError("GenerateMfaSecret", "mfa.mfa_disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GenerateMfaSecret", "mfa.mfa_disabled.app_error", nil, "", http.StatusNotImplemented)
} }
mfaSecret, err := a.srv.userService.GenerateMfaSecret(user) mfaSecret, err := a.ch.srv.userService.GenerateMfaSecret(user)
if err != nil { if err != nil {
return nil, model.NewAppError("GenerateMfaSecret", "mfa.generate_qr_code.create_code.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("GenerateMfaSecret", "mfa.generate_qr_code.create_code.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -671,7 +671,7 @@ func (a *App) ActivateMfa(userID, token string) *model.AppError {
return model.NewAppError("ActivateMfa", "mfa.mfa_disabled.app_error", nil, "", http.StatusNotImplemented) return model.NewAppError("ActivateMfa", "mfa.mfa_disabled.app_error", nil, "", http.StatusNotImplemented)
} }
if err := a.srv.userService.ActivateMfa(user, token); err != nil { if err := a.ch.srv.userService.ActivateMfa(user, token); err != nil {
switch { switch {
case errors.Is(err, mfa.InvalidToken): case errors.Is(err, mfa.InvalidToken):
return model.NewAppError("ActivateMfa", "mfa.activate.bad_token.app_error", nil, "", http.StatusUnauthorized) return model.NewAppError("ActivateMfa", "mfa.activate.bad_token.app_error", nil, "", http.StatusUnauthorized)
@@ -692,7 +692,7 @@ func (a *App) DeactivateMfa(userID string) *model.AppError {
return appErr return appErr
} }
if err := a.srv.userService.DeactivateMfa(user); err != nil { if err := a.ch.srv.userService.DeactivateMfa(user); err != nil {
return model.NewAppError("DeactivateMfa", "mfa.deactivate.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("DeactivateMfa", "mfa.deactivate.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -703,11 +703,11 @@ func (a *App) DeactivateMfa(userID string) *model.AppError {
} }
func (a *App) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) { func (a *App) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) {
return a.srv.GetProfileImage(user) return a.ch.srv.GetProfileImage(user)
} }
func (a *App) GetDefaultProfileImage(user *model.User) ([]byte, *model.AppError) { func (a *App) GetDefaultProfileImage(user *model.User) ([]byte, *model.AppError) {
return a.srv.GetDefaultProfileImage(user) return a.ch.srv.GetDefaultProfileImage(user)
} }
func (a *App) SetDefaultProfileImage(user *model.User) *model.AppError { func (a *App) SetDefaultProfileImage(user *model.User) *model.AppError {
@@ -762,7 +762,7 @@ func (a *App) SetProfileImageFromMultiPartFile(userID string, file multipart.Fil
func (a *App) AdjustImage(file io.Reader) (*bytes.Buffer, *model.AppError) { func (a *App) AdjustImage(file io.Reader) (*bytes.Buffer, *model.AppError) {
// Decode image into Image object // Decode image into Image object
img, _, err := a.srv.imgDecoder.Decode(file) img, _, err := a.ch.srv.imgDecoder.Decode(file)
if err != nil { if err != nil {
return nil, model.NewAppError("SetProfileImage", "api.user.upload_profile_user.decode.app_error", nil, err.Error(), http.StatusBadRequest) return nil, model.NewAppError("SetProfileImage", "api.user.upload_profile_user.decode.app_error", nil, err.Error(), http.StatusBadRequest)
} }
@@ -775,7 +775,7 @@ func (a *App) AdjustImage(file io.Reader) (*bytes.Buffer, *model.AppError) {
img = imaging.FillCenter(img, profileWidthAndHeight, profileWidthAndHeight) img = imaging.FillCenter(img, profileWidthAndHeight, profileWidthAndHeight)
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
err = a.srv.imgEncoder.EncodePNG(buf, img) err = a.ch.srv.imgEncoder.EncodePNG(buf, img)
if err != nil { if err != nil {
return nil, model.NewAppError("SetProfileImage", "api.user.upload_profile_user.encode.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("SetProfileImage", "api.user.upload_profile_user.encode.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -884,7 +884,7 @@ func (a *App) UpdateActive(c *request.Context, user *model.User, active bool) (*
user.DeleteAt = user.UpdateAt user.DeleteAt = user.UpdateAt
} }
userUpdate, err := a.srv.userService.UpdateUser(user, true) userUpdate, err := a.ch.srv.userService.UpdateUser(user, true)
if err != nil { if err != nil {
var appErr *model.AppError var appErr *model.AppError
var invErr *store.ErrInvalidInput var invErr *store.ErrInvalidInput
@@ -917,7 +917,7 @@ func (a *App) UpdateActive(c *request.Context, user *model.User, active bool) (*
} }
func (a *App) DeactivateGuests(c *request.Context) *model.AppError { func (a *App) DeactivateGuests(c *request.Context) *model.AppError {
userIDs, err := a.srv.userService.DeactivateAllGuests() userIDs, err := a.ch.srv.userService.DeactivateAllGuests()
if err != nil { if err != nil {
return model.NewAppError("DeactivateGuests", "app.user.update_active_for_multiple_users.updating.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("DeactivateGuests", "app.user.update_active_for_multiple_users.updating.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -938,11 +938,11 @@ func (a *App) DeactivateGuests(c *request.Context) *model.AppError {
} }
func (a *App) GetSanitizeOptions(asAdmin bool) map[string]bool { func (a *App) GetSanitizeOptions(asAdmin bool) map[string]bool {
return a.srv.userService.GetSanitizeOptions(asAdmin) return a.ch.srv.userService.GetSanitizeOptions(asAdmin)
} }
func (a *App) SanitizeProfile(user *model.User, asAdmin bool) { func (a *App) SanitizeProfile(user *model.User, asAdmin bool) {
options := a.srv.userService.GetSanitizeOptions(asAdmin) options := a.ch.srv.userService.GetSanitizeOptions(asAdmin)
user.SanitizeProfile(options) user.SanitizeProfile(options)
} }
@@ -1034,7 +1034,7 @@ func (a *App) sendUpdatedUserEvent(user model.User) {
} }
func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) { func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) {
prev, err := a.srv.userService.GetUser(user.Id) prev, err := a.ch.srv.userService.GetUser(user.Id)
if err != nil { if err != nil {
var nfErr *store.ErrNotFound var nfErr *store.ErrNotFound
switch { switch {
@@ -1077,7 +1077,7 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User,
} }
} }
userUpdate, err := a.srv.userService.UpdateUser(user, false) userUpdate, err := a.ch.srv.userService.UpdateUser(user, false)
if err != nil { if err != nil {
var appErr *model.AppError var appErr *model.AppError
var invErr *store.ErrInvalidInput var invErr *store.ErrInvalidInput
@@ -1144,7 +1144,7 @@ func (a *App) UpdateUserActive(c *request.Context, userID string, active bool) *
} }
func (a *App) updateUserNotifyProps(userID string, props map[string]string) *model.AppError { func (a *App) updateUserNotifyProps(userID string, props map[string]string) *model.AppError {
err := a.srv.userService.UpdateUserNotifyProps(userID, props) err := a.ch.srv.userService.UpdateUserNotifyProps(userID, props)
if err != nil { if err != nil {
var appErr *model.AppError var appErr *model.AppError
switch { switch {
@@ -2035,7 +2035,7 @@ func (a *App) GetViewUsersRestrictions(userID string) (*model.ViewUsersRestricti
// PromoteGuestToUser Convert user's roles and all his mermbership's roles from // PromoteGuestToUser Convert user's roles and all his mermbership's roles from
// guest roles to regular user roles. // guest roles to regular user roles.
func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestorId string) *model.AppError { func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestorId string) *model.AppError {
nErr := a.srv.userService.PromoteGuestToUser(user) nErr := a.ch.srv.userService.PromoteGuestToUser(user)
a.InvalidateCacheForUser(user.Id) a.InvalidateCacheForUser(user.Id)
if nErr != nil { if nErr != nil {
return model.NewAppError("PromoteGuestToUser", "app.user.promote_guest.user_update.app_error", nil, nErr.Error(), http.StatusInternalServerError) return model.NewAppError("PromoteGuestToUser", "app.user.promote_guest.user_update.app_error", nil, nErr.Error(), http.StatusInternalServerError)
@@ -2057,7 +2057,7 @@ func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestor
mlog.Warn("Failed to get user on promote guest to user", mlog.Err(err)) mlog.Warn("Failed to get user on promote guest to user", mlog.Err(err))
} else { } else {
a.sendUpdatedUserEvent(*promotedUser) a.sendUpdatedUserEvent(*promotedUser)
if uErr := a.srv.userService.UpdateSessionsIsGuest(promotedUser.Id, promotedUser.IsGuest()); uErr != nil { if uErr := a.ch.srv.userService.UpdateSessionsIsGuest(promotedUser.Id, promotedUser.IsGuest()); uErr != nil {
mlog.Warn("Unable to update user sessions", mlog.String("user_id", promotedUser.Id), mlog.Err(uErr)) mlog.Warn("Unable to update user sessions", mlog.String("user_id", promotedUser.Id), mlog.Err(uErr))
} }
} }
@@ -2095,14 +2095,14 @@ func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestor
// DemoteUserToGuest Convert user's roles and all his mermbership's roles from // DemoteUserToGuest Convert user's roles and all his mermbership's roles from
// regular user roles to guest roles. // regular user roles to guest roles.
func (a *App) DemoteUserToGuest(user *model.User) *model.AppError { func (a *App) DemoteUserToGuest(user *model.User) *model.AppError {
demotedUser, nErr := a.srv.userService.DemoteUserToGuest(user) demotedUser, nErr := a.ch.srv.userService.DemoteUserToGuest(user)
a.InvalidateCacheForUser(user.Id) a.InvalidateCacheForUser(user.Id)
if nErr != nil { if nErr != nil {
return model.NewAppError("DemoteUserToGuest", "app.user.demote_user_to_guest.user_update.app_error", nil, nErr.Error(), http.StatusInternalServerError) return model.NewAppError("DemoteUserToGuest", "app.user.demote_user_to_guest.user_update.app_error", nil, nErr.Error(), http.StatusInternalServerError)
} }
a.sendUpdatedUserEvent(*demotedUser) a.sendUpdatedUserEvent(*demotedUser)
if uErr := a.srv.userService.UpdateSessionsIsGuest(demotedUser.Id, demotedUser.IsGuest()); uErr != nil { if uErr := a.ch.srv.userService.UpdateSessionsIsGuest(demotedUser.Id, demotedUser.IsGuest()); uErr != nil {
mlog.Warn("Unable to update user sessions", mlog.String("user_id", demotedUser.Id), mlog.Err(uErr)) mlog.Warn("Unable to update user sessions", mlog.String("user_id", demotedUser.Id), mlog.Err(uErr))
} }

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

@@ -1554,12 +1554,12 @@ func TestUpdateThreadReadForUser(t *testing.T) {
mockThreadStore.On("MaintainMembership", "user1", "postid", mock.Anything).Return(nil, errors.New("error")) mockThreadStore.On("MaintainMembership", "user1", "postid", mock.Anything).Return(nil, errors.New("error"))
var err error var err error
th.App.srv.userService, err = users.New(users.ServiceConfig{ th.App.ch.srv.userService, err = users.New(users.ServiceConfig{
UserStore: &mockUserStore, UserStore: &mockUserStore,
SessionStore: &storemocks.SessionStore{}, SessionStore: &storemocks.SessionStore{},
OAuthStore: &storemocks.OAuthStore{}, OAuthStore: &storemocks.OAuthStore{},
ConfigFn: th.App.srv.Config, ConfigFn: th.App.ch.srv.Config,
LicenseFn: th.App.srv.License, LicenseFn: th.App.ch.srv.License,
}) })
require.NoError(t, err) require.NoError(t, err)
mockStore.On("User").Return(&mockUserStore) mockStore.On("User").Return(&mockUserStore)

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

@@ -172,7 +172,7 @@ func (a *App) NewWebConn(cfg *WebConnConfig) *WebConn {
cfg.activeQueue = make(chan model.WebSocketMessage, sendQueueSize) cfg.activeQueue = make(chan model.WebSocketMessage, sendQueueSize)
} }
if cfg.deadQueue == nil && *a.srv.Config().ServiceSettings.EnableReliableWebSockets { if cfg.deadQueue == nil && *a.ch.srv.Config().ServiceSettings.EnableReliableWebSockets {
cfg.deadQueue = make([]*model.WebSocketEvent, deadQueueSize) cfg.deadQueue = make([]*model.WebSocketEvent, deadQueueSize)
} }
@@ -287,7 +287,7 @@ func (wc *WebConn) SetSession(v *model.Session) {
// Pump starts the WebConn instance. After this, the websocket // Pump starts the WebConn instance. After this, the websocket
// is ready to send/receive messages. // is ready to send/receive messages.
func (wc *WebConn) Pump() { func (wc *WebConn) Pump() {
defer wc.App.srv.userService.ReturnSessionToPool(wc.GetSession()) defer wc.App.Srv().userService.ReturnSessionToPool(wc.GetSession())
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(1) wg.Add(1)
@@ -365,7 +365,7 @@ func (wc *WebConn) writePump() {
wc.WebSocket.Close() wc.WebSocket.Close()
}() }()
if *wc.App.srv.Config().ServiceSettings.EnableReliableWebSockets && wc.Sequence != 0 { if *wc.App.Srv().Config().ServiceSettings.EnableReliableWebSockets && wc.Sequence != 0 {
if ok, index := wc.isInDeadQueue(wc.Sequence); ok { if ok, index := wc.isInDeadQueue(wc.Sequence); ok {
if err := wc.drainDeadQueue(index); err != nil { if err := wc.drainDeadQueue(index); err != nil {
wc.logSocketErr("websocket.drainDeadQueue", err) wc.logSocketErr("websocket.drainDeadQueue", err)
@@ -462,7 +462,7 @@ func (wc *WebConn) writePump() {
mlog.Warn("websocket.full", logData...) mlog.Warn("websocket.full", logData...)
} }
if *wc.App.srv.Config().ServiceSettings.EnableReliableWebSockets && if *wc.App.Srv().Config().ServiceSettings.EnableReliableWebSockets &&
evtOk { evtOk {
wc.addToDeadQueue(evt) wc.addToDeadQueue(evt)
} }

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

@@ -101,7 +101,7 @@ func (a *App) HubStart() {
} }
// Assigning to the hubs slice without any mutex is fine because it is only assigned once // Assigning to the hubs slice without any mutex is fine because it is only assigned once
// during the start of the program and always read from after that. // during the start of the program and always read from after that.
a.srv.hubs = hubs a.ch.srv.hubs = hubs
} }
func (a *App) invalidateCacheForWebhook(webhookID string) { func (a *App) invalidateCacheForWebhook(webhookID string) {
@@ -259,7 +259,7 @@ func (a *App) invalidateCacheForChannelPosts(channelID string) {
func (a *App) InvalidateCacheForUser(userID string) { func (a *App) InvalidateCacheForUser(userID string) {
a.Srv().invalidateCacheForUserSkipClusterSend(userID) a.Srv().invalidateCacheForUserSkipClusterSend(userID)
a.srv.userService.InvalidateCacheForUser(userID) a.ch.srv.userService.InvalidateCacheForUser(userID)
} }
func (a *App) invalidateCacheForUserTeams(userID string) { func (a *App) invalidateCacheForUserTeams(userID string) {

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

@@ -165,13 +165,13 @@ func TestHubSessionRevokeRace(t *testing.T) {
UserStore: &mockUserStore, UserStore: &mockUserStore,
SessionStore: &mockSessionStore, SessionStore: &mockSessionStore,
OAuthStore: &mockOAuthStore, OAuthStore: &mockOAuthStore,
ConfigFn: th.App.srv.Config, ConfigFn: th.App.ch.srv.Config,
Metrics: th.App.Metrics(), Metrics: th.App.Metrics(),
Cluster: th.App.Cluster(), Cluster: th.App.Cluster(),
LicenseFn: th.App.srv.License, LicenseFn: th.App.ch.srv.License,
}) })
require.NoError(t, err) require.NoError(t, err)
th.App.srv.userService = userService th.App.ch.srv.userService = userService
// This needs to be false for the condition to trigger // This needs to be false for the condition to trigger
th.App.UpdateConfig(func(cfg *model.Config) { th.App.UpdateConfig(func(cfg *model.Config) {
@@ -189,7 +189,7 @@ func TestHubSessionRevokeRace(t *testing.T) {
time.Sleep(time.Second) time.Sleep(time.Second)
// We override the LastActivityAt which happens in NewWebConn. // We override the LastActivityAt which happens in NewWebConn.
// This is needed to call RevokeSessionById which triggers the race. // This is needed to call RevokeSessionById which triggers the race.
th.App.srv.userService.AddSessionToCache(sess1) th.App.ch.srv.userService.AddSessionToCache(sess1)
go func() { go func() {
for i := 0; i <= broadcastQueueSize; i++ { for i := 0; i <= broadcastQueueSize; i++ {

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

@@ -49,7 +49,7 @@ func initDBCommandContext(configDSN string, readOnlyConfigStore bool) (*app.App,
return nil, err return nil, err
} }
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
if model.BuildEnterpriseReady == "true" { if model.BuildEnterpriseReady == "true" {
a.Srv().LoadLicense() a.Srv().LoadLicense()

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

@@ -93,7 +93,7 @@ func runServer(configStore *config.Store, interruptChan chan os.Signal) error {
} }
}() }()
a := app.New(app.ServerConnector(server)) a := app.New(app.ServerConnector(server.Channels()))
api := api4.Init(a, server.Router) api := api4.Init(a, server.Router)
wsapi.Init(server) wsapi.Init(server)

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

@@ -28,7 +28,7 @@ type Worker struct {
func init() { func init() {
app.RegisterJobsActiveUsersInterface(func(s *app.Server) tjobs.ActiveUsersJobInterface { app.RegisterJobsActiveUsersInterface(func(s *app.Server) tjobs.ActiveUsersJobInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ActiveUsersJobInterfaceImpl{a} return &ActiveUsersJobInterfaceImpl{a}
}) })
} }

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

@@ -14,7 +14,7 @@ type ExpiryNotifyJobInterfaceImpl struct {
func init() { func init() {
app.RegisterJobsExpiryNotifyJobInterface(func(s *app.Server) tjobs.ExpiryNotifyJobInterface { app.RegisterJobsExpiryNotifyJobInterface(func(s *app.Server) tjobs.ExpiryNotifyJobInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ExpiryNotifyJobInterfaceImpl{a} return &ExpiryNotifyJobInterfaceImpl{a}
}) })
} }

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

@@ -16,7 +16,7 @@ import (
func init() { func init() {
app.RegisterJobsExportDeleteInterface(func(s *app.Server) tjobs.ExportDeleteInterface { app.RegisterJobsExportDeleteInterface(func(s *app.Server) tjobs.ExportDeleteInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ExportDeleteInterfaceImpl{a} return &ExportDeleteInterfaceImpl{a}
}) })
} }

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

@@ -16,7 +16,7 @@ import (
func init() { func init() {
app.RegisterJobsExportProcessInterface(func(s *app.Server) tjobs.ExportProcessInterface { app.RegisterJobsExportProcessInterface(func(s *app.Server) tjobs.ExportProcessInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ExportProcessInterfaceImpl{a} return &ExportProcessInterfaceImpl{a}
}) })
} }

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

@@ -24,7 +24,7 @@ var ignoredFiles = map[string]bool{
func init() { func init() {
app.RegisterJobsExtractContentInterface(func(s *app.Server) tjobs.ExtractContentInterface { app.RegisterJobsExtractContentInterface(func(s *app.Server) tjobs.ExtractContentInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ExtractContentInterfaceImpl{a} return &ExtractContentInterfaceImpl{a}
}) })
} }

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

@@ -18,7 +18,7 @@ import (
func init() { func init() {
app.RegisterJobsImportDeleteInterface(func(s *app.Server) tjobs.ImportDeleteInterface { app.RegisterJobsImportDeleteInterface(func(s *app.Server) tjobs.ImportDeleteInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ImportDeleteInterfaceImpl{a} return &ImportDeleteInterfaceImpl{a}
}) })
} }

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

@@ -22,7 +22,7 @@ import (
func init() { func init() {
app.RegisterJobsImportProcessInterface(func(s *app.Server) tjobs.ImportProcessInterface { app.RegisterJobsImportProcessInterface(func(s *app.Server) tjobs.ImportProcessInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ImportProcessInterfaceImpl{a} return &ImportProcessInterfaceImpl{a}
}) })
} }

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

@@ -14,7 +14,7 @@ type ProductNoticesJobInterfaceImpl struct {
func init() { func init() {
app.RegisterProductNoticesJobInterface(func(s *app.Server) tjobs.ProductNoticesJobInterface { app.RegisterProductNoticesJobInterface(func(s *app.Server) tjobs.ProductNoticesJobInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ProductNoticesJobInterfaceImpl{a} return &ProductNoticesJobInterfaceImpl{a}
}) })
} }

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

@@ -13,7 +13,7 @@ type ResendInvitationEmailJobInterfaceImpl struct {
func init() { func init() {
app.RegisterJobsResendInvitationEmailInterface(func(s *app.Server) ejobs.ResendInvitationEmailJobInterface { app.RegisterJobsResendInvitationEmailInterface(func(s *app.Server) ejobs.ResendInvitationEmailJobInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &ResendInvitationEmailJobInterfaceImpl{a} return &ResendInvitationEmailJobInterfaceImpl{a}
}) })
} }

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

@@ -67,7 +67,7 @@ func setupTestHelper(enterprise bool) *TestHelper {
} }
th := &TestHelper{ th := &TestHelper{
App: app.New(app.ServerConnector(s)), App: app.New(app.ServerConnector(s.Channels())),
Context: &request.Context{}, Context: &request.Context{},
Server: s, Server: s,
TestLogger: testLogger, TestLogger: testLogger,

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

@@ -14,7 +14,7 @@ type PluginsJobInterfaceImpl struct {
func init() { func init() {
app.RegisterJobsPluginsJobInterface(func(s *app.Server) tjobs.PluginsJobInterface { app.RegisterJobsPluginsJobInterface(func(s *app.Server) tjobs.PluginsJobInterface {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
return &PluginsJobInterfaceImpl{a} return &PluginsJobInterfaceImpl{a}
}) })
} }

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

@@ -120,7 +120,7 @@ func setupTestHelper(tb testing.TB, includeCacheLayer bool) *TestHelper {
}) })
ctx := &request.Context{} ctx := &request.Context{}
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
web := New(a, s.Router) web := New(a, s.Router)
URL = fmt.Sprintf("http://localhost:%v", s.ListenAddr.Port) URL = fmt.Sprintf("http://localhost:%v", s.ListenAddr.Port)

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

@@ -13,7 +13,7 @@ type API struct {
} }
func Init(s *app.Server) { func Init(s *app.Server) {
a := app.New(app.ServerConnector(s)) a := app.New(app.ServerConnector(s.Channels()))
api := &API{ api := &API{
App: a, App: a,
Router: s.WebSocketRouter, Router: s.WebSocketRouter,