feat(api): add composite ogen handler for incremental operations

This commit is contained in:
shira committed 2026-10-05 21:20:46 +03:00
1 parent 0f206bfc29
commit b2f6e87bfe
6 files changed
+133 -6

No files matched your search

@@ -18,12 +18,17 @@ const (
readinessPath = "/readyz"
)
// NewRouter mounts the internal operational routes and the generated public API.
// The generated server keeps ogen's default error handler, which answers
// ht.ErrNotImplemented with HTTP 501; operations without a business
// implementation in apiHandler rely on that mapping.
func NewRouter(
health *v1.HealthHandler,
apiHandler apiadapter.Handler,
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
) (http.Handler, error) {
apiServer, err := apiadapter.NewServer(health)
apiServer, err := apiadapter.NewServer(apiHandler)
if err != nil {
return nil, fmt.Errorf("httpadapter.NewRouter - create API server: %w", err)
}
@@ -9,6 +9,7 @@ import (
"testing"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/usecase/health"
@@ -70,11 +71,33 @@ func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) {
}
}
// An operation without a business implementation must answer 501 through the
// router instead of a successful stub or a generic 500. GetHealthz served by
// api.UnimplementedHandler stands in for any such operation, so the check needs
// no extra contract operation.
func TestPublicUnimplementedOperationReturnsNotImplemented(t *testing.T) {
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router := newTestRouterWithAPI(t, healthHandler, api.UnimplementedHandler{})
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
if response.Code != http.StatusNotImplemented {
t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusNotImplemented, response.Body.String())
}
}
func newTestRouter(t *testing.T, checker readinessFunc) http.Handler {
t.Helper()
readiness := health.NewReadiness(checker)
healthHandler := v1.NewHealthHandler(readiness, time.Second)
router, err := NewRouter(healthHandler, metrics.New(), slog.New(slog.DiscardHandler))
healthHandler := newTestHealthHandler(checker)
return newTestRouterWithAPI(t, healthHandler, v1.NewHandler(healthHandler))
}
func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler {
return v1.NewHealthHandler(health.NewReadiness(checker), time.Second)
}
func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler) http.Handler {
t.Helper()
router, err := NewRouter(healthHandler, apiHandler, metrics.New(), slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -0,0 +1,44 @@
package v1
import (
"context"
"lincodex/backend/internal/adapter/primary/http/api"
)
// Handler is the composite implementation of the generated api.Handler.
//
// The embedded api.UnimplementedHandler keeps the backend compiling after the
// contract gains an operation that has no business implementation yet. Such an
// operation returns ht.ErrNotImplemented without side effects. The generated
// server passes that error to its configured ErrorHandler, and the default
// ogenerrors.DefaultErrorHandler maps it to HTTP 501. When the contract defines
// a default error response, the generated server still sends
// ht.ErrNotImplemented to ErrorHandler before calling NewError. The embedded
// NewError, however, returns a zero status code that the generated encoder
// sends as HTTP 200, so the composite must then define NewError explicitly.
// That NewError must answer *ogenerrors.SecurityError with 401 or 403, which
// the generated server passes to it directly, and answer every other error
// with 500 and a sanitized message, never err.Error() of an internal error.
// Errors of the generated status-code error type (*<Schema>StatusCode) are
// encoded before NewError is called, so it does not need to handle them.
//
// Each implemented operation gets an explicit method here that delegates to
// the handler owning it. Each implemented operation also gets a router test
// through v1.NewHandler that asserts a non-501 response, because renaming an
// operationId would otherwise silently fall back to the embedded 501 method.
type Handler struct {
api.UnimplementedHandler
health *HealthHandler
}
var _ api.Handler = (*Handler)(nil)
func NewHandler(health *HealthHandler) *Handler {
return &Handler{health: health}
}
func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) {
return handler.health.GetHealthz(ctx)
}
@@ -0,0 +1,51 @@
package v1
import (
"context"
"errors"
"net/http"
"reflect"
"testing"
)
// Once the contract defines a default error response, ogen adds NewError to
// api.Handler and api.UnimplementedHandler supplies one that returns a zero
// status code, which the generated encoder sends as HTTP 200. A handler error
// would then look like a success, so the composite must define its own NewError.
func TestHandlerNewErrorDoesNotReportSuccess(t *testing.T) {
newError := reflect.ValueOf(NewHandler(nil)).MethodByName("NewError")
if !newError.IsValid() {
t.Skip("the contract has no default error response, so the generated server has no NewError")
}
contextType := reflect.TypeFor[context.Context]()
errorType := reflect.TypeFor[error]()
signature := newError.Type()
if signature.NumIn() != 2 || signature.In(0) != contextType || signature.In(1) != errorType || signature.NumOut() != 1 {
t.Fatalf("NewError has signature %s, want func(context.Context, error) <error response>", signature)
}
results := newError.Call([]reflect.Value{
reflect.ValueOf(context.Background()),
reflect.ValueOf(errors.New("handler failure")),
})
if len(results) != 1 {
t.Fatalf("NewError() returned %d values, want 1", len(results))
}
response := results[0]
if response.Kind() == reflect.Pointer {
if response.IsNil() {
t.Fatal("NewError() returned nil")
}
response = response.Elem()
}
if response.Kind() != reflect.Struct {
t.Fatalf("NewError() result kind = %s, want struct", response.Kind())
}
statusCode := response.FieldByName("StatusCode")
if !statusCode.IsValid() || !statusCode.CanInt() {
t.Fatalf("NewError() result %s has no integer StatusCode field", response.Type())
}
if code := statusCode.Int(); code < http.StatusBadRequest {
t.Fatalf("v1.Handler must define NewError with an error status: NewError yields status %d; the promoted api.UnimplementedHandler.NewError yields 0, which ogen encodes as HTTP 200", code)
}
}