We implement a cursor based pagination model
to page through the posts in a given thread.
The cursor is a combination of the post.CreateAt+
post.Id to differentiate multiple posts in a given
timestamp.
Some additional parameters like direction, fromPost,
fromCreateAt and perPage were introduced to implement
this.
```release-note
NONE
```
Due to the way our community deployment is done. The job server
is restarted every day. This means that whenever there is a job
that takes more than 24 hours, it will always get cancelled
when the server restarts and therefore will never finish.
This PR adds ability to resume any stopped jobs, by storing
intermediate progress in the job metadata and setting
the job to pending instead of cancelled when everything is
shut down.
The user can still cancel a job explicitly by clicking on
the cross button in the system console. That functionality
hasn't changed. Only server stop or stopping/starting
job server via config will pause/resume jobs.
```release-note
The elasticsearch indexing job is resumable now. Stopping a
server while the job is running will put the job in pending status
and will resume the job when the server starts.
The job can still be explicitly cancelled via the system console UI.
```
* revamp db version and add applied migrations endpoint
* replace old schema version with new
* add db version subcommand
* add to local api
* reflect review comments
* log errors
* remove setting the version from model.CurrentVersion
* fix a test
* use different field for schema version
* add build hash and current version to the support packet
* add tests
* update test to use new assets
* MM-42282: handle teamId parameter correctly
As per https://community-daily.mattermost.com/core/pl/ugs7ue6e4j8a7cgegk1bxje8to, `ThreadStore.GetThreadsForUser` accepts a `teamId` parameter, but incorrectly handles an empty value of `""` as looking only for channels with an empty `teamId` (aka DMs and GMs) instead of finding all channels and effectively ignoring the team property.
Fixes: https://mattermost.atlassian.net/browse/MM-42282
* break up getThreadsForUser, leverage errgroup
This change breaks up `GetThreadsForUser` in the `ThreadStore` into its constituent `GetTotalUnreadThreads`, `GetTotalThreads`, `GetTotalUnreadMentions`, and the original `GetThreadsForUser` but now solely returning the thread structures. Instead of a monolithic method at the store level, the application layer now handles calling bulk requests, leveraging `errgroup` for simpler parallelization.
This change brings with it a few benefits:
* Simpler code, including more idiomatic usage of squirrel
* Simpler SQL, joining tables only when configured conditions require same. (No performance benefit here, since an unused LEFT JOIN generally has no overhead.)
* Discrete Grafana metrics for each store method, giving us better insight into the performance characteristics in play.
* **Performance boost**: reduced overhead when clearing push notifications.
This last point is what prompted the re-re-reactoring in this PR. As I broke things up, I realized that `clearPushNotificationSync` only used the `TotalUnreadMentions`, but asked for the count of total threads and total unread threads. By exposing the discrete methods, this code path avoids two aggregate queries. We clear notifications when marking a thread as read, and when marking a channel with unread mentions as viewed, so I expect we'll see at least a modest boost to performance from simply not wasting these cycles anymore.
No performance improvements are expected from this PR for the general case of using `GetThreadsForUser` to populate the threads view.
* never discard errors from building queries
* no MustSql
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
* about to merge with master.
* merge from latest master.
* refactor squirrel function names to match original. clean up extra debugging.
* fix lint.
* reverted websocket_norace_test
* Fix issue of incorrect error being returned.
* made changes from annotated code.
* fix small lint issue.
* remove comment.
* cleaned up code some more.
* fix error with archived tests.
* Cleanup
```release-note
NONE
```
* more cleanup
```release-note
NONE
```
* address review comments
```release-note
NONE
```
* sq.Eq optimization
```release-note
NONE
```
Co-authored-by: Agniva De Sarker <agnivade@yahoo.co.in>
* Ported GetMembersByIds and GetMembersByChannelIds to Squirrel
* Added checks for empty ID lists
* Updated GetAllChannelMembersById to use Squirrel
* Added a method to get the query placeholder directly
* Migrated UpdateMultipleMembers to use a Squirrel query
* Migrated UpdateMultipleMembers to Squirrel
* Initialize a prepared query builder for channelMembersForTeamWithSchemeSelectQuery
* Migrated GetMembersForUser to Squirrel
* Slight improvement for constructMySQLJSONArgs
* Migrated UpdateMemberNotifyProps to Squirrel
* Migrated GetMembers to Squirrel
* Migrated GetMember to Squirrel
* Avoid shadowing err
* Don't set query builder on copy of SqlChannelStore
* Fixed typo in error message
* Fixed missing elipsis
* Shorter SQL generation for GetAllChannelMembersById
* Don't unnecessarily copy the reference
* Use a function to generate the ChannelMember map
* Avoid shadowing err
* Don't use IN for matching multiple possible values
* Initialize the members lists
* Remove check for empty channelIDs list
* Fixed test and removed check for empty list
* Use err2 rather than eerr
Co-authored-by: Tim Scheuermann <tim@plusmid.dev>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
* Revert "[MM-41576] Revamp database schema version (#19586)"
This reverts commit 645fee3fe3.
* Revert "MM-42049 - license endpoint not working (#19686)"
This reverts commit 4fe89e5847.
* revamp db version and add applied migrations endpoint
* replace old schema version with new
* add db version subcommand
* add to local api
* reflect review comments
* log errors
* remove setting the version from model.CurrentVersion
* fix a test
* deadcode: remove UpdateChannelLastViewedAt
* deadcode: remove ThreadStore.(Save(Multiple)|Update|Delete)
* deadcode: followThead in App.MarkChannelAsUnreadFromPost
* document ThreadMembership, Thread structs
* maintain LastUpdated consistently
Whenever we touch a `ThreadMembership` record, we should be setting `LastUpdated` to the current timestamp. The mobile client relies on this to detect changes to these records.
* simplify: never updateThreads from `App.MarkChannelAsUnreadFromPost`
Change all invocations of `ChannelStore.UpdateLastViewedAtPost` from `App.MarkChannelAsUnreadFromPost` to pass `updateThreads` as `false`. When `ChannelStore.UpdateLastViewedAtPost` was invoked with `updateThreads` as `true`, it would in turn call `ThreadStore.UpdateUnreadsByChannel` but pass `updateViewedTimestamp` as `false`. This effectively updated the `LastUpdated` field of the corresponding thread memberships but never touched any of the actual data (such as `LastViewed`).
The overall CRT feature continued to work, because `App.MarkChannelAsUnreadFromPost` directly updates the relevant thread memberships via `ThreadStore.MaintainMembership`.
* deadcode: updateThreads in ChannelStore.UpdateLastViewedAtPost
* simplify: never updateThreads from App.SendNotifications
Change all invocations of `ChannelStore.IncrementMentionCount` from
`App.SendNotifications` to pass `updateThreads` as `false`. When `ChannelStore.IncrementMentionCount` was invoked with `updateThreads` as `true`, it would in turn call `ThreadStore.UpdateUnreadsByChannel` but pass `updateViewedTimestamp` as `false`. This effectively updated the `LastUpdated` field of the corresponding thread memberships but never touched any of the actual data (such as `UnreadMentions`).
The overall CRT feature continued to work, because `App.SendNotifications` directly updates the relevant thread memberships mention counts via `ThreadStore.MaintainMembership`.
* deadcode: updateThreads in ChannelStore.IncrementMentionCount
* fix & rename ThreadStore.UpdateUnreadsByChannel
Rename `ThreadStore.UpdateUnreadsByChannel` to `ThreadStore.UpdateLastViewedByThreadIds`, making it unconditionally set the `LastViewed` for the given threads (as well as `LastUpdated`).
All previous invocations of this method that passed `updateViewedTimestamp` have been previously removed.
* unrelated gofmt -w -s changes to satisfy linter
* always set LastUpdated to model.GetMillis()
* deadcode: ThreadStore.SaveMembership
* fix TestMarkUnreadWithThreads
* MM-40302: CRT, use updateThreads param vs. MarkAllAsReadInChannels
`MarkAllAsReadInChannels` was the subject of a significant performance regression in v5.37 and is known to be very inefficient, by virtue of always writing to an ever increasing number of rows, and doing so on common events like simply viewing a channel.
Fortunately, `ChannelStore.UpdateLastViewedAt` already supported an `updateThreads` parameter that implemented the start of an improved algorithm: query the set of threads with newer posts, and then update only /those/. Missing was the need to reset the `UnreadMentions`, but thanks to the previous simplifications in #19523, we can make this change largely without impacting other semantics.
Fixes: https://mattermost.atlassian.net/browse/MM-40302
* fix MySQL
* remove another JOIN
* remove outdated comment
* unit tests
Previously, we were incrementing mentions one-by-one
all concurrently in an unbounded fashion.
This would cause a big spike in memory usage if there
were an `@all` mention in a large channel.
We fix this by changing the SQL query to take all userIDs
at once.
https://mattermost.atlassian.net/browse/MM-41752
```release-note
NONE
```
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
* deadcode: remove UpdateChannelLastViewedAt
* deadcode: remove ThreadStore.(Save(Multiple)|Update|Delete)
* deadcode: followThead in App.MarkChannelAsUnreadFromPost
* document ThreadMembership, Thread structs
* maintain LastUpdated consistently
Whenever we touch a `ThreadMembership` record, we should be setting `LastUpdated` to the current timestamp. The mobile client relies on this to detect changes to these records.
* simplify: never updateThreads from `App.MarkChannelAsUnreadFromPost`
Change all invocations of `ChannelStore.UpdateLastViewedAtPost` from `App.MarkChannelAsUnreadFromPost` to pass `updateThreads` as `false`. When `ChannelStore.UpdateLastViewedAtPost` was invoked with `updateThreads` as `true`, it would in turn call `ThreadStore.UpdateUnreadsByChannel` but pass `updateViewedTimestamp` as `false`. This effectively updated the `LastUpdated` field of the corresponding thread memberships but never touched any of the actual data (such as `LastViewed`).
The overall CRT feature continued to work, because `App.MarkChannelAsUnreadFromPost` directly updates the relevant thread memberships via `ThreadStore.MaintainMembership`.
* deadcode: updateThreads in ChannelStore.UpdateLastViewedAtPost
* simplify: never updateThreads from App.SendNotifications
Change all invocations of `ChannelStore.IncrementMentionCount` from
`App.SendNotifications` to pass `updateThreads` as `false`. When `ChannelStore.IncrementMentionCount` was invoked with `updateThreads` as `true`, it would in turn call `ThreadStore.UpdateUnreadsByChannel` but pass `updateViewedTimestamp` as `false`. This effectively updated the `LastUpdated` field of the corresponding thread memberships but never touched any of the actual data (such as `UnreadMentions`).
The overall CRT feature continued to work, because `App.SendNotifications` directly updates the relevant thread memberships mention counts via `ThreadStore.MaintainMembership`.
* deadcode: updateThreads in ChannelStore.IncrementMentionCount
* fix & rename ThreadStore.UpdateUnreadsByChannel
Rename `ThreadStore.UpdateUnreadsByChannel` to `ThreadStore.UpdateLastViewedByThreadIds`, making it unconditionally set the `LastViewed` for the given threads (as well as `LastUpdated`).
All previous invocations of this method that passed `updateViewedTimestamp` have been previously removed.
* unrelated gofmt -w -s changes to satisfy linter
* always set LastUpdated to model.GetMillis()
* deadcode: ThreadStore.SaveMembership
* fix TestMarkUnreadWithThreads
* GetMasterX
* WIP
* adding initial creategroup endpoint
* fetching by group source
* fixing startup error
* updating create endpoint to take an array of user_ids, this will allow us to create the group with one request
* adding delete group endpoint and appropriate test
* adding source param for getGroups
* adding add members and delete members endpoints
* locking down crud endpoints to only be allowed for custom groups
* user search stuff
* allowing remoteid be null by changing field to pointer
* code cleanup and store level tests
* adding new tests and removing unused endpoint
* resolving conflicts
* Adds authz check for group.
* Adds authz checks to groups APIs.
* Updated create group authz tests.
* Updates delete group tests.
* Tests create group.
* Adds some tests and validations.
* adding new parameter so I can get users not in a group
* Fixed all lint warnings.
* Fix type.
* fixing search users not in group
* Fixes some lint errors.
* Moves entry in JSON array.
* Fixed SQL query.
* Fixes permission migration test.
* Fixes migration test.
* Fixes some group store tests.
* Fix test.
* Fix test.
* Revert lint change.
* Migrated CreateWithUserIds to sqlx.
* Adds tests for GetMember; migrates implementation to sqlx.
* Tests GetNonMemberUsersPage and hanles wrong group id.
* Fixes test.
* Switches GetMaster to GetMasterX.
* Switches GetReplica to GetReplicaX.
* Fixes logic.
* Fixes shadow declaration.
* Adds include_member_count to get group API endpoint.
* Adds filter_has_member param to getGroups.
* Fixes.
* Removes array of group sources.
* fixing error
* Testing reverting CreateWithUserIds back to gorp.
* Added websocket event for CreateGroupWithUserIds.
* Changed a few response status codes. Switched to correct permission.
* Added member count to ws payload for group when updating or creating.
* Adds feature flag checks for custom groups.
* Added middleware function to require license. Added config to disable custom groups.
* Change for function signature change of executePossiblyEmptyQuery.
* Lint fixes.
* Adds telemetry none comment.
* Adds translations.
* Migrated to sqlx.
* Temp. removal of translation.
* Fixed typo.
* Added an intermediary model to query with a field that is now ignored by sqlx on read queries.
* Re-used existing store struct.
* Inludes member count.
* Fix for merge error.'
* Require license for group endpoints.
* Updates translations.
* Fix shadow declaration.
* Renames permissions. Switches to new method to retrieve remoteid.
* Added WS events for upsert and delete member(s).
* Added new store error type ErrUniqueConstraint.
* Added EnableCustonGroups to the client config.
* Sanitized some user records.
* Added parameter to include_total_count for listing groups.
* Added translations.
* adding deleteAt field to getByUsers query
* Revert sanitize.
* Added uniqueness constraint error to UpdateGroup.
* Removed the FutureFeatures flag so that the feature is not enabled on old Enterprise licenses.
* Renamed function.
* Updates authz check for user search related to groups.
* Removed debug statement.
* Removed unused app method.
* Added telemetry for enable_custom_groups.
* Returns early from nil license.
* Updates test.
* Returned early to avoid nesting in (*SqlGroupStore).checkUserExist. Switched to reading from replica in (*SqlGroupStore).GetMember. Handled JSON marshal error in (*Client4).UpsertGroupMembers
* Switched to SanitizeProfile.
* Switched to model.NewInt.
* Switched from status NotImplemented to Forbidden for missing license.
* Removed deactivated users from 'exists' set.
* Revert gotool update.
* Ignored lint error that I think is invalid.
* Added the approprate access tag for disabling custom groups.
* Revert change to response status.
* Fixed refactor mistake.
* Limited the group member WS events to individual users.
* Removed WS event of deleted groups.
* Updated license check for searchUsers endpoint.
* Switched from license feature to license sku.
* Update app/group.go
Co-authored-by: Claudio Costa <cstcld91@gmail.com>
* Update app/group.go
Co-authored-by: Claudio Costa <cstcld91@gmail.com>
* Remove linter ignore comment.
* Added function to create sku-specific license.
* Fixed typo. Removed comment.
* Fixed for wrong type.
* Added missing param to client. Removed unnecessary props setting. Added test for retrieving groups by source.
* Updated some tests now that we're validating group membership not created for deactivated user.
* Fix for groups endpoint returning all group types by default.
* Changes constant names. Adds migration for all users to manage custom group members.
* Removes requirement for manage_system permission to filter user search by group.
* Added migration mock.
* Removes default permissions from custom_group_user role.
* Fixes migration.
* Fixes emoji migration test.
* fixing issue with member counts
* fixing search issue for deleted members
Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MacBook-Pro.local>
Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MBP.ht.home>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MacBook-Pro.fritz.box>
Co-authored-by: Claudio Costa <cstcld91@gmail.com>
The GetTeamsUnreadForUser call would be called for every team switch.
In CRT mode, it would make a separate store call for every team, which
would run the 3 aggregate SQL queries in GetThreadsForUser.
This is suboptimal because the complexity is linearly proportional
to the number of teams.
We make the following optimizations:
1. Change the query to a single one which aggregates all teams.
2. The query originally used just 2 out of the 3 queries, so one
query was fully redundant. We remove that query in the new one.
3. Further analysis was done whether it makes sense to run the 2
queries synchronously or not. The load-tests didn't show any degradation
in running them concurrently, so we keep the same behavior.
```release-note
NONE
```
The UPSERT statement was taking unexplained gap
locks, due to which the import was somehow failing.
I still don't know exactly how this is happening.
But splitting the UPSERT into 2 different statements
in the same transaction changes the locking semantics,
and avoids the deadlock.
Naturally, this proves that even our retrylayer
is sometimes ineffective against some problems.
```release-note
NONE
```
We create a custom io.Writer to pass to the logger
instance. For now, we keep everything to debug
as all errors are surfaced back to the server via
the API.
```release-note
NONE
```
* tools updates
* Revert "tools updates"
This reverts commit 6293297b55803c5a263e200ebd80192899666ae9.
* new endpoint to get users that should potentially be guests
* checking authservice to ensure they were an email signup
* adding tests for new endpoint
* fixing translation issue
* permissions for new endpoint
* fixing tests
* fixing when domain array is empty
* fixing when domain array is empty
* removing bots from request
Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MacBook-Pro.local>
Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MBP.ht.home>
Co-authored-by: mkraft <martinkraft@gmail.com>
* MM-36589: provide previous values for unreads
To successfully figure out the new counts of mentions or unread replies
for CRT we need to provide previous values alongside with the new.
This is needed so we'll know how many to subtract from the total.
This commit provides those numbers upon publishing websocket ThreadUpdated
and ThreadReadChanged events.
* Fixes errors
* Removes unneeded lines
* Adds GetThreadUnreadReplyCount store method
Uses the new store method to get unread replies instead of
GetThreadForUser.
* Tests, and some changes
- Adds api4 tests to test ws events
- Uses sqlx instead of gorp for new store method
- Fixes case where previous_unread_replies could be a negative value
* Refactors tests and adds more cases
* Fixes previous and current unread counts for commenter
When a user posts a reply to a thread the unread counts had a couple of
issues.
UnreadMentions where not zeroed out, and previous unread counts where
not set correctly.
This commit tries to fix that by marking the thread as read for the
current poster after we set previous unread counts to the websocket
event data.
Also MaintainMembership should zero out UnreadMentions when we are
setting the thread as read.
* Oops
* Fixes tests by updating when maintaining membership
OK, so some tests broke because we zero UnreadMentions in the membership
when we UpdateViewedTimestamp, since the new timestamp is always now.
Some tests broke because MaintainMembership for the commenter so that
the thread is read each time commenter posts moved further down in the
SendNotification method.
BOTH those test cases are fixed with this commit. To be sincere though I
don't understand why the second one is fixed by this.
* SystemAdminUser was not part of the channel
Some tests are failing because SystemAdminUser is not part of the
team and channels.
This commit adds user to team and channels, in an effort to fix
api4/user_tests
* Fixes tests
* Fixes tests
* Addresses review comments
* Fix if clause
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Before gorp, to use sqlx we had to resort to using
internal structs without the `db:"-"` tag so that
it doesn't interfere with the gorp table generation.
Now that it's gone, we can use the original model structs.
```release-note
NONE
```
* MM-35298: Follow thread when added to channel
* return better error if thread doesn't exist
* update test for possible race
* use correct comparision operator
* Update morph dependency to use a newer version
* remove timeout check for migrations statements
* store/sqlstore: reset timeout for mysql while creating db for migrations
* update morph to v0.2.1