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
2 changes: 1 addition & 1 deletion internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ func (db *DB) GetIncident(ctx context.Context, id int) (*Incident, error) {
// WithTx runs fn inside a single transaction on the shared connection pool.
// Callers use it to write a business change and enqueue its notification atomically.
func (db *DB) WithTx(ctx context.Context, fn func(tx *Tx) error) error {
tx, err := db.begin(ctx)
tx, err := db.begin(ctx, nil)
if err != nil {
return err
}
Expand Down
17 changes: 12 additions & 5 deletions internal/db/event_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,18 @@ import (
func (db *DB) getEventsByType(
ctx context.Context, eventType incident.Type, order entsql.OrderTermOption,
) ([]*Incident, error) {
query := db.e.Incident.Query().
Where(incident.TypeEQ(eventType)).
Order(incident.ByID(order))
// incident_status has no Ent edge, so the events and their history are read
// in two statements; one transaction keeps them on the same snapshot.
tx, err := db.beginRead(ctx)
if err != nil {
return nil, err
}
defer func() { _ = tx.rollback() }()

rows, err := query.All(ctx)
rows, err := tx.client.Incident.Query().
Where(incident.TypeEQ(eventType)).
Order(incident.ByID(order)).
All(ctx)
if err != nil {
return nil, err
}
Expand All @@ -26,7 +33,7 @@ func (db *DB) getEventsByType(
incidents = append(incidents, incidentFromEnt(row))
}

grouped, err := statusesByIncident(ctx, db.e, incidentIDs(rows))
grouped, err := statusesByIncident(ctx, tx.client, incidentIDs(rows))
if err != nil {
return nil, err
}
Expand Down
13 changes: 10 additions & 3 deletions internal/db/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ func (db *DB) rawFor(tx *Tx) entsql.ExecQuerier {
}

// begin starts a transaction whose Ent client and raw executor share one connection.
func (db *DB) begin(ctx context.Context) (*Tx, error) {
sqlTx, err := db.sql.BeginTx(ctx, nil)
func (db *DB) begin(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
sqlTx, err := db.sql.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
Expand All @@ -64,6 +64,13 @@ func (db *DB) begin(ctx context.Context) (*Tx, error) {
}, nil
}

// beginRead starts a read-only REPEATABLE READ transaction. READ COMMITTED takes
// a new snapshot per statement, so related reads could observe different points
// in time; REPEATABLE READ holds one snapshot for the whole transaction.
func (db *DB) beginRead(ctx context.Context) (*Tx, error) {
return db.begin(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
}

func (tx *Tx) commit() error {
return tx.sqlTx.Commit()
}
Expand All @@ -82,7 +89,7 @@ func (db *DB) execWithTx(
return fn(tx.client, tx.driver)
}

t, err := db.begin(ctx)
t, err := db.begin(ctx, nil)
if err != nil {
return err
}
Expand Down
63 changes: 63 additions & 0 deletions tests/events_snapshot_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package tests

import (
"context"
"database/sql"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/stackmon/otc-status-dashboard/internal/conf"
"github.com/stackmon/otc-status-dashboard/internal/db"
"github.com/stackmon/otc-status-dashboard/internal/event"
)

// Info events and their history are read in two statements. The returned
// statuses must be attached to the incidents they belong to, never to a
// neighbour that happens to be in the same result set.
func TestInfoEventsIncludeOwnStatuses(t *testing.T) {
truncateIncidents(t)
sqlDB := openRawDB(t)

firstID := insertInfoIncident(t, sqlDB, "first info event")
secondID := insertInfoIncident(t, sqlDB, "second info event")

insertIncidentStatus(t, sqlDB, firstID, string(event.InfoPlanned), "first planned")
insertIncidentStatus(t, sqlDB, secondID, string(event.InfoPlanned), "second planned")
insertIncidentStatus(t, sqlDB, secondID, string(event.InfoActive), "second active")

d, err := db.New(&conf.Config{DB: databaseURL})
require.NoError(t, err)
t.Cleanup(func() { _ = d.Close() })

events, err := d.GetInfoEvents(context.Background())
require.NoError(t, err)
require.Len(t, events, 2)

statuses := make(map[uint][]db.IncidentStatus, len(events))
for _, inc := range events {
require.NotEmpty(t, inc.Statuses, "every incident carries its history")
for _, status := range inc.Statuses {
assert.Equal(t, inc.ID, status.IncidentID, "status belongs to another incident")
}
statuses[inc.ID] = inc.Statuses
}

require.Len(t, statuses[firstID], 1)
assert.Equal(t, "first planned", statuses[firstID][0].Text)
require.Len(t, statuses[secondID], 2)
assert.Equal(t, "second planned", statuses[secondID][0].Text)
assert.Equal(t, "second active", statuses[secondID][1].Text)
}

func insertInfoIncident(t *testing.T, sqlDB *sql.DB, text string) uint {
t.Helper()

var id uint
require.NoError(t, sqlDB.QueryRow(
"INSERT INTO incident (text, start_date, impact, system, type, status) "+
"VALUES ($1, now(), 0, false, $2, $3) RETURNING id",
text, event.TypeInformation, event.InfoPlanned).Scan(&id))
return id
}