diff --git a/internal/api/v2/v2.go b/internal/api/v2/v2.go index 9c50b8f..c6b1a51 100644 --- a/internal/api/v2/v2.go +++ b/internal/api/v2/v2.go @@ -614,15 +614,23 @@ func addComponentToSystemIncident( IsSystem: &system, IsActive: &active, } - sysIncidents, errEvents := dbInst.GetEventsInternal(ctx, params) - if errEvents != nil { - return nil, errEvents - } - log.Info("found all system incidents", zap.Int("systemIncidentsCount", len(sysIncidents))) - // check if we have any system incident with the target impact - for _, sysInc := range sysIncidents { - if sysInc.Impact != nil && *sysInc.Impact == *incData.Impact { + var result *db.Incident + err := dbInst.WithSystemIncidentLock(ctx, *incData.Impact, func(tx *db.Tx) error { + // Re-query after taking the lock: a competing caller may have created + // the system incident for this impact and committed it already. + sysIncidents, errEvents := dbInst.GetEventsInternalTx(ctx, tx, params) + if errEvents != nil { + return errEvents + } + + log.Info("found all system incidents", zap.Int("systemIncidentsCount", len(sysIncidents))) + // check if we have any system incident with the target impact + for _, sysInc := range sysIncidents { + if sysInc.Impact == nil || *sysInc.Impact != *incData.Impact { + continue + } + log.Info( "found existing system incident with target impact, link component to it", zap.Uint("componentID", comp.ID), zap.Uint("incidentID", sysInc.ID), @@ -634,36 +642,40 @@ func addComponentToSystemIncident( Text: fmt.Sprintf("%s added to the incident by system.", comp.PrintAttrs()), Timestamp: time.Now().UTC(), } - err := dbInst.AddComponentToIncident(ctx, sysInc, comp, status) - if err != nil { - return nil, err + if err := dbInst.AddComponentToIncidentTx(ctx, tx, sysInc, comp, status); err != nil { + return err } - return sysInc, nil + result = sysInc + return nil } - } - log.Info( - "no system incident found with the target impact", - zap.Uint("componentID", comp.ID), zap.Int("impact", *incData.Impact), - ) - log.Info("creating general system incident with target impact", zap.Int("impact", *incData.Impact)) - - incIn := db.Incident{ - Text: &incData.Title, - Description: &incData.Description, - StartDate: &incData.StartDate, - EndDate: incData.EndDate, - Impact: incData.Impact, - System: *incData.System, - Type: incData.Type, - Components: []db.Component{*comp}, - } - - if err := createEvent(ctx, dbInst, log, &incIn, nil, nil); err != nil { + log.Info( + "no system incident found with the target impact", + zap.Uint("componentID", comp.ID), zap.Int("impact", *incData.Impact), + ) + log.Info("creating general system incident with target impact", zap.Int("impact", *incData.Impact)) + + incIn := db.Incident{ + Text: &incData.Title, + Description: &incData.Description, + StartDate: &incData.StartDate, + EndDate: incData.EndDate, + Impact: incData.Impact, + System: *incData.System, + Type: incData.Type, + Components: []db.Component{*comp}, + } + if err := createEventTx(ctx, dbInst, log, tx, &incIn, nil, nil); err != nil { + return err + } + result = &incIn + return nil + }) + if err != nil { return nil, err } - return &incIn, nil + return result, nil } func moveComponentFromToSystemIncidents( @@ -979,59 +991,7 @@ func createEvent( log.Info("start to save an event to the database") err := dbInst.WithTx(ctx, func(tx *db.Tx) error { - id, err := dbInst.SaveIncidentTx(ctx, tx, inc) - if err != nil { - return err - } - - inc.ID = id - - log.Info("add initial status to the event", zap.Uint("eventID", inc.ID)) - var statusText string - var status event.Status - timestamp := time.Now().UTC() - // Sometimes we have a gap between the start date and the current time. - // Example: the incident was created now, but we add an update with a detected status since 1-2 seconds. - // And on the FE it looks like the incident was created in the past. - // it doesn't affect planned events, like maintenance or info, because they have a start date in the future. - // However, if someone creates an incident with a start date in the past, - // we should set up the right timestamp for the status update. - if inc.StartDate.Before(timestamp) { - timestamp = *inc.StartDate - } - - switch inc.Type { - case event.TypeInformation: - statusText = event.InfoPlannedStatusText() - status = event.InfoPlanned - case event.TypeMaintenance: - if inc.Status == event.MaintenancePendingReview { - statusText = event.MaintenancePendingReviewStatusText() - status = event.MaintenancePendingReview - } else { - statusText = event.MaintenancePlannedStatusText() - status = event.MaintenancePlanned - } - case event.TypeIncident: - statusText = event.IncidentDetectedStatusText() - status = event.IncidentDetected - } - - inc.Statuses = append(inc.Statuses, db.IncidentStatus{ - IncidentID: inc.ID, - Status: status, - Text: statusText, - Timestamp: timestamp, - CreatedBy: userID, - }) - inc.Status = status - - if err = dbInst.ModifyIncidentTx(ctx, tx, inc); err != nil { - return err - } - - // A newly created maintenance has no previous status. - return publishMaintenanceChange(ctx, tx, pub, inc, "", userID) + return createEventTx(ctx, dbInst, log, tx, inc, userID, pub) }) if err == nil && inc.Type == event.TypeMaintenance { pub.Notify() // wake the worker after the commit @@ -1039,6 +999,67 @@ func createEvent( return err } +// createEventTx saves an event and its initial status inside tx so callers can +// keep a read-check-write sequence in one transaction. +func createEventTx( + ctx context.Context, dbInst *db.DB, log *zap.Logger, tx *db.Tx, + inc *db.Incident, userID *string, pub *notification.Publisher, +) error { + id, err := dbInst.SaveIncidentTx(ctx, tx, inc) + if err != nil { + return err + } + + inc.ID = id + + log.Info("add initial status to the event", zap.Uint("eventID", inc.ID)) + var statusText string + var status event.Status + timestamp := time.Now().UTC() + // Sometimes we have a gap between the start date and the current time. + // Example: the incident was created now, but we add an update with a detected status since 1-2 seconds. + // And on the FE it looks like the incident was created in the past. + // it doesn't affect planned events, like maintenance or info, because they have a start date in the future. + // However, if someone creates an incident with a start date in the past, + // we should set up the right timestamp for the status update. + if inc.StartDate.Before(timestamp) { + timestamp = *inc.StartDate + } + + switch inc.Type { + case event.TypeInformation: + statusText = event.InfoPlannedStatusText() + status = event.InfoPlanned + case event.TypeMaintenance: + if inc.Status == event.MaintenancePendingReview { + statusText = event.MaintenancePendingReviewStatusText() + status = event.MaintenancePendingReview + } else { + statusText = event.MaintenancePlannedStatusText() + status = event.MaintenancePlanned + } + case event.TypeIncident: + statusText = event.IncidentDetectedStatusText() + status = event.IncidentDetected + } + + inc.Statuses = append(inc.Statuses, db.IncidentStatus{ + IncidentID: inc.ID, + Status: status, + Text: statusText, + Timestamp: timestamp, + CreatedBy: userID, + }) + inc.Status = status + + if err = dbInst.ModifyIncidentTx(ctx, tx, inc); err != nil { + return err + } + + // A newly created maintenance has no previous status. + return publishMaintenanceChange(ctx, tx, pub, inc, "", userID) +} + // optionalPublisher extracts the single optional publisher from a variadic arg. func optionalPublisher(pub []*notification.Publisher) *notification.Publisher { if len(pub) > 0 { diff --git a/internal/db/db.go b/internal/db/db.go index 12d2ceb..10f4f56 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -188,6 +188,12 @@ func noPublicStatus() predicate.Incident { // GetEventsWithCount retrieves events based on the provided parameters, with pagination and total count. func (db *DB) GetEventsWithCount( ctx context.Context, isAuth bool, params ...*IncidentsParams, +) ([]*Incident, int64, error) { + return db.getEventsWithCount(ctx, db.e, isAuth, params...) +} + +func (db *DB) getEventsWithCount( + ctx context.Context, c *ent.Client, isAuth bool, params ...*IncidentsParams, ) ([]*Incident, int64, error) { var param IncidentsParams if len(params) > 0 && params[0] != nil { @@ -200,13 +206,13 @@ func (db *DB) GetEventsWithCount( } // Get total count before applying limit and offset. - count, err := db.e.Incident.Query().Where(preds...).Count(ctx) + count, err := c.Incident.Query().Where(preds...).Count(ctx) if err != nil { return nil, 0, err } total := int64(count) - query := db.e.Incident.Query(). + query := c.Incident.Query(). Where(preds...). WithComponents(func(q *ent.ComponentQuery) { q.Select(component.FieldID, component.FieldName) @@ -239,7 +245,7 @@ func (db *DB) GetEventsWithCount( events = append(events, incidentFromEnt(row)) } - grouped, err := db.statusesByIncident(ctx, incidentIDs(rows)) + grouped, err := statusesByIncident(ctx, c, incidentIDs(rows)) if err != nil { return nil, 0, err } @@ -260,6 +266,16 @@ func (db *DB) GetEventsInternal(ctx context.Context, params ...*IncidentsParams) return db.GetEvents(ctx, AuthorizedAccess, params...) } +// GetEventsInternalTx retrieves all events through tx. A transaction that holds +// an advisory lock needs this variant to observe rows committed by the previous +// lock holder instead of a stale snapshot from another connection. +func (db *DB) GetEventsInternalTx( + ctx context.Context, tx *Tx, params ...*IncidentsParams, +) ([]*Incident, error) { + events, _, err := db.getEventsWithCount(ctx, db.clientFor(tx), AuthorizedAccess, params...) + return events, err +} + func (db *DB) GetIncident(ctx context.Context, id int) (*Incident, error) { e, err := db.e.Incident.Query(). Where(incident.IDEQ(id)). @@ -276,7 +292,7 @@ func (db *DB) GetIncident(ctx context.Context, id int) (*Incident, error) { } inc := incidentFromEnt(e) - grouped, err := db.statusesByIncident(ctx, []int{e.ID}) + grouped, err := statusesByIncident(ctx, db.e, []int{e.ID}) if err != nil { return nil, err } @@ -479,6 +495,22 @@ func applyIncidentPatch(update *ent.IncidentUpdate, inc *Incident) { // AddComponentToIncident adds a component and a status update to an incident using optimistic locking. func (db *DB) AddComponentToIncident(ctx context.Context, inc *Incident, comp *Component, status IncidentStatus) error { + return db.execWithTx(ctx, nil, func(client *ent.Client, _ entsql.ExecQuerier) error { + return addComponentToIncident(ctx, client, inc, comp, status) + }) +} + +// AddComponentToIncidentTx adds a component and a status update inside the +// caller's transaction, for callers that already hold a lock on the incident. +func (db *DB) AddComponentToIncidentTx( + ctx context.Context, tx *Tx, inc *Incident, comp *Component, status IncidentStatus, +) error { + return addComponentToIncident(ctx, db.clientFor(tx), inc, comp, status) +} + +func addComponentToIncident( + ctx context.Context, client *ent.Client, inc *Incident, comp *Component, status IncidentStatus, +) error { if inc.Version == nil { return errors.New("version is required for incident modification") } @@ -486,31 +518,25 @@ func (db *DB) AddComponentToIncident(ctx context.Context, inc *Incident, comp *C expectedVersion := *inc.Version newVersion := expectedVersion + 1 - err := db.execWithTx(ctx, nil, func(client *ent.Client, _ entsql.ExecQuerier) error { - affected, err := client.Incident.Update(). - Where(incident.IDEQ(int(inc.ID)), incident.VersionEQ(expectedVersion)). - SetVersion(newVersion). - Save(ctx) - if err != nil { - return err - } - if affected == 0 { - return ErrVersionConflict - } - - if comp.ID != 0 { - if _, err = client.Incident.UpdateOneID(int(inc.ID)).AddComponentIDs(int(comp.ID)).Save(ctx); err != nil { - return err - } - inc.Components = append(inc.Components, *comp) - } + affected, err := client.Incident.Update(). + Where(incident.IDEQ(int(inc.ID)), incident.VersionEQ(expectedVersion)). + SetVersion(newVersion). + Save(ctx) + if err != nil { + return err + } + if affected == 0 { + return ErrVersionConflict + } - if _, err = insertIncidentStatus(ctx, client, &status, inc.ID); err != nil { + if comp.ID != 0 { + if _, err = client.Incident.UpdateOneID(int(inc.ID)).AddComponentIDs(int(comp.ID)).Save(ctx); err != nil { return err } - return nil - }) - if err != nil { + inc.Components = append(inc.Components, *comp) + } + + if _, err = insertIncidentStatus(ctx, client, &status, inc.ID); err != nil { return err } @@ -596,7 +622,7 @@ func (db *DB) GetEventsByComponentID( incidents = append(incidents, incidentFromEnt(row)) } - grouped, err := db.statusesByIncident(ctx, incidentIDs(rows)) + grouped, err := statusesByIncident(ctx, db.e, incidentIDs(rows)) if err != nil { return nil, err } diff --git a/internal/db/event_types.go b/internal/db/event_types.go index 6257b54..cb21024 100644 --- a/internal/db/event_types.go +++ b/internal/db/event_types.go @@ -26,7 +26,7 @@ func (db *DB) getEventsByType( incidents = append(incidents, incidentFromEnt(row)) } - grouped, err := db.statusesByIncident(ctx, incidentIDs(rows)) + grouped, err := statusesByIncident(ctx, db.e, incidentIDs(rows)) if err != nil { return nil, err } diff --git a/internal/db/lock.go b/internal/db/lock.go index 6fdc0fb..61821ec 100644 --- a/internal/db/lock.go +++ b/internal/db/lock.go @@ -2,6 +2,7 @@ package db import ( "context" + "strconv" entsql "entgo.io/ent/dialect/sql" ) @@ -46,3 +47,26 @@ func lockComponentName(ctx context.Context, raw entsql.ExecQuerier, name, region _, err := raw.ExecContext(ctx, "SELECT pg_advisory_xact_lock(hashtext($1))", name+"|"+region) return err } + +// lockSystemIncident serializes creation of a system incident for one impact +// until the surrounding transaction ends. The key is hashed in Postgres so its +// length stays constant; a hash collision only makes unrelated creations wait. +func lockSystemIncident(ctx context.Context, raw entsql.ExecQuerier, impact int) error { + _, err := raw.ExecContext( + ctx, "SELECT pg_advisory_xact_lock(hashtext($1))", "system-incident|"+strconv.Itoa(impact), + ) + return err +} + +// WithSystemIncidentLock runs fn in a transaction holding the advisory lock +// that serializes system incident creation for impact. The lookup and the +// insert must happen inside fn: a competing caller waits for the lock and then +// observes the committed incident instead of creating a duplicate. +func (db *DB) WithSystemIncidentLock(ctx context.Context, impact int, fn func(tx *Tx) error) error { + return db.WithTx(ctx, func(tx *Tx) error { + if err := lockSystemIncident(ctx, db.rawFor(tx), impact); err != nil { + return err + } + return fn(tx) + }) +} diff --git a/internal/db/mappers.go b/internal/db/mappers.go index de76394..435e77f 100644 --- a/internal/db/mappers.go +++ b/internal/db/mappers.go @@ -116,7 +116,9 @@ const incidentStatusChunkSize = 1000 // statusesByIncident loads the update history for the given incidents. The Ent // schema has no status edge (production carries no foreign key on // incident_status), so callers attach the result themselves. -func (db *DB) statusesByIncident(ctx context.Context, ids []int) (map[int][]IncidentStatus, error) { +func statusesByIncident( + ctx context.Context, c *ent.Client, ids []int, +) (map[int][]IncidentStatus, error) { grouped := make(map[int][]IncidentStatus, len(ids)) if len(ids) == 0 { return grouped, nil @@ -125,7 +127,7 @@ func (db *DB) statusesByIncident(ctx context.Context, ids []int) (map[int][]Inci for start := 0; start < len(ids); start += incidentStatusChunkSize { end := min(start+incidentStatusChunkSize, len(ids)) - rows, err := db.e.IncidentStatus.Query(). + rows, err := c.IncidentStatus.Query(). Where(incidentstatus.IncidentIDIn(ids[start:end]...)). Order(incidentstatus.ByID(entsql.OrderAsc())). All(ctx) diff --git a/internal/db/raw.go b/internal/db/raw.go index d4c61fb..cd0f740 100644 --- a/internal/db/raw.go +++ b/internal/db/raw.go @@ -80,7 +80,7 @@ func (db *DB) incidentsByIDs(ctx context.Context, ids []int) ([]*Incident, error } } - grouped, err := db.statusesByIncident(ctx, ids) + grouped, err := statusesByIncident(ctx, db.e, ids) if err != nil { return nil, err } diff --git a/tests/system_incident_lock_test.go b/tests/system_incident_lock_test.go new file mode 100644 index 0000000..4abab9d --- /dev/null +++ b/tests/system_incident_lock_test.go @@ -0,0 +1,106 @@ +package tests + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + v2 "github.com/stackmon/otc-status-dashboard/internal/api/v2" + "github.com/stackmon/otc-status-dashboard/internal/event" +) + +// TestSystemIncidentCreationSerializedByImpact posts one system incident per +// component at the same time. All calls must converge on the single system +// incident created for the impact instead of creating one incident per caller. +func TestSystemIncidentCreationSerializedByImpact(t *testing.T) { + r := initTests(t) + truncateIncidents(t) + + impact := 2 + system := true + start := time.Now().UTC() + componentIDs := []int{1, 2, 3, 4} + + sqlDB := openRawDB(t) + activeSystemIncidents := "system AND type = 'incident' AND end_date IS NULL AND impact = $1" + require.Equal(t, int64(0), tableCount(t, sqlDB, "incident", activeSystemIncidents, impact)) + + type outcome struct { + componentID int + incidentID int + status int + body string + } + + gate := make(chan struct{}) + results := make(chan outcome, len(componentIDs)) + var wg sync.WaitGroup + + for _, componentID := range componentIDs { + payload, err := json.Marshal(v2.IncidentData{ + Title: "concurrent system incident", + Description: "same impact from concurrent callers", + Impact: &impact, + Components: []int{componentID}, + StartDate: start, + System: &system, + Type: event.TypeIncident, + }) + require.NoError(t, err) + + wg.Add(1) + go func(id int, body []byte) { + defer wg.Done() + <-gate + + w := httptest.NewRecorder() + req, reqErr := http.NewRequest(http.MethodPost, v2IncidentsEndpoint, bytes.NewReader(body)) + if reqErr != nil { + results <- outcome{componentID: id, body: reqErr.Error()} + return + } + req.Header.Set("Authorization", "Bearer "+adminToken) + r.ServeHTTP(w, req) + + res := outcome{componentID: id, status: w.Code, body: w.Body.String()} + if w.Code == http.StatusOK { + var resp v2.PostIncidentResp + if unmarshalErr := json.Unmarshal(w.Body.Bytes(), &resp); unmarshalErr == nil && + len(resp.Result) == 1 { + res.incidentID = resp.Result[0].IncidentID + } + } + results <- res + }(componentID, payload) + } + + close(gate) + wg.Wait() + close(results) + + incidentID := 0 + for res := range results { + require.Equalf(t, http.StatusOK, res.status, "component %d: %s", res.componentID, res.body) + require.NotZerof(t, res.incidentID, "component %d: %s", res.componentID, res.body) + + if incidentID == 0 { + incidentID = res.incidentID + continue + } + assert.Equal(t, incidentID, res.incidentID, + "component %d was attached to a different system incident", res.componentID) + } + + incident := v2GetEvent(t, r, incidentID) + assert.True(t, *incident.System) + assert.ElementsMatch(t, componentIDs, incident.Components) + + assert.Equal(t, int64(1), tableCount(t, sqlDB, "incident", activeSystemIncidents, impact)) +}