Skip to content
Draft
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
20 changes: 18 additions & 2 deletions submitqueue/extension/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ const MetricsResultNotFound = "not_found"
// CompleteReadMetricsOp finishes a store read's metrics. A read that finds no
// record has answered the question rather than failed, so ErrNotFound is recorded
// as result=not_found instead of result=error; every other outcome is classified
// by metrics.Op.Complete. Writes finish with metrics.Op.Complete directly: a write
// whose row is missing is an anomaly and stays counted as an error.
// by metrics.Op.Complete. Updates finish with metrics.Op.Complete directly: an
// update whose row is missing is an anomaly and stays counted as an error.
func CompleteReadMetricsOp(op metrics.Op, err error) {
if IsNotFound(err) {
op.CompleteAs(MetricsResultNotFound)
Expand All @@ -60,6 +60,22 @@ func CompleteReadMetricsOp(op metrics.Op, err error) {
// ErrAlreadyExists is returned by storage implementations when attempting to create a record with an ID that already exists.
var ErrAlreadyExists = errors.New("record already exists")

// MetricsResultAlreadyExists is the result tag CompleteCreateMetricsOp records for a record that already exists.
const MetricsResultAlreadyExists = "already_exists"

// CompleteCreateMetricsOp finishes the metrics of a create whose callers create
// idempotently, so ErrAlreadyExists confirms the record rather than failing and
// is recorded as result=already_exists. Every other outcome is classified by
// metrics.Op.Complete. A create whose duplicate signals a bug finishes with
// metrics.Op.Complete directly, so the duplicate stays counted as an error.
func CompleteCreateMetricsOp(op metrics.Op, err error) {
if errors.Is(err, ErrAlreadyExists) {
op.CompleteAs(MetricsResultAlreadyExists)
return
}
op.Complete(err)
}

// ErrVersionMismatch is returned by storage implementations when the expected entity version does not match the current version of the object.
// This is used to implement an optimistic locking mechanism, allowing multiple clients to update the same entity concurrently
// and either retry or implement idempotent operations. It is intrinsically a retryable infrastructure error.
Expand Down
24 changes: 24 additions & 0 deletions submitqueue/extension/storage/storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,27 @@ func TestCompleteReadMetricsOp(t *testing.T) {
})
}
}

func TestCompleteCreateMetricsOp(t *testing.T) {
tests := []struct {
name string
err error
result string
}{
{name: "success", result: "success"},
{name: "already exists", err: fmt.Errorf("request receipt: %w", ErrAlreadyExists), result: MetricsResultAlreadyExists},
{name: "other error", err: fmt.Errorf("connection refused"), result: "error"},
{name: "not found", err: WrapNotFound(sql.ErrNoRows), result: "error"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
scope := tally.NewTestScope("", nil)
CompleteCreateMetricsOp(metrics.Begin(scope, "create", metrics.StorageLatencyBuckets), tt.err)

histograms := scope.Snapshot().Histograms()
assert.Len(t, histograms, 1)
assert.Contains(t, histograms, "create.finish+result="+tt.result)
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func NewRequestReceiptStore(db *sql.DB, scope tally.Scope, queue string) storage

func (r *requestReceiptStore) Create(ctx context.Context, receipt entity.RequestReceipt) (retErr error) {
op := metrics.Begin(r.scope, "create", metrics.StorageLatencyBuckets)
defer func() { op.Complete(retErr) }()
defer func() { storage.CompleteCreateMetricsOp(op, retErr) }()

if receipt.Queue != r.queue {
return fmt.Errorf("request receipt queue %q does not match the store's bound queue %q", receipt.Queue, r.queue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import (

"github.com/DATA-DOG/go-sqlmock"
"github.com/go-sql-driver/mysql"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/uber-go/tally"
"github.com/uber/submitqueue/submitqueue/entity"
"github.com/uber/submitqueue/submitqueue/extension/storage"
)
Expand All @@ -39,30 +41,36 @@ func TestRequestReceiptStoreCreate(t *testing.T) {
receipt := entity.RequestReceipt{Queue: "monorepo/main", ReceivedAtMs: 1000, RequestID: "request/monorepo/main/1"}
writeErr := errors.New("write failed")
for _, tt := range []struct {
name string
err error
want error
name string
err error
want error
result string
}{
{name: "created"},
{name: "duplicate", err: &mysql.MySQLError{Number: mysqlErrDuplicateEntry}, want: storage.ErrAlreadyExists},
{name: "write failure", err: writeErr, want: writeErr},
{name: "created", result: "success"},
{name: "duplicate", err: &mysql.MySQLError{Number: mysqlErrDuplicateEntry}, want: storage.ErrAlreadyExists, result: storage.MetricsResultAlreadyExists},
{name: "write failure", err: writeErr, want: writeErr, result: "error"},
} {
t.Run(tt.name, func(t *testing.T) {
mock, store := newRequestReceiptStoreTest(t)
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
require.NoError(t, err)
t.Cleanup(func() { db.Close() })
scope := tally.NewTestScope("", nil)
store := NewRequestReceiptStore(db, scope, "monorepo/main")
write := mock.ExpectExec("INSERT INTO request_receipt (queue, received_at_ms, request_id) VALUES (?, ?, ?)").
WithArgs(receipt.Queue, receipt.ReceivedAtMs, receipt.RequestID)
if tt.err != nil {
write.WillReturnError(tt.err)
} else {
write.WillReturnResult(sqlmock.NewResult(0, 1))
}
err := store.Create(context.Background(), receipt)
err = store.Create(context.Background(), receipt)
if tt.want != nil {
require.ErrorIs(t, err, tt.want)
} else {
require.NoError(t, err)
}
require.NoError(t, mock.ExpectationsWereMet())
assert.Contains(t, scope.Snapshot().Histograms(), "create.finish+result="+tt.result)
})
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func NewRequestURIStore(db *sql.DB, scope tally.Scope, queue string) storage.Req

func (s *requestURIStore) Create(ctx context.Context, mapping entity.RequestURI) (retErr error) {
op := metrics.Begin(s.scope, "create", metrics.StorageLatencyBuckets)
defer func() { op.Complete(retErr) }()
defer func() { storage.CompleteCreateMetricsOp(op, retErr) }()

if mapping.Queue != s.queue {
return fmt.Errorf("request URI change_uri=%s queue %q does not match the store's bound queue %q", mapping.ChangeURI, mapping.Queue, s.queue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/go-sql-driver/mysql"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/uber-go/tally"

"github.com/uber/submitqueue/submitqueue/entity"
storage "github.com/uber/submitqueue/submitqueue/extension/storage"
Expand Down Expand Up @@ -56,6 +57,7 @@ func TestRequestURIStore_Create(t *testing.T) {
setup func(mock sqlmock.Sqlmock)
wantErr bool
wantErrIs error
result string
}{
{
name: "success",
Expand All @@ -64,6 +66,7 @@ func TestRequestURIStore_Create(t *testing.T) {
WithArgs(mapping.Queue, mapping.ChangeURI, mapping.ReceivedAtMs, mapping.RequestID).
WillReturnResult(sqlmock.NewResult(0, 1))
},
result: "success",
},
{
name: "duplicate mapping returns ErrAlreadyExists",
Expand All @@ -74,6 +77,7 @@ func TestRequestURIStore_Create(t *testing.T) {
},
wantErr: true,
wantErrIs: storage.ErrAlreadyExists,
result: storage.MetricsResultAlreadyExists,
},
{
name: "other exec error",
Expand All @@ -83,17 +87,21 @@ func TestRequestURIStore_Create(t *testing.T) {
WillReturnError(fmt.Errorf("connection reset"))
},
wantErr: true,
result: "error",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
db, mock, store := setupRequestURIStoreTest(t)
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer db.Close()
scope := tally.NewTestScope("", nil)
store := NewRequestURIStore(db, scope, testURIQueue)

tt.setup(mock)

err := store.Create(context.Background(), mapping)
err = store.Create(context.Background(), mapping)
if tt.wantErr {
require.Error(t, err)
if tt.wantErrIs != nil {
Expand All @@ -103,6 +111,7 @@ func TestRequestURIStore_Create(t *testing.T) {
require.NoError(t, err)
}
require.NoError(t, mock.ExpectationsWereMet())
assert.Contains(t, scope.Snapshot().Histograms(), "create.finish+result="+tt.result)
})
}
}
Expand Down