Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 121 additions & 28 deletions internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,14 @@ func (db *DB) GetEventsInternalTx(
}

func (db *DB) GetIncident(ctx context.Context, id int) (*Incident, error) {
e, err := db.e.Incident.Query().
return db.getIncidentTx(ctx, nil, id)
}

// getIncidentTx reads an incident with its components and statuses through tx,
// or through the pool when tx is nil.
func (db *DB) getIncidentTx(ctx context.Context, tx *Tx, id int) (*Incident, error) {
c := db.clientFor(tx)
e, err := c.Incident.Query().
Where(incident.IDEQ(id)).
WithComponents(func(q *ent.ComponentQuery) {
q.Select(component.FieldID, component.FieldName)
Expand All @@ -292,11 +299,19 @@ func (db *DB) GetIncident(ctx context.Context, id int) (*Incident, error) {
}

inc := incidentFromEnt(e)
grouped, err := statusesByIncident(ctx, db.e, []int{e.ID})

statuses, err := c.IncidentStatus.Query().
Where(incidentstatus.IncidentID(e.ID)).
Order(incidentstatus.ByID(entsql.OrderAsc())).
All(ctx)

if err != nil {
return nil, err
}
attachStatuses([]*Incident{inc}, grouped)
inc.Statuses = make([]IncidentStatus, 0, len(statuses))
for _, status := range statuses {
inc.Statuses = append(inc.Statuses, incidentStatusFromEnt(status))
}

return inc, nil
}
Expand Down Expand Up @@ -910,6 +925,49 @@ func (db *DB) MoveComponentFromOldToAnotherIncident(
return incNew, nil
}

// currentComponentsTx re-reads the components to extract inside the
// transaction, preserving the caller's order. A component that disappeared
// aborts the extraction instead of being reported with stale attributes.
func (db *DB) currentComponentsTx(ctx context.Context, tx *Tx, comps []Component) ([]Component, error) {
ids := make([]int, 0, len(comps))
for i := range comps {
if comps[i].ID != 0 {
ids = append(ids, int(comps[i].ID))
}
}
if len(ids) == 0 {
return comps, nil
}

rows, err := db.clientFor(tx).Component.Query().
Where(component.IDIn(ids...), component.DeletedAtIsNil()).
WithAttributes().
All(ctx)
if err != nil {
return nil, err
}

byID := make(map[int]Component, len(rows))
for _, row := range rows {
byID[row.ID] = componentFromEnt(row)
}

out := make([]Component, len(comps))
for i := range comps {
if comps[i].ID == 0 {
out[i] = comps[i]
continue
}
stored, ok := byID[int(comps[i].ID)]
if !ok {
return nil, ErrDBComponentDSNotExist
}
out[i] = stored
}

return out, nil
}

func (db *DB) ExtractComponentsToNewIncident(
ctx context.Context, comp []Component, incOld *Incident, impact int, text string, description *string,
) (*Incident, error) {
Expand All @@ -933,38 +991,33 @@ func (db *DB) ExtractComponentsToNewIncident(
}

err := db.WithTx(ctx, func(tx *Tx) error {
if _, saveErr := db.SaveIncidentTx(ctx, tx, inc); saveErr != nil {
return saveErr
// The caller loaded the source incident before this transaction, so lock
// and re-read it: its components, statuses and version may have changed.
if lockErr := lockIncidentRows(ctx, db.rawFor(tx), incOld.ID); lockErr != nil {
return lockErr
}
freshOld, readErr := db.getIncidentTx(ctx, tx, int(incOld.ID))
if readErr != nil {
return readErr
}
*incOld = *freshOld

for _, c := range comp {
inc.Statuses = append(inc.Statuses, IncidentStatus{
IncidentID: inc.ID,
Status: event.OutDatedSystem,
Text: fmt.Sprintf("%s moved from %s", c.PrintAttrs(), incOld.Link()),
Timestamp: timeNow,
})
freshComps, readErr := db.currentComponentsTx(ctx, tx, comp)
if readErr != nil {
return readErr
}
comp = freshComps
inc.Components = comp

for _, c := range comp {
incOld.Statuses = append(incOld.Statuses, IncidentStatus{
IncidentID: incOld.ID,
Status: event.OutDatedSystem,
Text: fmt.Sprintf("%s moved to %s", c.PrintAttrs(), inc.Link()),
Timestamp: timeNow,
})
if _, saveErr := db.SaveIncidentTx(ctx, tx, inc); saveErr != nil {
return saveErr
}

client := db.clientFor(tx)
appendExtractionStatuses(inc, incOld, comp, timeNow)

for i := range comp {
if comp[i].ID == 0 {
continue
}
if errRemove := removeIncidentComponent(ctx, client, incOld.ID, comp[i].ID); errRemove != nil {
return errRemove
}
dropIncidentComponent(incOld, comp[i].ID)
client := db.clientFor(tx)
if errRemove := detachExtractedComponents(ctx, client, incOld, comp); errRemove != nil {
return errRemove
}

if errSave := saveIncidentFull(ctx, client, inc); errSave != nil {
Expand All @@ -979,6 +1032,46 @@ func (db *DB) ExtractComponentsToNewIncident(
return inc, nil
}

// appendExtractionStatuses records the move on both incidents; the following
// saveIncidentFull calls insert the rows.
func appendExtractionStatuses(inc, incOld *Incident, comp []Component, timeNow time.Time) {
for _, c := range comp {
inc.Statuses = append(inc.Statuses, IncidentStatus{
IncidentID: inc.ID,
Status: event.OutDatedSystem,
Text: fmt.Sprintf("%s moved from %s", c.PrintAttrs(), incOld.Link()),
Timestamp: timeNow,
})
}

for _, c := range comp {
incOld.Statuses = append(incOld.Statuses, IncidentStatus{
IncidentID: incOld.ID,
Status: event.OutDatedSystem,
Text: fmt.Sprintf("%s moved to %s", c.PrintAttrs(), inc.Link()),
Timestamp: timeNow,
})
}
}

// detachExtractedComponents removes the extracted components from the source
// incident and from its in-memory association list.
func detachExtractedComponents(
ctx context.Context, client *ent.Client, incOld *Incident, comp []Component,
) error {
for i := range comp {
if comp[i].ID == 0 {
continue
}
if err := removeIncidentComponent(ctx, client, incOld.ID, comp[i].ID); err != nil {
return err
}
dropIncidentComponent(incOld, comp[i].ID)
}

return nil
}

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")
Expand Down
21 changes: 21 additions & 0 deletions internal/db/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package db

import (
"context"
"slices"
"strconv"

entsql "entgo.io/ent/dialect/sql"
Expand Down Expand Up @@ -40,6 +41,26 @@ func (db *DB) WithAdvisoryLock(ctx context.Context, key int64, fn func(context.C
return fn(ctx)
}

// lockIncidentRows takes row locks on the given incidents until the surrounding
// transaction ends. Rows are locked in ascending id order so transactions that
// touch the same pair cannot deadlock. Only the named rows are locked: two
// extractions from different incidents that share a component stay unserialized,
// which is accepted and out of scope here.
func lockIncidentRows(ctx context.Context, raw entsql.ExecQuerier, ids ...uint) error {
ordered := slices.Clone(ids)
slices.Sort(ordered)

for _, id := range ordered {
if _, err := raw.ExecContext(
ctx, "SELECT id FROM incident WHERE id = $1 FOR UPDATE", int(id),
); err != nil {
return err
}
}

return nil
}

// lockComponentName serializes component creation for one (name, region) pair
// until the surrounding transaction ends. The key is hashed in Postgres so its
// length stays constant; a hash collision only makes unrelated inserts wait.
Expand Down
121 changes: 117 additions & 4 deletions tests/extract_tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,12 @@ func TestExtractComponentsRollsBackOnSecondPhaseFailure(t *testing.T) {
require.NoError(t, err)
require.Len(t, incOld.Components, 1)

// An empty text fails saveIncidentFull after the new incident, its statuses
// and the association removal were written.
emptyText := ""
incOld.Text = &emptyText
// An empty stored text fails saveIncidentFull after the new incident, its
// statuses and the association removal were written. Updating the row rather
// than the caller's copy also proves the extraction re-reads it in the
// transaction.
_, err = g.Exec("UPDATE incident SET text = '' WHERE id = $1", oldID)
require.NoError(t, err)

newText := "extracted incident " + uuid.NewString()
description := "extract transaction probe"
Expand All @@ -68,3 +70,114 @@ func TestExtractComponentsRollsBackOnSecondPhaseFailure(t *testing.T) {
assert.Equal(t, int64(1), tableCount(t, g, "incident_component_relation",
"incident_id = $1 AND component_id = $2", oldID, comp.ID))
}

// TestExtractComponentsUsesFreshIncidentState changes the source incident after
// the caller has read it and checks that the extraction works from the stored
// row: a component and a version written by the concurrent change must survive.
func TestExtractComponentsUsesFreshIncidentState(t *testing.T) {
ctx := context.Background()
d, _ := newNotifDB(t)

probes := make([]*db.Component, 3)
for i := range probes {
probes[i] = newProbeComponent("extract probe "+uuid.NewString(), "EU-DE")
_, err := d.SaveComponent(ctx, probes[i])
require.NoError(t, err)
}
compA, compB, compC := probes[0], probes[1], probes[2]

start := time.Now().UTC()
impact := 2
oldText := "source incident " + uuid.NewString()

oldID, err := d.SaveIncident(ctx, &db.Incident{
Text: &oldText,
StartDate: &start,
Impact: &impact,
Status: event.OutDatedSystem,
Type: event.TypeIncident,
Components: []db.Component{*compA, *compB},
})
require.NoError(t, err)

staleOld, err := d.GetIncident(ctx, int(oldID))
require.NoError(t, err)
require.Len(t, staleOld.Components, 2)

// The caller's copy is stale from here on: a concurrent writer adds a
// component and bumps the version before the extraction starts.
freshOld, err := d.GetIncident(ctx, int(oldID))
require.NoError(t, err)
added := db.IncidentStatus{
IncidentID: oldID,
Status: event.IncidentDetected,
Text: "concurrent update",
Timestamp: time.Now().UTC(),
}
require.NoError(t, d.AddComponentToIncident(ctx, freshOld, compC, added))

newText := "extracted incident " + uuid.NewString()
description := "fresh read probe"
inc, err := d.ExtractComponentsToNewIncident(
ctx, []db.Component{*compA}, staleOld, impact, newText, &description,
)
require.NoError(t, err)
require.Len(t, inc.Components, 1)
assert.Equal(t, compA.ID, inc.Components[0].ID)

after, err := d.GetIncident(ctx, int(oldID))
require.NoError(t, err)
assert.ElementsMatch(t, []uint{compB.ID, compC.ID}, incidentComponentIDs(after))
assert.Equal(t, *freshOld.Version, *after.Version,
"the extraction must keep the version written by the concurrent change")
}

// TestExtractComponentsAbortsOnSoftDeletedComponent soft-deletes a component
// between the caller's read and the extraction; the re-read must treat it as
// missing instead of extracting it with stale attributes.
func TestExtractComponentsAbortsOnSoftDeletedComponent(t *testing.T) {
ctx := context.Background()
d, g := newNotifDB(t)

comp := newProbeComponent("extract probe "+uuid.NewString(), "EU-FR")
_, err := d.SaveComponent(ctx, comp)
require.NoError(t, err)

start := time.Now().UTC()
impact := 2
oldText := "source incident " + uuid.NewString()
oldID, err := d.SaveIncident(ctx, &db.Incident{
Text: &oldText,
StartDate: &start,
Impact: &impact,
Status: event.OutDatedSystem,
Type: event.TypeIncident,
Components: []db.Component{*comp},
})
require.NoError(t, err)

incOld, err := d.GetIncident(ctx, int(oldID))
require.NoError(t, err)

_, err = g.Exec("UPDATE component SET deleted_at = now() WHERE id = $1", comp.ID)
require.NoError(t, err)

newText := "extracted incident " + uuid.NewString()
description := "soft delete probe"
_, err = d.ExtractComponentsToNewIncident(
ctx, []db.Component{*comp}, incOld, impact, newText, &description,
)
require.ErrorIs(t, err, db.ErrDBComponentDSNotExist)

assert.Equal(t, int64(0), tableCount(t, g, "incident", "text = $1", newText))
assert.Equal(t, int64(1), tableCount(t, g, "incident_component_relation",
"incident_id = $1 AND component_id = $2", oldID, comp.ID))
}

func incidentComponentIDs(inc *db.Incident) []uint {
ids := make([]uint, len(inc.Components))
for i := range inc.Components {
ids[i] = inc.Components[i].ID
}
return ids
}