Files
baddf24ba4 [MM-69403] Push WebSocket events on job status changes (#37130)
* Add WebSocket push for job status changes, remove System Console polling

Server now broadcasts a job_updated WebSocket event whenever a job
transitions state (pending, in_progress, success, error, warning,
canceled). The webapp handles this event by updating the Redux store
immediately, so the LDAP (and any other) job table in the System Console
reflects changes in real time without a polling interval.

* Address security review: strip job Data from WS event, guard JSON.parse

- publishJobStatus now strips job.Data before broadcasting so sensitive
  job-type-specific fields (requesting_user_id, team_id, policy_id, role)
  are not exposed to WebSocket clients without permission checks; status,
  progress, and timestamps are sufficient for real-time UI updates
- handleJobUpdated wraps JSON.parse in try/catch to prevent a malformed
  payload from breaking WebSocket event handling

* Fix import/order ESLint errors for @mattermost/types/jobs

The Job type import must appear after @mattermost/types/integrations
alphabetically in both websocket_actions.ts and websocket_messages.ts.

* Add unit tests for job status WebSocket broadcasting

- Server: TestPublishJobStatus covers nil callback safety, Data stripping,
  and per-method status verification (ClaimJob→in_progress, SetJobWarning→
  warning, SetJobSuccess→success, SetJobError nil/non-nil→error,
  SetJobCanceled→canceled, SetJobPending→pending)
- Reducer: jobs.test.ts covers RECEIVED_JOB on jobsByTypeList (type absent,
  id absent, id found/updated, multi-entry list preserves other entries)
- Webapp: handleJobUpdated tests cover valid JSON dispatch and malformed
  JSON no-op

* Fix run time display by using DB-returned job for WebSocket publish

UpdateStatus now returns the full job via RETURNING (same pattern as
UpdateStatusOptimistically), so SetJob* methods can pass the DB result
to publishJobStatus. This ensures last_activity_at and start_at are
populated from the DB in the broadcasted event rather than from the
potentially-stale in-memory worker struct.

Before this change, polling masked the issue by re-fetching jobs via
REST API after completion. Without polling, the WebSocket event was
the only update and could carry zero timestamps → "--" run time.

* Return ErrNotFound from UpdateStatus when no rows matched and remove nil guards

UpdateStatus targets a specific job by ID unconditionally, so zero rows
updated means the job doesn't exist — an error, not a silent no-op.
Returning store.ErrNotFound makes callers fail loudly (rather than
silently falling back to stale in-memory data) and removes the need for
nil-guard boilerplate in every SetJob* caller.

* Re-fetch job list on terminal status to populate run time and error details

The WebSocket payload intentionally omits job Data for security, so fields
like the error message and accurate last_activity_at are only available via
the REST API. On receiving a terminal status (success/error/warning/canceled),
dispatch getJobsByType to fill in those details immediately after the status
update lands in the store.

Also set job.LastActivityAt before publishing in SetJobError's non-nil branch
so the WebSocket event carries a reasonable run time approximation even before
the re-fetch completes (UpdateOptimistically updates last_activity_at in the DB
but not the in-memory struct).

* Change UpdateOptimistically to return (*model.Job, error) via SQL RETURNING

Returns the full updated row on success; returns nil, nil when the
precondition status doesn't match (expected outcome, not an error).
Drops the manual LastActivityAt assignment in SetJobError — the DB
timestamp is now authoritative via the returned job.

* Tighten UpdateOptimistically precondition-fail assertion in storetest

The previous require.False(t, err != nil && ret != nil) would incorrectly
pass if the function returned (job, nil) instead of the expected (nil, nil).
Use explicit require.NoError + require.Nil to pin both return values.

* Scope job_updated WebSocket events to system admins only

Set ContainsSensitiveData=true so the hub only delivers the event to
connections where the user holds manage_system permission. The job
system is admin-only; regular users have no UI that consumes this event.

* Pass publish func through NewJobServer, remove SetPublish

SetPublish was called immediately after NewJobServer in its only
production call site with no initialization ordering constraint.
Passing it as a constructor parameter removes the unnecessary setter.

* Fix four gaps in job status WebSocket push coverage

- Remove ContainsSensitiveData=true from publishJobStatus: the payload
  carries no sensitive fields (Data is stripped), so sysadmins with
  delegated roles (e.g. sysconsole_read_authentication_ldap) receive
  events instead of seeing a frozen table.

- SetJobProgress now publishes in_progress events so the progress bar
  advances via WebSocket rather than staying frozen at 0%.

- RequestCancellation pending→canceled path now publishes a canceled
  event, matching the behavior of all other terminal-state transitions.

- jobsByTypeList RECEIVED_JOB reducer now prepends a newly-seen job
  when the type list is already loaded, so brand-new jobs appear
  immediately via WebSocket push without waiting for a page reload.

* Revert finding 1: restore ContainsSensitiveData=true on job WebSocket events

* Add non-admin polling fallback and fix missing WS publish in RequestCancellation

- JobTable now polls every 15s as a fallback for non-system-admin
  viewers, since job_updated WebSocket events are scoped to system
  admins only (addresses PR #37130 review comment r3462905643).
- RequestCancellation now publishes a job_updated event when a job
  transitions from in_progress to cancel_requested, matching the
  existing publish on the pending->canceled branch (addresses
  r3462940359).
- Add test coverage for both.

* Stop stripping Data from job_updated WebSocket event

publishJobStatus broadcasts are already restricted to system admins
via ContainsSensitiveData, and system admins can already read job
Data through the permissioned REST API. Stripping it here provided
no additional protection.

MM-69695 tracks scoping the broadcast to per-job-type permissions
instead of system-admin-only; that follow-up needs to reintroduce
appropriate Data filtering once the audience widens.

---------

Co-authored-by: Hanzo Dev <[email protected]>
2026-07-10 22:17:29 +02:00

473 lines
13 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package sqlstore
import (
"database/sql"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/lib/pq"
sq "github.com/mattermost/squirrel"
"github.com/pkg/errors"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/store"
)
const (
jobsCleanupDelay = 100 * time.Millisecond
)
type SqlJobStore struct {
*SqlStore
jobColumns []string
jobQuery sq.SelectBuilder
}
func newSqlJobStore(sqlStore *SqlStore) store.JobStore {
s := &SqlJobStore{
SqlStore: sqlStore,
jobColumns: []string{
"Id",
"Type",
"Priority",
"CreateAt",
"StartAt",
"LastActivityAt",
"Status",
"Progress",
"Data",
},
}
s.jobQuery = s.getQueryBuilder().
Select(s.jobColumns...).
From("Jobs")
return s
}
func (jss SqlJobStore) Save(job *model.Job) (*model.Job, error) {
jsonData, err := json.Marshal(job.Data)
if err != nil {
return nil, errors.Wrap(err, "failed marshalling job data")
}
if jss.IsBinaryParamEnabled() {
jsonData = AppendBinaryFlag(jsonData)
}
query := jss.getQueryBuilder().
Insert("Jobs").
Columns("Id", "Type", "Priority", "CreateAt", "StartAt", "LastActivityAt", "Status", "Progress", "Data").
Values(job.Id, job.Type, job.Priority, job.CreateAt, job.StartAt, job.LastActivityAt, job.Status, job.Progress, jsonData)
queryString, args, err := query.ToSql()
if err != nil {
return nil, errors.Wrap(err, "failed to generate sqlquery")
}
if _, err = jss.GetMaster().Exec(queryString, args...); err != nil {
return nil, errors.Wrap(err, "failed to save Job")
}
return job, nil
}
func (jss SqlJobStore) SaveOnce(job *model.Job) (*model.Job, error) {
jsonData, err := json.Marshal(job.Data)
if err != nil {
return nil, errors.Wrap(err, "failed marshalling job data")
}
if jss.IsBinaryParamEnabled() {
jsonData = AppendBinaryFlag(jsonData)
}
tx, err := jss.GetMaster().BeginWithIsolation(&sql.TxOptions{
Isolation: sql.LevelSerializable,
})
if err != nil {
return nil, errors.Wrap(err, "begin_transaction")
}
defer finalizeTransactionX(tx, &err)
query, args, err := jss.getQueryBuilder().
Select("COUNT(*)").
From("Jobs").
Where(sq.Eq{
"Status": []string{model.JobStatusPending, model.JobStatusInProgress},
"Type": job.Type,
}).ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
var count int64
err = tx.Get(&count, query, args...)
if err != nil {
return nil, errors.Wrapf(err, "failed to count pending and in-progress jobs with type=%s", job.Type)
}
if count > 0 {
return nil, nil
}
query, args, err = jss.getQueryBuilder().
Insert("Jobs").
Columns("Id", "Type", "Priority", "CreateAt", "StartAt", "LastActivityAt", "Status", "Progress", "Data").
Values(job.Id, job.Type, job.Priority, job.CreateAt, job.StartAt, job.LastActivityAt, job.Status, job.Progress, jsonData).ToSql()
if err != nil {
return nil, errors.Wrap(err, "failed to generate sqlquery")
}
if _, err = tx.Exec(query, args...); err != nil {
if isRepeatableError(err) {
return nil, nil
}
return nil, errors.Wrap(err, "failed to save Job")
}
if err = tx.Commit(); err != nil {
if isRepeatableError(err) {
return nil, nil
}
return nil, errors.Wrap(err, "commit_transaction")
}
return job, nil
}
// UpdateOptimistically updates the job only if its current status matches currentStatus.
// Returns the updated job on success, or nil if no row was matched (status mismatch or job not
// found). A nil return with a nil error is not an error — it means the precondition was not met.
func (jss SqlJobStore) UpdateOptimistically(job *model.Job, currentStatus string) (*model.Job, error) {
dataJSON, jsonErr := json.Marshal(job.Data)
if jsonErr != nil {
return nil, errors.Wrap(jsonErr, "failed to encode job's data to JSON")
}
if jss.IsBinaryParamEnabled() {
dataJSON = AppendBinaryFlag(dataJSON)
}
builder := jss.getQueryBuilder().
Update("Jobs").
Set("LastActivityAt", model.GetMillis()).
Set("Status", job.Status).
Set("Data", dataJSON).
Set("Progress", job.Progress).
Where(sq.Eq{"Id": job.Id, "Status": currentStatus}).
Suffix("RETURNING " + strings.Join(jss.jobColumns, ", "))
var jobs []*model.Job
if err := jss.GetMaster().SelectBuilder(&jobs, builder); err != nil {
return nil, errors.Wrapf(err, "failed to update Job with id=%s", job.Id)
}
if len(jobs) != 1 {
return nil, nil
}
return jobs[0], nil
}
func (jss SqlJobStore) UpdateStatus(id string, status string) (*model.Job, error) {
builder := jss.getQueryBuilder().
Update("Jobs").
Set("Status", status).
Set("LastActivityAt", model.GetMillis()).
Where(sq.Eq{"Id": id}).
Suffix("RETURNING " + strings.Join(jss.jobColumns, ", "))
var jobs []*model.Job
if err := jss.GetMaster().SelectBuilder(&jobs, builder); err != nil {
return nil, errors.Wrapf(err, "failed to update Job with id=%s", id)
}
if len(jobs) != 1 {
return nil, store.NewErrNotFound("Job", id)
}
return jobs[0], nil
}
func (jss SqlJobStore) UpdateStatusOptimistically(id string, currentStatus string, newStatus string) (*model.Job, error) {
lastActivityAndStartTime := model.GetMillis()
// Use RETURNING to get the updated job in a single query
builder := jss.getQueryBuilder().
Update("Jobs").
Set("LastActivityAt", lastActivityAndStartTime).
Set("Status", newStatus).
Where(sq.Eq{"Id": id, "Status": currentStatus}).
Suffix("RETURNING " + strings.Join(jss.jobColumns, ", "))
if newStatus == model.JobStatusInProgress {
builder = builder.Set("StartAt", lastActivityAndStartTime)
}
var job []*model.Job
if err := jss.GetMaster().SelectBuilder(&job, builder); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, store.NewErrNotFound("Job", id)
}
return nil, errors.Wrapf(err, "failed to update Job with id=%s", id)
}
// we are updating by id, so we should only ever update 1 job
if len(job) != 1 {
// no row was updated, but no error above, so to remain consistent we return nil, nil
return nil, nil
}
return job[0], nil
}
func (jss SqlJobStore) Get(rctx request.CTX, id string) (*model.Job, error) {
query, args, err := jss.jobQuery.
Where(sq.Eq{"Id": id}).ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
var status model.Job
if err = jss.GetReplica().Get(&status, query, args...); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, store.NewErrNotFound("Job", id)
}
return nil, errors.Wrapf(err, "failed to get Job with id=%s", id)
}
return &status, nil
}
func (jss SqlJobStore) GetAllByTypesPage(rctx request.CTX, jobTypes []string, page int, perPage int) ([]*model.Job, error) {
offset := page * perPage
query, args, err := jss.jobQuery.
Where(sq.Eq{"Type": jobTypes}).
OrderBy("CreateAt DESC").
Limit(uint64(perPage)).
Offset(uint64(offset)).ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
var jobs []*model.Job
if err = jss.GetReplica().Select(&jobs, query, args...); err != nil {
return nil, errors.Wrapf(err, "failed to find Jobs with types")
}
return jobs, nil
}
func (jss SqlJobStore) GetAllByType(rctx request.CTX, jobType string) ([]*model.Job, error) {
query, args, err := jss.jobQuery.
Where(sq.Eq{"Type": jobType}).
OrderBy("CreateAt DESC").ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
statuses := []*model.Job{}
if err = jss.GetReplica().Select(&statuses, query, args...); err != nil {
return nil, errors.Wrapf(err, "failed to find Jobs with type=%s", jobType)
}
return statuses, nil
}
func (jss SqlJobStore) GetAllByTypeAndStatus(rctx request.CTX, jobType string, status string) ([]*model.Job, error) {
query, args, err := jss.jobQuery.
Where(sq.Eq{"Type": jobType, "Status": status}).
OrderBy("CreateAt DESC").ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
jobs := []*model.Job{}
if err = jss.GetReplica().Select(&jobs, query, args...); err != nil {
return nil, errors.Wrapf(err, "failed to find Jobs with type=%s", jobType)
}
return jobs, nil
}
func (jss SqlJobStore) GetAllByTypePage(rctx request.CTX, jobType string, page int, perPage int) ([]*model.Job, error) {
offset := page * perPage
query, args, err := jss.jobQuery.
Where(sq.Eq{"Type": jobType}).
OrderBy("CreateAt DESC").
Limit(uint64(perPage)).
Offset(uint64(offset)).ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
statuses := []*model.Job{}
if err = jss.GetReplica().Select(&statuses, query, args...); err != nil {
return nil, errors.Wrapf(err, "failed to find Jobs with type=%s", jobType)
}
return statuses, nil
}
func (jss SqlJobStore) GetAllByStatus(rctx request.CTX, status string) ([]*model.Job, error) {
statuses := []*model.Job{}
query, args, err := jss.jobQuery.
Where(sq.Eq{"Status": status}).
OrderBy("CreateAt ASC").ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
if err = jss.GetReplica().Select(&statuses, query, args...); err != nil {
return nil, errors.Wrapf(err, "failed to find Jobs with status=%s", status)
}
return statuses, nil
}
func (jss SqlJobStore) GetAllByTypesAndStatusesPage(rctx request.CTX, jobType []string, status []string, offset int, limit int) ([]*model.Job, error) {
query, args, err := jss.jobQuery.
Where(sq.Eq{"Type": jobType, "Status": status}).
OrderBy("CreateAt DESC").
Limit(uint64(limit)).
Offset(uint64(offset)).ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
jobs := []*model.Job{}
if err = jss.GetReplica().Select(&jobs, query, args...); err != nil {
return nil, errors.Wrapf(err, "failed to find Jobs with types=%s and statuses=%s", strings.Join(jobType, ","), strings.Join(status, ","))
}
return jobs, nil
}
func (jss SqlJobStore) GetNewestJobByStatusAndType(status string, jobType string) (*model.Job, error) {
return jss.GetNewestJobByStatusesAndType([]string{status}, jobType)
}
func (jss SqlJobStore) GetNewestJobByStatusesAndType(status []string, jobType string) (*model.Job, error) {
query, args, err := jss.jobQuery.
Where(sq.Eq{"Status": status, "Type": jobType}).
OrderBy("CreateAt DESC").
Limit(1).ToSql()
if err != nil {
return nil, errors.Wrap(err, "job_tosql")
}
var job model.Job
if err = jss.GetReplica().Get(&job, query, args...); err != nil {
if err == sql.ErrNoRows {
return nil, store.NewErrNotFound("Job", fmt.Sprintf("<status, type>=<%s, %s>", strings.Join(status, ","), jobType))
}
return nil, errors.Wrapf(err, "failed to find Job with statuses=%s and type=%s", strings.Join(status, ","), jobType)
}
return &job, nil
}
func (jss SqlJobStore) GetCountByStatusAndType(status string, jobType string) (int64, error) {
query, args, err := jss.getQueryBuilder().
Select("COUNT(*)").
From("Jobs").
Where(sq.Eq{"Status": status, "Type": jobType}).ToSql()
if err != nil {
return 0, errors.Wrap(err, "job_tosql")
}
var count int64
err = jss.GetReplica().Get(&count, query, args...)
if err != nil {
return int64(0), errors.Wrapf(err, "failed to count Jobs with status=%s and type=%s", status, jobType)
}
return count, nil
}
func (jss SqlJobStore) GetByTypeAndData(rctx request.CTX, jobType string, data map[string]string, useMaster bool, statuses ...string) ([]*model.Job, error) {
query := jss.jobQuery.Where(sq.Eq{"Type": jobType})
// Add status filtering if provided - enables full usage of idx_jobs_status_type index
if len(statuses) > 0 {
query = query.Where(sq.Eq{"Status": statuses})
}
// Add JSON data filtering for each key-value pair
for key, value := range data {
query = query.Where(sq.Expr("Data->? = ?", key, fmt.Sprintf(`"%s"`, value)))
}
queryString, args, err := query.ToSql()
if err != nil {
return nil, errors.Wrap(err, "get_by_type_and_data_tosql")
}
var jobs []*model.Job
// For consistency-critical operations (like job deduplication), use master
db := jss.GetReplica()
if useMaster {
db = jss.GetMaster()
}
if err := db.Select(&jobs, queryString, args...); err != nil {
return nil, errors.Wrap(err, "failed to get Jobs by type and data")
}
return jobs, nil
}
func (jss SqlJobStore) Delete(id string) (string, error) {
query, args, err := jss.getQueryBuilder().
Delete("Jobs").
Where(sq.Eq{"Id": id}).ToSql()
if err != nil {
return "", errors.Wrap(err, "job_tosql")
}
if _, err = jss.GetMaster().Exec(query, args...); err != nil {
return "", errors.Wrapf(err, "failed to delete Job with id=%s", id)
}
return id, nil
}
func (jss SqlJobStore) Cleanup(expiryTime int64, batchSize int) error {
query := "DELETE FROM Jobs WHERE Id IN (SELECT Id FROM Jobs WHERE CreateAt < ? AND (Status != ? AND Status != ?) ORDER BY CreateAt ASC LIMIT ?)"
var rowsAffected int64 = 1
for rowsAffected > 0 {
sqlResult, err := jss.GetMaster().Exec(query,
expiryTime, model.JobStatusInProgress, model.JobStatusPending, batchSize)
if err != nil {
return errors.Wrap(err, "unable to delete jobs")
}
var rowErr error
rowsAffected, rowErr = sqlResult.RowsAffected()
if rowErr != nil {
return errors.Wrap(rowErr, "unable to delete jobs")
}
time.Sleep(jobsCleanupDelay)
}
return nil
}
// isRepeatableError is a bit of copied code from retrylayer.go.
// A little copying is fine because we don't want to import another package
// in the store layer
func isRepeatableError(err error) bool {
var pqErr *pq.Error
switch {
case errors.As(err, &pqErr):
if pqErr.Code == "40001" || pqErr.Code == "40P01" {
return true
}
}
return false
}