diff --git a/go.mod b/go.mod index 3515903..1c547be 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/stretchr/testify v1.11.1 github.com/upfluence/errors v0.2.17 github.com/upfluence/log v0.0.6 + github.com/upfluence/stats v0.2.1 ) require ( diff --git a/go.sum b/go.sum index 70b7f62..6a8fb05 100644 --- a/go.sum +++ b/go.sum @@ -30,6 +30,8 @@ github.com/upfluence/errors v0.2.17 h1:fjuWvx31U34U4I6Ugx+JtaqQ/RTTaWbGJXw3bL9JD github.com/upfluence/errors v0.2.17/go.mod h1:F20G28/uHKxrcXwrufkVl7iy/SVozr+6w9Xyg5BEx0k= github.com/upfluence/log v0.0.6 h1:cG+dq0CXTZTXGknzwZbQEW2QQH6KRjUu9rysdhmhBcA= github.com/upfluence/log v0.0.6/go.mod h1:pCbKPbgnoF5zqR9JsTgParTIEBvqXsIuaa8eoEVhdPA= +github.com/upfluence/stats v0.2.1 h1:T3d7fQsL2rdthYqDTF6rRIXRUKtvM98hGRwNoonuots= +github.com/upfluence/stats v0.2.1/go.mod h1:68ZOq0AWeoZlgdp9M50Vxbtxl6+HCtsMlAcSEQmSr4Y= go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= diff --git a/middleware/stats/batch.go b/middleware/stats/batch.go new file mode 100644 index 0000000..6226fff --- /dev/null +++ b/middleware/stats/batch.go @@ -0,0 +1,35 @@ +package stats + +import "github.com/upfluence/cql" + +type batch struct { + cql.Batch + + instruments instruments + queries int64 +} + +func (b *batch) Query(stmt string, vs ...any) { + b.queries++ + b.Batch.Query(stmt, vs...) +} + +func (b *batch) Exec() error { + b.instruments.batchQueries.Add(b.queries) + + operation := b.instruments.batchExec.Begin() + err := b.Batch.Exec() + operation.Finish(err) + + return err //nolint:wrapcheck +} + +func (b *batch) ExecCAS() (bool, cql.Cursor, error) { + b.instruments.batchQueries.Add(b.queries) + + operation := b.instruments.batchExecCAS.Begin() + applied, cur, err := b.Batch.ExecCAS() + operation.Finish(err) + + return applied, cur, err //nolint:wrapcheck +} diff --git a/middleware/stats/cursor.go b/middleware/stats/cursor.go new file mode 100644 index 0000000..51c0516 --- /dev/null +++ b/middleware/stats/cursor.go @@ -0,0 +1,36 @@ +package stats + +import ( + "sync" + + "github.com/upfluence/stats" + + "github.com/upfluence/cql" +) + +// cursor finishes its operation on Close: a CQL cursor only reports the +// query error once it is closed. +type cursor struct { + cql.Cursor + + once sync.Once + operation stats.Operation + rowsScanned stats.Counter +} + +func (c *cursor) Scan(vs ...any) bool { + ok := c.Cursor.Scan(vs...) + + if ok { + c.rowsScanned.Inc() + } + + return ok +} + +func (c *cursor) Close() error { + err := c.Cursor.Close() + c.once.Do(func() { c.operation.Finish(err) }) + + return err //nolint:wrapcheck +} diff --git a/middleware/stats/db_test.go b/middleware/stats/db_test.go new file mode 100644 index 0000000..a0207ab --- /dev/null +++ b/middleware/stats/db_test.go @@ -0,0 +1,203 @@ +package stats + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/upfluence/cql" +) + +func TestExec(t *testing.T) { + for _, tt := range []struct { + name string + haveErr error + wantStatus string + }{ + {name: successCase, wantStatus: success}, + {name: failureCase, haveErr: errQuery, wantStatus: failed}, + } { + t.Run(tt.name, func(t *testing.T) { + rawDB := &fakeDB{err: tt.haveErr} + db, collector := wrap(rawDB) + + err := db.Exec(context.Background(), queryString, 42) + + assert.Equal(t, tt.haveErr, err) + assert.Equal(t, []string{queryString}, rawDB.stmts) + assert.Equal(t, counters(0, 0, metric("exec_total", tt.wantStatus)), collector.Get().Counters) + }) + } +} + +func TestExecCAS(t *testing.T) { + for _, tt := range []struct { + name string + haveErr error + haveApplied bool + wantStatus string + }{ + {name: successCase, haveApplied: true, wantStatus: success}, + {name: failureCase, haveErr: errQuery, wantStatus: failed}, + } { + t.Run(tt.name, func(t *testing.T) { + rawDB := &fakeDB{scanner: &fakeScanner{err: tt.haveErr, applied: tt.haveApplied}} + db, collector := wrap(rawDB) + + scanner := db.ExecCAS(context.Background(), queryString, 42) + + assert.Equal(t, counters(0, 0), collector.Get().Counters) + + applied, err := scanner.ScanCAS() + + assert.Equal(t, tt.haveErr, err) + assert.Equal(t, tt.haveApplied, applied) + assert.Equal(t, []string{queryString}, rawDB.stmts) + assert.Equal(t, counters(0, 0, metric("exec_cas_total", tt.wantStatus)), collector.Get().Counters) + }) + } +} + +func TestQueryRow(t *testing.T) { + for _, tt := range []struct { + name string + haveErr error + wantStatus string + }{ + {name: successCase, wantStatus: success}, + {name: failureCase, haveErr: errQuery, wantStatus: failed}, + } { + t.Run(tt.name, func(t *testing.T) { + rawDB := &fakeDB{scanner: &fakeScanner{err: tt.haveErr}} + db, collector := wrap(rawDB) + + scanner := db.QueryRow(context.Background(), queryString, 42) + + assert.Equal(t, counters(0, 0), collector.Get().Counters) + + err := scanner.Scan() + + assert.Equal(t, tt.haveErr, err) + assert.Equal(t, []string{queryString}, rawDB.stmts) + assert.Equal(t, counters(0, 0, metric("query_row_total", tt.wantStatus)), collector.Get().Counters) + }) + } +} + +func TestQueryRowFinishesOnce(t *testing.T) { + db, collector := wrap(&fakeDB{scanner: &fakeScanner{}}) + + scanner := db.QueryRow(context.Background(), queryString) + + require.NoError(t, scanner.Scan()) + require.NoError(t, scanner.Scan()) + assert.Equal(t, counters(0, 0, metric("query_row_total", success)), collector.Get().Counters) +} + +func TestQuery(t *testing.T) { + for _, tt := range []struct { + name string + haveRows int + haveErr error + wantStatus string + wantScanned int64 + }{ + {name: successCase, haveRows: 2, wantStatus: success, wantScanned: 2}, + {name: "empty", wantStatus: success}, + {name: failureCase, haveErr: errQuery, wantStatus: failed}, + } { + t.Run(tt.name, func(t *testing.T) { + rawDB := &fakeDB{cursor: &fakeCursor{rows: tt.haveRows, closeErr: tt.haveErr}} + db, collector := wrap(rawDB) + + cursor := db.Query(context.Background(), queryString, 42) + + for cursor.Scan() { + } + + assert.Equal(t, counters(tt.wantScanned, 0), collector.Get().Counters) + + err := cursor.Close() + + assert.Equal(t, tt.haveErr, err) + assert.Equal(t, []string{queryString}, rawDB.stmts) + assert.Equal( + t, + counters(tt.wantScanned, 0, metric("query_total", tt.wantStatus)), + collector.Get().Counters, + ) + }) + } +} + +func TestQueryFinishesOnce(t *testing.T) { + db, collector := wrap(&fakeDB{cursor: &fakeCursor{}}) + + cursor := db.Query(context.Background(), queryString) + + require.NoError(t, cursor.Close()) + require.NoError(t, cursor.Close()) + assert.Equal(t, counters(0, 0, metric("query_total", success)), collector.Get().Counters) +} + +func TestBatchExec(t *testing.T) { + for _, tt := range []struct { + name string + haveErr error + wantStatus string + }{ + {name: successCase, wantStatus: success}, + {name: failureCase, haveErr: errQuery, wantStatus: failed}, + } { + t.Run(tt.name, func(t *testing.T) { + rawBatch := &fakeBatch{err: tt.haveErr} + db, collector := wrap(&fakeDB{batch: rawBatch}) + + b := db.Batch(context.Background(), cql.LoggedBatch) + b.Query("q1", 1) + b.Query("q2", 2) + + assert.Equal(t, counters(0, 0), collector.Get().Counters) + + err := b.Exec() + + assert.Equal(t, tt.haveErr, err) + assert.Equal(t, []string{"q1", "q2"}, rawBatch.queries) + assert.Equal(t, counters(0, 2, metric("batch_exec_total", tt.wantStatus)), collector.Get().Counters) + }) + } +} + +func TestBatchExecCAS(t *testing.T) { + for _, tt := range []struct { + name string + haveErr error + haveApplied bool + wantStatus string + }{ + {name: successCase, haveApplied: true, wantStatus: success}, + {name: failureCase, haveErr: errQuery, wantStatus: failed}, + } { + t.Run(tt.name, func(t *testing.T) { + rawBatch := &fakeBatch{err: tt.haveErr, applied: tt.haveApplied} + db, collector := wrap(&fakeDB{batch: rawBatch}) + + b := db.Batch(context.Background(), cql.LoggedBatch) + b.Query("q1", 1) + + applied, cursor, err := b.ExecCAS() + + assert.Equal(t, tt.haveErr, err) + assert.Equal(t, tt.haveApplied, applied) + assert.Equal(t, &fakeCursor{}, cursor) + assert.Equal(t, []string{"q1"}, rawBatch.queries) + assert.Equal( + t, + counters(0, 1, metric("batch_exec_cas_total", tt.wantStatus)), + collector.Get().Counters, + ) + }) + } +} diff --git a/middleware/stats/middleware.go b/middleware/stats/middleware.go new file mode 100644 index 0000000..482079f --- /dev/null +++ b/middleware/stats/middleware.go @@ -0,0 +1,125 @@ +// Package stats instruments CQL database operations. +package stats + +import ( + "context" + + "github.com/upfluence/stats" + + "github.com/upfluence/cql" +) + +// Config configures each CQL operation instrument. +type Config struct { + ExecOptions []stats.InstrumentOption + ExecCASOptions []stats.InstrumentOption + QueryOptions []stats.InstrumentOption + QueryRowOptions []stats.InstrumentOption + BatchExecOptions []stats.InstrumentOption + BatchExecCASOptions []stats.InstrumentOption + + TrackRowsScanned bool + TrackBatchQueries bool +} + +type instruments struct { + exec stats.Instrument + execCAS stats.Instrument + query stats.Instrument + queryRow stats.Instrument + batchExec stats.Instrument + batchExecCAS stats.Instrument + + rowsScanned stats.Counter + batchQueries stats.Counter +} + +type factory struct { + instruments instruments +} + +// NewFactory creates a CQL middleware factory using scope. +func NewFactory(scope stats.Scope, cfg Config) cql.MiddlewareFactory { + rowsScanned := stats.NoopCounter + + if cfg.TrackRowsScanned { + rowsScanned = scope.Counter("rows_scanned_total") + } + + batchQueries := stats.NoopCounter + + if cfg.TrackBatchQueries { + batchQueries = scope.Counter("batch_queries_total") + } + + return &factory{ + instruments: instruments{ + exec: stats.NewInstrument(scope, "exec", cfg.ExecOptions...), + execCAS: stats.NewInstrument(scope, "exec_cas", cfg.ExecCASOptions...), + query: stats.NewInstrument(scope, "query", cfg.QueryOptions...), + queryRow: stats.NewInstrument(scope, "query_row", cfg.QueryRowOptions...), + batchExec: stats.NewInstrument(scope, "batch_exec", cfg.BatchExecOptions...), + batchExecCAS: stats.NewInstrument(scope, "batch_exec_cas", cfg.BatchExecCASOptions...), + + rowsScanned: rowsScanned, + batchQueries: batchQueries, + }, + } +} + +func (f *factory) Wrap(rawDB cql.DB) cql.DB { + return &db{db: rawDB, instruments: f.instruments} +} + +type db struct { + db cql.DB + + instruments instruments +} + +func (d *db) Unwrap() cql.DB { + return d.db +} + +func (d *db) Exec(ctx context.Context, stmt string, vs ...any) error { + operation := d.instruments.exec.Begin() + err := d.db.Exec(ctx, stmt, vs...) + operation.Finish(err) + + return err //nolint:wrapcheck +} + +func (d *db) ExecCAS(ctx context.Context, stmt string, vs ...any) cql.CASScanner { + operation := d.instruments.execCAS.Begin() + + return &casScanner{ + CASScanner: d.db.ExecCAS(ctx, stmt, vs...), + operation: operation, + } +} + +func (d *db) QueryRow(ctx context.Context, stmt string, vs ...any) cql.Scanner { + operation := d.instruments.queryRow.Begin() + + return &scanner{ + Scanner: d.db.QueryRow(ctx, stmt, vs...), + operation: operation, + } +} + +func (d *db) Query(ctx context.Context, stmt string, vs ...any) cql.Cursor { + operation := d.instruments.query.Begin() + + return &cursor{ + Cursor: d.db.Query(ctx, stmt, vs...), + operation: operation, + rowsScanned: d.instruments.rowsScanned, + } +} + +func (d *db) Batch(ctx context.Context, bt cql.BatchType, opts ...cql.Option) cql.Batch { + return &batch{ + Batch: d.db.Batch(ctx, bt, opts...), + instruments: d.instruments, + } +} diff --git a/middleware/stats/middleware_test.go b/middleware/stats/middleware_test.go new file mode 100644 index 0000000..0af8fcc --- /dev/null +++ b/middleware/stats/middleware_test.go @@ -0,0 +1,188 @@ +package stats + +import ( + "context" + "sort" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/upfluence/errors" + statslib "github.com/upfluence/stats" + + "github.com/upfluence/cql" +) + +const ( + failureCase = "failure" + failed = "failed" + queryString = "query" + statusLabel = "status" + success = "success" + successCase = "success" +) + +var ( + errQuery = errors.New("query") + + instrumentOptions = []statslib.InstrumentOption{ + statslib.DisableDurationTracking(), + statslib.DisableStartedCounter(), + } +) + +type fakeScanner struct { + err error + applied bool +} + +func (s *fakeScanner) Scan(...any) error { return s.err } + +func (s *fakeScanner) ScanCAS(...any) (bool, error) { return s.applied, s.err } + +type fakeCursor struct { + rows int + closeErr error +} + +func (c *fakeCursor) Scan(...any) bool { + if c.rows == 0 { + return false + } + + c.rows-- + + return true +} + +func (c *fakeCursor) Close() error { return c.closeErr } + +type fakeBatch struct { + queries []string + err error + applied bool +} + +func (b *fakeBatch) Query(stmt string, _ ...any) { b.queries = append(b.queries, stmt) } + +func (b *fakeBatch) Exec() error { return b.err } + +func (b *fakeBatch) ExecCAS() (bool, cql.Cursor, error) { return b.applied, &fakeCursor{}, b.err } + +type fakeDB struct { + err error + scanner *fakeScanner + cursor *fakeCursor + batch *fakeBatch + + stmts []string +} + +func (db *fakeDB) Exec(_ context.Context, stmt string, _ ...any) error { + db.stmts = append(db.stmts, stmt) + + return db.err +} + +func (db *fakeDB) ExecCAS(_ context.Context, stmt string, _ ...any) cql.CASScanner { + db.stmts = append(db.stmts, stmt) + + return db.scanner +} + +func (db *fakeDB) QueryRow(_ context.Context, stmt string, _ ...any) cql.Scanner { + db.stmts = append(db.stmts, stmt) + + return db.scanner +} + +func (db *fakeDB) Query(_ context.Context, stmt string, _ ...any) cql.Cursor { + db.stmts = append(db.stmts, stmt) + + return db.cursor +} + +func (db *fakeDB) Batch(context.Context, cql.BatchType, ...cql.Option) cql.Batch { + return db.batch +} + +func testConfig() Config { + return Config{ + ExecOptions: instrumentOptions, + ExecCASOptions: instrumentOptions, + QueryOptions: instrumentOptions, + QueryRowOptions: instrumentOptions, + BatchExecOptions: instrumentOptions, + BatchExecCASOptions: instrumentOptions, + TrackRowsScanned: true, + TrackBatchQueries: true, + } +} + +func wrap(rawDB cql.DB) (cql.DB, *statslib.StaticCollector) { + collector := statslib.NewStaticCollector() + db := NewFactory(statslib.RootScope(collector), testConfig()).Wrap(rawDB) + + return db, collector +} + +func metric(name, status string) statslib.Int64Snapshot { + return statslib.Int64Snapshot{ + Name: name, + Labels: map[string]string{statusLabel: status}, + Value: 1, + } +} + +func counters(rowsScanned, batchQueries int64, metrics ...statslib.Int64Snapshot) []statslib.Int64Snapshot { + metrics = append( + metrics, + statslib.Int64Snapshot{Name: "batch_queries_total", Labels: map[string]string{}, Value: batchQueries}, + statslib.Int64Snapshot{Name: "rows_scanned_total", Labels: map[string]string{}, Value: rowsScanned}, + ) + sort.Sort(statslib.Int64Snapshots(metrics)) + + return metrics +} + +func TestUnwrap(t *testing.T) { + rawDB := &fakeDB{} + db, _ := wrap(rawDB) + + u, ok := db.(interface{ Unwrap() cql.DB }) + + require.True(t, ok) + assert.Same(t, rawDB, u.Unwrap()) +} + +func TestWithoutTracking(t *testing.T) { + rawDB := &fakeDB{ + cursor: &fakeCursor{rows: 2}, + batch: &fakeBatch{}, + } + cfg := testConfig() + cfg.TrackRowsScanned = false + cfg.TrackBatchQueries = false + collector := statslib.NewStaticCollector() + db := NewFactory(statslib.RootScope(collector), cfg).Wrap(rawDB) + + cursor := db.Query(context.Background(), queryString) + + for cursor.Scan() { + } + + require.NoError(t, cursor.Close()) + + b := db.Batch(context.Background(), cql.LoggedBatch) + b.Query(queryString) + + require.NoError(t, b.Exec()) + assert.Equal( + t, + []statslib.Int64Snapshot{ + metric("batch_exec_total", success), + metric("query_total", success), + }, + collector.Get().Counters, + ) +} diff --git a/middleware/stats/scanner.go b/middleware/stats/scanner.go new file mode 100644 index 0000000..0dc8166 --- /dev/null +++ b/middleware/stats/scanner.go @@ -0,0 +1,37 @@ +package stats + +import ( + "sync" + + "github.com/upfluence/stats" + + "github.com/upfluence/cql" +) + +type scanner struct { + cql.Scanner + + once sync.Once + operation stats.Operation +} + +func (s *scanner) Scan(vs ...any) error { + err := s.Scanner.Scan(vs...) + s.once.Do(func() { s.operation.Finish(err) }) + + return err //nolint:wrapcheck +} + +type casScanner struct { + cql.CASScanner + + once sync.Once + operation stats.Operation +} + +func (s *casScanner) ScanCAS(vs ...any) (bool, error) { + applied, err := s.CASScanner.ScanCAS(vs...) + s.once.Do(func() { s.operation.Finish(err) }) + + return applied, err //nolint:wrapcheck +}