diff --git a/internal/api/v2/v2.go b/internal/api/v2/v2.go index 9c50b8f..874d86c 100644 --- a/internal/api/v2/v2.go +++ b/internal/api/v2/v2.go @@ -400,6 +400,11 @@ func PostIncidentHandler(dbInst *db.DB, logger *zap.Logger, pub ...*notification apiErrors.RaiseBadRequestErr(c, err) return } + if errors.Is(err, db.ErrVersionConflict) { + logger.Warn("incident creation failed: version conflict", zap.Error(err)) + apiErrors.RaiseConflictErr(c, apiErrors.ErrVersionConflict) + return + } logger.Error("incident creation failed: internal error", zap.Error(err)) apiErrors.RaiseInternalErr(c, err) return diff --git a/internal/db/db.go b/internal/db/db.go index 12d2ceb..ab1ef5b 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -917,18 +917,15 @@ func (db *DB) ExtractComponentsToNewIncident( } func (db *DB) IncreaseIncidentImpact(ctx context.Context, inc *Incident, impact int) (*Incident, error) { + if inc.Version == nil { + return nil, errors.New("version is required for incident modification") + } + + expectedVersion := *inc.Version + newVersion := expectedVersion + 1 + timeNow := time.Now().UTC() - text := fmt.Sprintf("impact changed from %d to %d", *inc.Impact, impact) - inc.Statuses = append(inc.Statuses, IncidentStatus{ - IncidentID: inc.ID, - Status: event.OutDatedSystem, - Text: text, - Timestamp: timeNow, - CreatedAt: &timeNow, - ModifiedAt: &timeNow, - }) - inc.Impact = &impact - inc.ModifiedAt = &timeNow + text := recordImpactIncrease(inc, impact, timeNow) // Only non-zero fields are written for the incident row, mirroring the // previous struct-based update. incident_status has no Ent edge, so the @@ -938,7 +935,8 @@ func (db *DB) IncreaseIncidentImpact(ctx context.Context, inc *Incident, impact return nil, err } - update := tx.Incident.UpdateOneID(int(inc.ID)) + update := tx.Incident.Update(). + Where(incident.IDEQ(int(inc.ID)), incident.VersionEQ(expectedVersion)) if inc.Text != nil && *inc.Text != "" { update.SetText(*inc.Text) } @@ -971,14 +969,17 @@ func (db *DB) IncreaseIncidentImpact(ctx context.Context, inc *Incident, impact if inc.ContactEmail != nil { update.SetContactEmail(*inc.ContactEmail) } - if inc.Version != nil { - update.SetVersion(*inc.Version) - } + update.SetVersion(newVersion) - if err = update.Exec(ctx); err != nil { + affected, err := update.Save(ctx) + if err != nil { _ = tx.Rollback() return nil, err } + if affected == 0 { + _ = tx.Rollback() + return nil, ErrVersionConflict + } _, err = tx.IncidentStatus.Create(). SetIncidentID(int(inc.ID)). @@ -997,9 +998,28 @@ func (db *DB) IncreaseIncidentImpact(ctx context.Context, inc *Incident, impact return nil, err } + inc.Version = &newVersion return inc, nil } +// recordImpactIncrease appends the status for the impact change to the +// in-memory incident and returns its text. +func recordImpactIncrease(inc *Incident, impact int, timeNow time.Time) string { + text := fmt.Sprintf("impact changed from %d to %d", *inc.Impact, impact) + inc.Statuses = append(inc.Statuses, IncidentStatus{ + IncidentID: inc.ID, + Status: event.OutDatedSystem, + Text: text, + Timestamp: timeNow, + CreatedAt: &timeNow, + ModifiedAt: &timeNow, + }) + inc.Impact = &impact + inc.ModifiedAt = &timeNow + + return text +} + func (db *DB) GetUniqueAttributeValues(ctx context.Context, attrName string) ([]string, error) { rows, err := db.e.ComponentAttr.Query(). Where(componentattr.NameEQ(attrName)). diff --git a/tests/impact_version_test.go b/tests/impact_version_test.go new file mode 100644 index 0000000..660d250 --- /dev/null +++ b/tests/impact_version_test.go @@ -0,0 +1,65 @@ +package tests + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stackmon/otc-status-dashboard/internal/db" + "github.com/stackmon/otc-status-dashboard/internal/event" +) + +// TestIncreaseIncidentImpactVersionPredicate checks that the impact bump is +// rejected for a stale version and that its status row is written only when the +// update succeeds. +func TestIncreaseIncidentImpactVersionPredicate(t *testing.T) { + ctx := context.Background() + d, g := newNotifDB(t) + + text := "impact probe " + uuid.NewString() + start := time.Now().UTC() + impact := 1 + + id, err := d.SaveIncident(ctx, &db.Incident{ + Text: &text, + StartDate: &start, + Impact: &impact, + Status: event.IncidentDetected, + System: true, + Type: event.TypeIncident, + }) + require.NoError(t, err) + + stale, err := d.GetIncident(ctx, int(id)) + require.NoError(t, err) + version := *stale.Version + stale.Version = intPtr(version - 1) + + _, err = d.IncreaseIncidentImpact(ctx, stale, 3) + require.ErrorIs(t, err, db.ErrVersionConflict) + + unchanged, err := d.GetIncident(ctx, int(id)) + require.NoError(t, err) + assert.Equal(t, impact, *unchanged.Impact) + assert.Equal(t, version, *unchanged.Version) + assert.Equal(t, int64(0), tableCount(t, g, "incident_status", + "incident_id = $1 AND text = $2", id, "impact changed from 1 to 3")) + + fresh, err := d.GetIncident(ctx, int(id)) + require.NoError(t, err) + updated, err := d.IncreaseIncidentImpact(ctx, fresh, 3) + require.NoError(t, err) + assert.Equal(t, 3, *updated.Impact) + assert.Equal(t, version+1, *updated.Version) + + stored, err := d.GetIncident(ctx, int(id)) + require.NoError(t, err) + assert.Equal(t, 3, *stored.Impact) + assert.Equal(t, version+1, *stored.Version) + assert.Equal(t, int64(1), tableCount(t, g, "incident_status", + "incident_id = $1 AND text = $2", id, "impact changed from 1 to 3")) +}