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
191 changes: 106 additions & 85 deletions internal/api/v2/v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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(
Expand Down Expand Up @@ -979,66 +991,75 @@ 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
}
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 {
Expand Down
80 changes: 53 additions & 27 deletions internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down Expand Up @@ -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
}
Expand All @@ -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)).
Expand All @@ -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
}
Expand Down Expand Up @@ -479,38 +495,48 @@ 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")
}

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
}

Expand Down Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion internal/db/event_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
Loading