-
Notifications
You must be signed in to change notification settings - Fork 0
Add otelhttp middleware for automatic HTTP request metrics #31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
aparajon
wants to merge
1
commit into
main
Choose a base branch
from
armand/otelhttp
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+187
−3
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| //go:build integration | ||
|
|
||
| package api | ||
|
|
||
| import ( | ||
| "database/sql" | ||
| "io" | ||
| "log/slog" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/block/spirit/pkg/utils" | ||
| _ "github.com/go-sql-driver/mysql" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| "github.com/testcontainers/testcontainers-go" | ||
| "github.com/testcontainers/testcontainers-go/modules/mysql" | ||
| "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" | ||
|
|
||
| "github.com/block/schemabot/pkg/storage/mysqlstore" | ||
| "github.com/block/schemabot/pkg/testutil" | ||
| ) | ||
|
|
||
| // TestMetricsAfterRequests starts a real service with MySQL storage, hits | ||
| // several API endpoints, then scrapes /metrics and verifies that HTTP server | ||
| // metrics appear in the Prometheus text output. | ||
| func TestMetricsAfterRequests(t *testing.T) { | ||
| ctx := t.Context() | ||
|
|
||
| container, err := mysql.Run(ctx, | ||
| "mysql:8.4", | ||
| mysql.WithDatabase("schemabot_test"), | ||
| mysql.WithUsername("root"), | ||
| mysql.WithPassword("test"), | ||
| ) | ||
| require.NoError(t, err, "failed to start mysql") | ||
| t.Cleanup(func() { | ||
| if err := testcontainers.TerminateContainer(container); err != nil { | ||
| t.Logf("failed to terminate container: %v", err) | ||
| } | ||
| }) | ||
|
|
||
| dsn, err := testutil.ContainerConnectionString(ctx, container, "parseTime=true") | ||
| require.NoError(t, err, "failed to get connection string") | ||
|
|
||
| logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError})) | ||
| require.NoError(t, EnsureSchema(dsn, logger), "failed to ensure schema") | ||
|
|
||
| db, err := sql.Open("mysql", dsn) | ||
| require.NoError(t, err) | ||
| require.NoError(t, db.PingContext(ctx)) | ||
|
|
||
| storage := mysqlstore.New(db) | ||
| serverConfig := &ServerConfig{ | ||
| TernDeployments: TernConfig{ | ||
| "default": {"staging": "tern-staging:9090"}, | ||
| }, | ||
| } | ||
| svc := New(storage, serverConfig, nil, logger) | ||
| defer utils.CloseAndLog(svc) | ||
|
|
||
| // Set up telemetry and routes exactly as serve.go does. | ||
| tel, err := SetupTelemetry(logger) | ||
| require.NoError(t, err) | ||
| t.Cleanup(func() { require.NoError(t, tel.Shutdown(t.Context())) }) | ||
|
|
||
| mux := http.NewServeMux() | ||
| svc.ConfigureRoutes(mux) | ||
| mux.Handle("GET /metrics", tel.MetricsHandler) | ||
| handler := otelhttp.NewHandler(mux, "schemabot") | ||
|
|
||
| ts := httptest.NewServer(handler) | ||
| defer ts.Close() | ||
|
|
||
| // Hit several endpoints to generate HTTP metrics. | ||
| endpoints := []struct { | ||
| method string | ||
| path string | ||
| }{ | ||
| {"GET", "/health"}, | ||
| {"GET", "/api/status"}, | ||
| {"GET", "/api/locks"}, | ||
| {"GET", "/api/settings"}, | ||
| {"GET", "/api/logs"}, | ||
| } | ||
|
|
||
| client := ts.Client() | ||
| for _, ep := range endpoints { | ||
| req, err := http.NewRequestWithContext(ctx, ep.method, ts.URL+ep.path, nil) | ||
| require.NoError(t, err) | ||
| resp, err := client.Do(req) | ||
| require.NoError(t, err) | ||
| resp.Body.Close() | ||
| } | ||
|
|
||
| // Scrape /metrics and verify HTTP server metrics appear. | ||
| metricsReq, err := http.NewRequestWithContext(ctx, "GET", ts.URL+"/metrics", nil) | ||
| require.NoError(t, err) | ||
| resp, err := client.Do(metricsReq) | ||
| require.NoError(t, err) | ||
| defer resp.Body.Close() | ||
|
|
||
| assert.Equal(t, http.StatusOK, resp.StatusCode) | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| require.NoError(t, err) | ||
| metricsText := string(body) | ||
|
|
||
| // otelhttp produces these standard metrics. | ||
| assert.True(t, strings.Contains(metricsText, "http_server_request_duration"), | ||
| "/metrics should contain http_server_request_duration") | ||
| assert.True(t, strings.Contains(metricsText, "http_server_request_body_size"), | ||
| "/metrics should contain http_server_request_body_size") | ||
| assert.True(t, strings.Contains(metricsText, "http_server_response_body_size"), | ||
| "/metrics should contain http_server_response_body_size") | ||
|
|
||
| // The custom plans counter only appears after its first increment, | ||
| // so we don't assert it here — it's tested in TestRecordPlanMetric. | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.