prometheus/web/api/v1/test_helpers.go

160 lines
4.9 KiB
Go
Raw Permalink Normal View History

Add OpenAPI 3.2 specification generation for Prometheus HTTP API (#17825) * Add OpenAPI 3.2 specification generation for Prometheus HTTP API This commit introduces an OpenAPI specification for the Prometheus API. After testing multiple code-generation servers with built-in APIs, this implementation uses an independent spec file outside of the critical path. This spec file is tested with a framework present in this pull request. The specification helps clients know which parameters they can use and is served at /api/v1/openapi.yaml. The spec file will evolve with the Prometheus API and has the same version number. Downstream projects can tune the APIs presented in the spec file with configuration options using the IncludePaths setting for path filtering. In the future, there is room to generate a server from this spec file (e.g. with interfaces), but this is out of scope for this pull request. Architecture: - Core OpenAPI infrastructure (openapi.go): Dynamic spec building, caching, and thread-safe spec generation - Schema definitions (openapi_schemas.go): Complete type definitions for all API request and response types - Path specifications (openapi_paths.go): Endpoint definitions with parameters, request bodies, and response schemas - Examples (openapi_examples.go): Realistic request/response examples - Helper functions (openapi_helpers.go): Reusable builders for common OpenAPI structures Testing: - Comprehensive test suite with golden file validation - Test helpers package for API testing infrastructure - OpenAPI compliance validation utilities The golden file captures the complete specification for snapshot testing. Update with: go test -run TestOpenAPIGolden -update-openapi-spec REVIEWERS: The most important thing to check would be the OpenAPI golden file (web/api/v1/testdata/openapi_golden.yaml). Test scenarios are important as they test the actual OpenAPI spec validity. Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * Add OpenAPI 3.1 support with version selection Add support for both OpenAPI 3.1 and 3.2 specifications with version selection via openapi_version query parameter. Defaults to 3.1 for broader compatibility Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * Enhance OpenAPI examples and add helper functions - Add timestampExamples helper for consistent time formatting - Add exampleMap helper to simplify example creation - Improve example summaries with query details - Add matrix result example for range vector queries Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * web/api: Add AtST method to test helper iterators Implement the AtST() method required by chunkenc.Iterator interface for FakeSeriesIterator and FakeHistogramSeriesIterator test helpers. The method returns 0 as these test helpers don't use start timestamps Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * OpenAPI: Add minimum coverage test Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * OpenAPI: Improve examples handling Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> --------- Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com>
2026-01-29 07:36:13 -05:00
// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v1
import (
"context"
"testing"
"time"
"github.com/prometheus/common/route"
"github.com/prometheus/prometheus/promql/parser"
Add OpenAPI 3.2 specification generation for Prometheus HTTP API (#17825) * Add OpenAPI 3.2 specification generation for Prometheus HTTP API This commit introduces an OpenAPI specification for the Prometheus API. After testing multiple code-generation servers with built-in APIs, this implementation uses an independent spec file outside of the critical path. This spec file is tested with a framework present in this pull request. The specification helps clients know which parameters they can use and is served at /api/v1/openapi.yaml. The spec file will evolve with the Prometheus API and has the same version number. Downstream projects can tune the APIs presented in the spec file with configuration options using the IncludePaths setting for path filtering. In the future, there is room to generate a server from this spec file (e.g. with interfaces), but this is out of scope for this pull request. Architecture: - Core OpenAPI infrastructure (openapi.go): Dynamic spec building, caching, and thread-safe spec generation - Schema definitions (openapi_schemas.go): Complete type definitions for all API request and response types - Path specifications (openapi_paths.go): Endpoint definitions with parameters, request bodies, and response schemas - Examples (openapi_examples.go): Realistic request/response examples - Helper functions (openapi_helpers.go): Reusable builders for common OpenAPI structures Testing: - Comprehensive test suite with golden file validation - Test helpers package for API testing infrastructure - OpenAPI compliance validation utilities The golden file captures the complete specification for snapshot testing. Update with: go test -run TestOpenAPIGolden -update-openapi-spec REVIEWERS: The most important thing to check would be the OpenAPI golden file (web/api/v1/testdata/openapi_golden.yaml). Test scenarios are important as they test the actual OpenAPI spec validity. Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * Add OpenAPI 3.1 support with version selection Add support for both OpenAPI 3.1 and 3.2 specifications with version selection via openapi_version query parameter. Defaults to 3.1 for broader compatibility Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * Enhance OpenAPI examples and add helper functions - Add timestampExamples helper for consistent time formatting - Add exampleMap helper to simplify example creation - Improve example summaries with query details - Add matrix result example for range vector queries Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * web/api: Add AtST method to test helper iterators Implement the AtST() method required by chunkenc.Iterator interface for FakeSeriesIterator and FakeHistogramSeriesIterator test helpers. The method returns 0 as these test helpers don't use start timestamps Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * OpenAPI: Add minimum coverage test Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * OpenAPI: Improve examples handling Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> --------- Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com>
2026-01-29 07:36:13 -05:00
"github.com/prometheus/prometheus/web/api/testhelpers"
)
// newTestAPI creates a new API instance for testing using testhelpers.
func newTestAPI(t *testing.T, cfg testhelpers.APIConfig) *testhelpers.APIWrapper {
t.Helper()
params := testhelpers.PrepareAPI(t, cfg)
// Adapt the testhelpers interfaces to v1 interfaces.
api := NewAPI(
params.QueryEngine,
params.Queryable,
nil, nil, // appendables
Add OpenAPI 3.2 specification generation for Prometheus HTTP API (#17825) * Add OpenAPI 3.2 specification generation for Prometheus HTTP API This commit introduces an OpenAPI specification for the Prometheus API. After testing multiple code-generation servers with built-in APIs, this implementation uses an independent spec file outside of the critical path. This spec file is tested with a framework present in this pull request. The specification helps clients know which parameters they can use and is served at /api/v1/openapi.yaml. The spec file will evolve with the Prometheus API and has the same version number. Downstream projects can tune the APIs presented in the spec file with configuration options using the IncludePaths setting for path filtering. In the future, there is room to generate a server from this spec file (e.g. with interfaces), but this is out of scope for this pull request. Architecture: - Core OpenAPI infrastructure (openapi.go): Dynamic spec building, caching, and thread-safe spec generation - Schema definitions (openapi_schemas.go): Complete type definitions for all API request and response types - Path specifications (openapi_paths.go): Endpoint definitions with parameters, request bodies, and response schemas - Examples (openapi_examples.go): Realistic request/response examples - Helper functions (openapi_helpers.go): Reusable builders for common OpenAPI structures Testing: - Comprehensive test suite with golden file validation - Test helpers package for API testing infrastructure - OpenAPI compliance validation utilities The golden file captures the complete specification for snapshot testing. Update with: go test -run TestOpenAPIGolden -update-openapi-spec REVIEWERS: The most important thing to check would be the OpenAPI golden file (web/api/v1/testdata/openapi_golden.yaml). Test scenarios are important as they test the actual OpenAPI spec validity. Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * Add OpenAPI 3.1 support with version selection Add support for both OpenAPI 3.1 and 3.2 specifications with version selection via openapi_version query parameter. Defaults to 3.1 for broader compatibility Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * Enhance OpenAPI examples and add helper functions - Add timestampExamples helper for consistent time formatting - Add exampleMap helper to simplify example creation - Improve example summaries with query details - Add matrix result example for range vector queries Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * web/api: Add AtST method to test helper iterators Implement the AtST() method required by chunkenc.Iterator interface for FakeSeriesIterator and FakeHistogramSeriesIterator test helpers. The method returns 0 as these test helpers don't use start timestamps Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * OpenAPI: Add minimum coverage test Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * OpenAPI: Improve examples handling Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> --------- Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com>
2026-01-29 07:36:13 -05:00
params.ExemplarQueryable,
func(ctx context.Context) ScrapePoolsRetriever {
return adaptScrapePoolsRetriever(params.ScrapePoolsRetriever(ctx))
},
func(ctx context.Context) TargetRetriever {
return adaptTargetRetriever(params.TargetRetriever(ctx))
},
func(ctx context.Context) AlertmanagerRetriever {
return adaptAlertmanagerRetriever(params.AlertmanagerRetriever(ctx))
},
params.ConfigFunc,
params.FlagsMap,
GlobalURLOptions{},
params.ReadyFunc,
adaptTSDBAdminStats(params.TSDBAdmin),
params.DBDir,
false, // enableAdmin
params.Logger,
func(ctx context.Context) RulesRetriever {
return adaptRulesRetriever(params.RulesRetriever(ctx))
},
0, // remoteReadSampleLimit
0, // remoteReadConcurrencyLimit
0, // remoteReadMaxBytesInFrame
false, // isAgent
nil, // corsOrigin
func() (RuntimeInfo, error) {
info, err := params.RuntimeInfoFunc()
return RuntimeInfo{
StartTime: info.StartTime,
CWD: info.CWD,
Hostname: info.Hostname,
ServerTime: info.ServerTime,
ReloadConfigSuccess: info.ReloadConfigSuccess,
LastConfigTime: info.LastConfigTime,
CorruptionCount: info.CorruptionCount,
GoroutineCount: info.GoroutineCount,
GOMAXPROCS: info.GOMAXPROCS,
GOMEMLIMIT: info.GOMEMLIMIT,
GOGC: info.GOGC,
GODEBUG: info.GODEBUG,
StorageRetention: info.StorageRetention,
}, err
},
&PrometheusVersion{
Version: params.BuildInfo.Version,
Revision: params.BuildInfo.Revision,
Branch: params.BuildInfo.Branch,
BuildUser: params.BuildInfo.BuildUser,
BuildDate: params.BuildInfo.BuildDate,
GoVersion: params.BuildInfo.GoVersion,
},
params.NotificationsGetter,
params.NotificationsSub,
params.Gatherer,
params.Registerer,
nil, // statsRenderer
false, // rwEnabled
nil, // acceptRemoteWriteProtoMsgs
false, // otlpEnabled
false, // otlpDeltaToCumulative
false, // otlpNativeDeltaIngestion
false, // stZeroIngestionEnabled
5*time.Minute, // lookbackDelta
false, // enableTypeAndUnitLabels
false, // appendMetadata
nil, // overrideErrorCode
nil, // featureRegistry
OpenAPIOptions{}, // openAPIOptions
parser.NewParser(parser.Options{}), // promqlParser
Add OpenAPI 3.2 specification generation for Prometheus HTTP API (#17825) * Add OpenAPI 3.2 specification generation for Prometheus HTTP API This commit introduces an OpenAPI specification for the Prometheus API. After testing multiple code-generation servers with built-in APIs, this implementation uses an independent spec file outside of the critical path. This spec file is tested with a framework present in this pull request. The specification helps clients know which parameters they can use and is served at /api/v1/openapi.yaml. The spec file will evolve with the Prometheus API and has the same version number. Downstream projects can tune the APIs presented in the spec file with configuration options using the IncludePaths setting for path filtering. In the future, there is room to generate a server from this spec file (e.g. with interfaces), but this is out of scope for this pull request. Architecture: - Core OpenAPI infrastructure (openapi.go): Dynamic spec building, caching, and thread-safe spec generation - Schema definitions (openapi_schemas.go): Complete type definitions for all API request and response types - Path specifications (openapi_paths.go): Endpoint definitions with parameters, request bodies, and response schemas - Examples (openapi_examples.go): Realistic request/response examples - Helper functions (openapi_helpers.go): Reusable builders for common OpenAPI structures Testing: - Comprehensive test suite with golden file validation - Test helpers package for API testing infrastructure - OpenAPI compliance validation utilities The golden file captures the complete specification for snapshot testing. Update with: go test -run TestOpenAPIGolden -update-openapi-spec REVIEWERS: The most important thing to check would be the OpenAPI golden file (web/api/v1/testdata/openapi_golden.yaml). Test scenarios are important as they test the actual OpenAPI spec validity. Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * Add OpenAPI 3.1 support with version selection Add support for both OpenAPI 3.1 and 3.2 specifications with version selection via openapi_version query parameter. Defaults to 3.1 for broader compatibility Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * Enhance OpenAPI examples and add helper functions - Add timestampExamples helper for consistent time formatting - Add exampleMap helper to simplify example creation - Improve example summaries with query details - Add matrix result example for range vector queries Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * web/api: Add AtST method to test helper iterators Implement the AtST() method required by chunkenc.Iterator interface for FakeSeriesIterator and FakeHistogramSeriesIterator test helpers. The method returns 0 as these test helpers don't use start timestamps Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * OpenAPI: Add minimum coverage test Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> * OpenAPI: Improve examples handling Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com> --------- Signed-off-by: Julien Pivotto <291750+roidelapluie@users.noreply.github.com>
2026-01-29 07:36:13 -05:00
)
// Register routes.
router := route.New()
api.Register(router.WithPrefix("/api/v1"))
return &testhelpers.APIWrapper{
Handler: router,
}
}
// Adapter functions to convert testhelpers interfaces to v1 interfaces.
type rulesRetrieverAdapter struct {
testhelpers.RulesRetriever
}
func adaptRulesRetriever(r testhelpers.RulesRetriever) RulesRetriever {
return &rulesRetrieverAdapter{r}
}
type targetRetrieverAdapter struct {
testhelpers.TargetRetriever
}
func adaptTargetRetriever(t testhelpers.TargetRetriever) TargetRetriever {
return &targetRetrieverAdapter{t}
}
type scrapePoolsRetrieverAdapter struct {
testhelpers.ScrapePoolsRetriever
}
func adaptScrapePoolsRetriever(s testhelpers.ScrapePoolsRetriever) ScrapePoolsRetriever {
return &scrapePoolsRetrieverAdapter{s}
}
type alertmanagerRetrieverAdapter struct {
testhelpers.AlertmanagerRetriever
}
func adaptAlertmanagerRetriever(a testhelpers.AlertmanagerRetriever) AlertmanagerRetriever {
return &alertmanagerRetrieverAdapter{a}
}
type tsdbAdminStatsAdapter struct {
testhelpers.TSDBAdminStats
}
func adaptTSDBAdminStats(t testhelpers.TSDBAdminStats) TSDBAdminStats {
return &tsdbAdminStatsAdapter{t}
}