Skip to content

feat(server): register v3 api router - #3683

Merged
gergely-kurucz-konghq merged 5 commits into
mainfrom
feat/v3-api
Dec 11, 2025
Merged

gergely-kurucz-konghq merged 5 commits into
mainfrom
feat/v3-api

Conversation

@tothandras

@tothandras tothandras commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added support for resource labels and public labels
    • Added pagination metadata structures
    • Added support for multiple content types in event ingestion (JSON, CloudEvents, CloudEvents Batch formats)
    • Improved error handling with detailed validation messages
  • Breaking Changes

    • Events ingestion endpoint moved from /metering/events to /openmeter/events
    • Event ingestion response status code changed to 202 Accepted

✏️ Tip: You can customize this high-level summary in your review settings.

@tothandras
tothandras requested a review from a team as a code owner December 11, 2025 00:40
@tothandras tothandras added the release-note/ignore Ignore this change when generating release notes label Dec 11, 2025
@coderabbitai

coderabbitai Bot commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR refactors the metering/events API endpoints and introduces a comprehensive v3 OpenAPI-integrated server with error handling and validation middleware. Changes include renaming MeteringEvents operations to Events (moving from /metering/events to /openmeter/events, status 204→202), restructuring TypeSpec models (removing timestamp-specific types, adding generic request/response wrappers), expanding shared constants, and implementing a Go error framework with OpenAPI validation hooks and render utilities.

Changes

Cohort / File(s) Summary
OpenAPI Schema Definitions
api/spec/common/definitions/konnect_properties.yaml
Added Labels and PublicLabels schemas with key pattern validation (1-63 chars, no reserved prefixes), maxProperties 50, and descriptive metadata.
TypeSpec Pagination & Properties
api/spec/src/v3/common/pagination.tsp, api/spec/src/v3/common/properties.tsp
Added PaginatedMeta and PageMeta models for pagination metadata. Removed CreatedAt, UpdatedAt, DeletedAt models; added PublicLabels model referencing konnect_properties schema.
TypeSpec Shared Models
api/spec/src/v3/shared/consts.tsp, api/spec/src/v3/shared/index.tsp, api/spec/src/v3/shared/properties.tsp, api/spec/src/v3/shared/request.tsp, api/spec/src/v3/shared/responses.tsp, api/spec/src/v3/shared/pagination.tsp, api/spec/src/v3/shared/rest.tsp, api/spec/src/v3/shared/resource.tsp
Reorganized shared constants (renamed MeteringEventsTag→EventsTag, added EventsDescription, CustomersTag/Description, etc.); added OpenMeterTitle and PrivateExtension constants. Introduced generic request models (CreateRequest, UpsertRequest, UpdateRequest) and response models (GetResponse, CreateResponse, UpdateResponse, DeleteResponse, CursorPaginatedResponse, PagePaginatedResponse). Updated Resource model to use DateTime instead of specific timestamp types, removed public_labels field. Removed CursorPaginatedResponse from shared pagination. Removed imports for pagination/rest in index.tsp. Added ULIDOrResourceKey union and ExternalResourceKey scalar.
Events Endpoint Refactoring
api/spec/src/v3/events/event.tsp, api/spec/src/v3/events/operations.tsp, api/spec/src/v3/konnect.tsp, api/spec/src/v3/openmeter.tsp
Renamed MeteringEventsOperations→EventsOperations; changed IngestEventsResponse status code 204→202. Removed TypeSpec.OpenAPI using directive. Updated route from /metering/events to /openmeter/events in both konnect and openmeter namespaces. Replaced MeteringEventsTag metadata with EventsTag and added CustomersTag, MetersTag metadata. Updated route, tag, and friendlyName references accordingly.
Go Error Handling Framework
api/v3/apierrors/errors.go, api/v3/apierrors/errors_ctors.go, api/v3/apierrors/encoder.go
Introduced BaseAPIError with fields for type, status, title, instance, detail, invalid parameters, and context. Added InvalidParameters, InvalidParameterSource (with path/query/body/header origins), and InvalidParameter types. Implements Error(), Unwrap(), Context(), HandleAPIError() methods. Defined 30+ error constants (InternalType, NotFoundType, BadRequestType, etc.) and constructors (NewInternalError, NewNotFoundError, NewBadRequestError, etc.). Includes MakeSentenceCase utility and instance ID derivation. Added GenericErrorEncoder for HTTP response rendering.
OpenAPI Middleware & Validation
api/v3/oasmiddleware/decoder.go, api/v3/oasmiddleware/error.go, api/v3/oasmiddleware/hook.go, api/v3/oasmiddleware/response.go
Introduced JsonBodyDecoder for kin-openapi request body parsing. Added OAS error translation (ToAipError) mapping OpenAPI validation errors to AIP-compliant InvalidParameters. Implemented OasRouteNotFoundErrorHook and OasValidationErrorHook for centralized error handling, with SanitizeSensitiveFieldValues to mask sensitive fields. Created ResponseWriterWrapper to capture response body and status code for middleware inspection.
Response Rendering
api/v3/render/render.go
Added RenderJSON and RenderYAML generic functions with Option builder pattern (WithStatus, WithHeader, WithContentType). Handles default 200 status, content-type negotiation, and marshalling errors. Exposed ContentTypeKey, ContentTypeJSONValue, ContentTypeYAMLValue constants.
v3 Server Implementation
api/v3/server/server.go, api/v3/server/routes.go, api/v3/handlers/events/handler.go, api/v3/handlers/events/ingest.go
Introduced v3 Server with Config validation, OpenAPI spec loading, namespace resolution, and route registration. Wired error handling via OAS validation hooks. Created Handler interface and New constructor for events handler. Implemented IngestEvents handler supporting multiple content types (application/json, application/cloudevents+json, application/cloudevents-batch+json), returning HTTP 202. Added IngestMeteringEvents route handler.
Server Integration
api/v3/api.gen.go, openmeter/server/server.go
Updated generated API code to reflect new /openmeter/events route. Integrated v3 server into main router via grouped middleware registration, supporting namespace decoding and BaseURL configuration. Applied middlewares within v3 route context.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Error handling framework completeness: Review BaseAPIError structure, error constructors, and edge cases (invalid parameter mappings, sensitive field sanitization).
  • OpenAPI middleware integration: Verify hook ordering, error translation logic (ToAipError), validation error propagation, and sensitive field masking correctness.
  • Handler wiring: Confirm namespace resolution, content-type parsing, and request/response type aliases align with TypeSpec operations.
  • Server setup: Validate Config validation logic, swagger spec loading, and route registration order.
  • Type reshaping: Ensure DateTime field changes don't break existing consumers; verify request/response model generic constraints.

Possibly related PRs

Suggested labels

area/api, release-note/feature

Suggested reviewers

  • GAlexIHU

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.78% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: registering a v3 API router with the server, which is the core objective reflected across multiple files.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/v3-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 19

🧹 Nitpick comments (24)
api/v3/request/body.go (1)

10-24: Consider enhancing error information and safety.

The function works but could be more robust:

  1. Missing field context: The InvalidParameter doesn't specify which field failed, making debugging harder for API consumers. Consider adding the field name if the decoder error provides it.

  2. Optional safety improvements (defer if needed):

    • Add a body size limit to prevent memory exhaustion from large payloads
    • Consider decoder.DisallowUnknownFields() to catch typos in requests

The current implementation is functional for basic use cases.

Example enhancement for error detail:

 func ParseBody(r *http.Request, payload any) *apierrors.BaseAPIError {
+	// Limit body size to prevent abuse
+	r.Body = http.MaxBytesReader(nil, r.Body, 10<<20) // 10MB limit
+	
 	decoder := json.NewDecoder(r.Body)
+	decoder.DisallowUnknownFields()
+	
 	if err := decoder.Decode(&payload); err != nil {
 		return apierrors.NewBadRequestError(r.Context(), err,
 			apierrors.InvalidParameters{
 				apierrors.InvalidParameter{
-					Reason: "unable to parse body",
+					Reason: fmt.Sprintf("unable to parse body: %v", err),
 					Source: apierrors.InvalidParamSourceBody,
 				},
 			},
 		)
 	}
api/spec/src/v3/shared/properties.tsp (1)

39-47: LGTM on the permissive external key type.

The ExternalResourceKey appropriately uses loose constraints since external systems can use various ID formats. The 256-char limit is reasonable.

Optional: Consider adding more diverse examples to showcase the flexibility:

@example("019ae40f-4258-7f15-9491-842f42a7d6ac")
@example("ext_cust_12345")
@example("customer-abc-def")
api/v3/handlers/convert.go (1)

1-1: Consider using the standard goverter directive syntax.

While your current approach //go:generate go tool github.com/jmattheis/goverter/cmd/goverter gen ./ does work (I see it's successfully generating code across the codebase), the official goverter docs recommend the simpler syntax:

//go:generate goverter gen ./

This assumes you have goverter installed. If you prefer the direct approach without a separate install, the documented fallback is:

//go:generate go run github.com/jmattheis/goverter/cmd/goverter@v<version> gen ./

The go tool pattern isn't officially documented for goverter, so switching to one of the standard approaches would make the codebase clearer and more maintainable.

openmeter/server/server.go (1)

96-108: Consider extracting duplicated middleware chain.

The same middleware stack (RealIP, RequestID, context attributes, request logger, Recoverer) appears twice - once for v3 (lines 96-108) and again for the main group (lines 126-137). This duplication could lead to maintenance drift.

You could extract a shared middleware factory:

func defaultMiddlewareStack(logger slog.Handler) []func(http.Handler) http.Handler {
    return []func(http.Handler) http.Handler{
        middleware.RealIP,
        middleware.RequestID,
        func(h http.Handler) http.Handler {
            return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                ctx := r.Context()
                ctx = contextx.WithAttrs(ctx, server.GetRequestAttributes(r))
                h.ServeHTTP(w, r.WithContext(ctx))
            })
        },
        server.NewRequestLoggerMiddleware(logger),
        middleware.Recoverer,
    }
}

Also applies to: 126-137

api/v3/render/render.go (1)

10-15: Duplicate ContentTypeKey constant.

Per the relevant code snippets, ContentTypeKey is also defined in api/v3/apierrors/errors_ctors.go:13. Consider moving shared constants to a common location to avoid duplication.

api/v3/apierrors/errors.go (2)

83-95: ToInvalid returns zero value for unknown input.

When an unknown string is passed, the function returns InvalidParameterSource(0), which isn't a defined constant. This could lead to confusing behavior when marshaling (empty string) or in switch statements. Consider returning an error or a dedicated "unknown" constant.


180-185: Ignored render error.

The error from render.RenderJSON is discarded. If rendering fails, the response might be incomplete. Consider logging this failure at minimum for debugging purposes.

-func (bae *BaseAPIError) HandleAPIError(
-	w http.ResponseWriter,
-	r *http.Request,
-) {
-	_ = render.RenderJSON(w, bae, render.WithContentType(ContentTypeProblemValue), render.WithStatus(bae.Status))
+func (bae *BaseAPIError) HandleAPIError(w http.ResponseWriter, r *http.Request) {
+	if err := render.RenderJSON(w, bae, render.WithContentType(ContentTypeProblemValue), render.WithStatus(bae.Status)); err != nil {
+		// Log the render failure - at this point we can't do much else
+		slog.ErrorContext(r.Context(), "failed to render API error", "error", err)
+	}
 }
api/v3/server/handlers.go (1)

7-9: Thin wrapper is good; consider guarding against a nil handler

The delegation to s.eventsHandler.IngestEvents().ServeHTTP(w, r) keeps this nicely minimal. Just make sure eventsHandler is always non‑nil (e.g., enforced in Server construction), or add a defensive nil check here to avoid a panic if wiring ever regresses.

api/v3/oasmiddleware/error.go (1)

21-77: Error mapping is solid; a few tweaks could make it more robust and readable

This whole chain (ToAipError → aipMapper → collectFromSchemaError / unwrapOriginError / invalidParamFromSchemaError) looks thoughtfully put together and should produce nice AIP‑style invalid parameter payloads. A couple of follow‑ups you might consider:

  • The type switch in aipMapper silently drops any errors that aren’t *openapi3.SchemaError or *openapi3filter.RequestError. If kin‑openapi ever adds new validation error types, they’ll just disappear. A default case that falls back to a generic InvalidParameter{Reason: err.Error()} would make this future‑proof without changing current behavior.
  • In the RequestError branch, the reuse and shadowing of err (if err, ok := err.Err.(openapi3.MultiError) / if err, ok := err.Err.(*openapi3.SchemaError)) is a bit hard to follow. Renaming the inner vars (me, schemaErr) would reduce cognitive load without functional change.
  • For oneOf handling, collectFromSchemaError currently drops any parent context (parameter name, source) because it calls invalidParamFromSchemaError with parent == nil. If you ever need parameter‑scoped field / source in those nested errors, you may want to thread the parent InvalidParameter through that path too.

Also applies to: 82-120, 122-143

api/v3/request/request_test.go (1)

15-281: Great coverage for GetAttributes; a couple of optional extensions

This table‑driven suite does a nice job exercising:

  • Default and explicit page‑based pagination (including max size overflow).
  • Cursor pagination (size, before/after, invalid ranges).
  • Sorting (default asc, explicit desc, invalid order).
  • A bunch of filter operators and combined pagination/sort/filter cases.
  • Ignoring unrelated query params while still parsing pagination/sort.

If you ever want to harden this further, two optional ideas:

  • Add at least one case that hits ocontains (since it has special handling in Filter).
  • Cover a negative path where multiple filter ops are set for the same field and you expect ErrFilterMultipleFilterOperations to surface via GetAttributes.

But as‑is, this is already very solid.

api/v3/oasmiddleware/response.go (2)

11-15: Consider storing the http.ResponseWriter directly instead of a pointer to interface.

Storing *http.ResponseWriter (pointer to interface) is unusual in Go. Since interfaces already contain a pointer to their underlying data, wrapping it in another pointer adds indirection without benefit. This could lead to subtle bugs if the interface value is reassigned elsewhere.

Also, using value receivers on a struct that relies on pointer fields for shared state works but is a bit unusual—pointer receivers would make the intent clearer.

 type ResponseWriterWrapper struct {
-	w          *http.ResponseWriter
+	w          http.ResponseWriter
 	body       *bytes.Buffer
 	statusCode *int
 }

Then update the methods to use rww.w directly instead of (*rww.w).


37-41: Comment is incorrect—it says "Header()" but describes the Write function.

Quick copy-paste slip here. Also, while bytes.Buffer.Write never returns an error in practice, you might want to be defensive and check it anyway.

-// Write function overwrites the http.ResponseWriter Header() function
+// Write function overwrites the http.ResponseWriter Write() function
 func (rww ResponseWriterWrapper) Write(buf []byte) (int, error) {
-	rww.body.Write(buf)
+	_, _ = rww.body.Write(buf) // bytes.Buffer.Write never errors, but explicitly ignore for clarity
 	return (*rww.w).Write(buf)
 }
api/v3/oasmiddleware/hook.go (1)

78-88: Heads up: this mutates the input error in place.

Lines 79 and 85 modify the error objects directly. This is generally fine since these errors are used for response rendering, but be aware that any other code holding a reference to these errors will see the sanitized values. If that's intentional, consider adding a brief comment noting the mutation.

api/v3/request/query/query_test.go (2)

56-66: Minor: inconsistent error assertion style.

You're using require.Nil(t, err) here but require.NoError(t, err) in other tests (e.g., line 274). Both work, but picking one style for the file would be a bit cleaner.


226-232: Consider asserting the actual value, not just the length.

The comment says it should have "one key 'param' with last value", but the test only checks require.Len(t, result2, 1). Adding an assertion for the actual key and value would make the test more robust.

 	result2, err := Parse(ctx, longQuery, &ParseOptions{
 		ParameterLimit:       100,
 		ThrowOnLimitExceeded: false,
 	})
 	require.Nil(t, err)
-	require.Len(t, result2, 1) // Should only have one key "param" with last value
+	require.Len(t, result2, 1)
+	require.Contains(t, result2, "param") // verify the key exists
api/v3/request/pagination.go (2)

22-27: Error naming could be more generic.

The ErrCursorPaginationSizeInvalid error is used for all pagination kinds (line 42-44), not just cursor pagination. Consider renaming to ErrPaginationSizeInvalid for clarity, since the Size validation applies regardless of pagination kind.

 var (
-	ErrCursorPaginationSizeInvalid   = errors.New("size must be greater than 0")
+	ErrPaginationSizeInvalid         = errors.New("size must be greater than 0")
 	ErrCursorPaginationRange         = errors.New("range pagination not supported, both before and after cursor were defined")
 	ErrCursorPaginationAfterInvalid  = errors.New("after cursor is invalid")
 	ErrCursorPaginationBeforeInvalid = errors.New("before cursor is invalid")
 )

29-39: Consider adding validation for offset pagination.

The Number field for offset pagination has no validation. If someone passes a negative page number, it would go through unchecked. Depending on your use case, you might want to validate Number >= 0 (or >= 1 if 1-indexed) when using page-based pagination.

 func (p *Pagination) Validate() error {
 	if p.Size < 1 {
 		return ErrCursorPaginationSizeInvalid
 	}

+	if p.kind == paginationKindPage {
+		if p.Number < 0 {
+			return errors.New("page number must be non-negative")
+		}
+	}
+
 	if p.kind == paginationKindCursor {
api/v3/request/request.go (1)

57-66: Minor naming nit: redundant "Default" suffix.

WithDefaultPageSizeDefault has "Default" twice. Consider renaming to WithDefaultPageSize for cleaner API.

-// WithDefaultPageSizeDefault sets the  request parser default page size.
+// WithDefaultPageSize sets the request parser default page size.
 // This value is used when the client is not setting the page[size] querystring
 // or when the page[size] attribute is not valid.
 //
 // Default value is 20
-func WithDefaultPageSizeDefault(value int) AttributesOption {
+func WithDefaultPageSize(value int) AttributesOption {
 	return func(c *config) {
 		c.defaultPageSize = value
 	}
 }
api/v3/handlers/events.go (1)

69-84: Silent error swallowing when parsing events.

When AsEvent() fails and AsIngestEventsBody1() also fails, the errors are silently ignored and only a generic "no events found" error is returned. This makes debugging harder for API consumers. Consider preserving the parse errors.

 			// Try to parse as a single event
 			e, err := apiRequest.AsEvent()
 			if err == nil {
 				req.Events = []event.Event{e}
 			} else {
+				singleEventErr := err
 				// Try to parse as a batch of events
 				e, err := apiRequest.AsIngestEventsBody1()
 				if err == nil {
 					req.Events = e
+				} else {
+					// Both parsing attempts failed
+					return req, apierrors.NewBadRequestError(ctx, 
+						fmt.Errorf("failed to parse events: single=%v, batch=%v", singleEventErr, err), nil)
 				}
 			}
-
-			// If we still don't have any events, return an error
-			if len(req.Events) == 0 {
-				return req, apierrors.NewBadRequestError(ctx, errors.New("no events found"), nil)
-			}
api/v3/server/server.go (1)

121-128: Consider logging render errors.

The render errors are silently discarded. While unlikely to fail, logging these could help with debugging if something goes wrong with OpenAPI spec serialization.

 		// Serve the OpenAPI spec
 		r.Get("/openapi.json", func(w http.ResponseWriter, r *http.Request) {
-			_ = render.RenderJSON(w, s.swagger)
+			if err := render.RenderJSON(w, s.swagger); err != nil {
+				slog.Error("failed to render OpenAPI JSON", "error", err)
+			}
 		})

 		r.Get("/openapi.yaml", func(w http.ResponseWriter, r *http.Request) {
-			_ = render.RenderYAML(w, s.swagger)
+			if err := render.RenderYAML(w, s.swagger); err != nil {
+				slog.Error("failed to render OpenAPI YAML", "error", err)
+			}
 		})
api/v3/request/query/query.go (4)

244-310: Options merging doesn't allow explicit zero values.

The current merging logic uses zero-value checks, which means a user can't explicitly set Depth: 0 or ArrayLimit: 0 - they'll be ignored. Same goes for booleans if defaults ever change to true.

A more robust pattern would be to use pointer fields in the options struct or a functional options pattern.

For example, with pointer fields:

type ParseOptions struct {
    Depth *int
    // ...
}

// Then in merge:
if custom.Depth != nil {
    options.Depth = *custom.Depth
}

1015-1040: Zero-value checks can cause unexpected behavior.

The type switch at lines 1015-1040 returns empty string for "falsy" values (0, false, empty string). This might be surprising - if someone explicitly wants to encode key=0 or key=false, they can't. Worth documenting this behavior or reconsidering if it's intentional.


1-17: Large file - consider splitting in the future.

At ~1900 lines, this file is quite hefty. It's cohesive around query string handling, but you might consider splitting into separate files (e.g., parse.go, stringify.go, marshal.go) for maintainability down the road. Not blocking for this PR though!


1068-1099: stringify only handles map[string]interface{} and []interface{}.

Direct calls to Stringify with concrete types like []string or map[string]string will silently produce no output since they don't match the type switch cases. The Marshal function handles this by converting first, but Stringify alone might surprise users.

Consider adding a fallback that uses reflection, or document that Stringify expects the generic interface types.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 179c8d5 and 0b0698f.

⛔ Files ignored due to path filters (1)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
📒 Files selected for processing (38)
  • api/spec/common/definitions/konnect_properties.yaml (1 hunks)
  • api/spec/src/v3/common/pagination.tsp (1 hunks)
  • api/spec/src/v3/common/properties.tsp (1 hunks)
  • api/spec/src/v3/events/event.tsp (0 hunks)
  • api/spec/src/v3/events/operations.tsp (1 hunks)
  • api/spec/src/v3/konnect.tsp (1 hunks)
  • api/spec/src/v3/openmeter.tsp (2 hunks)
  • api/spec/src/v3/shared/consts.tsp (1 hunks)
  • api/spec/src/v3/shared/index.tsp (1 hunks)
  • api/spec/src/v3/shared/pagination.tsp (0 hunks)
  • api/spec/src/v3/shared/properties.tsp (1 hunks)
  • api/spec/src/v3/shared/request.tsp (1 hunks)
  • api/spec/src/v3/shared/resource.tsp (1 hunks)
  • api/spec/src/v3/shared/responses.tsp (1 hunks)
  • api/spec/src/v3/shared/rest.tsp (0 hunks)
  • api/v3/api.gen.go (4 hunks)
  • api/v3/apierrors/errors.go (1 hunks)
  • api/v3/apierrors/errors_ctors.go (1 hunks)
  • api/v3/apierrors/invalidparameterrules/rules.go (1 hunks)
  • api/v3/handlers/convert.go (1 hunks)
  • api/v3/handlers/events.go (1 hunks)
  • api/v3/oasmiddleware/decoder.go (1 hunks)
  • api/v3/oasmiddleware/error.go (1 hunks)
  • api/v3/oasmiddleware/hook.go (1 hunks)
  • api/v3/oasmiddleware/response.go (1 hunks)
  • api/v3/render/render.go (1 hunks)
  • api/v3/request/body.go (1 hunks)
  • api/v3/request/filter.go (1 hunks)
  • api/v3/request/pagination.go (1 hunks)
  • api/v3/request/query/query.go (1 hunks)
  • api/v3/request/query/query_test.go (1 hunks)
  • api/v3/request/request.go (1 hunks)
  • api/v3/request/request_test.go (1 hunks)
  • api/v3/request/sort.go (1 hunks)
  • api/v3/response/pagination.go (1 hunks)
  • api/v3/server/handlers.go (1 hunks)
  • api/v3/server/server.go (1 hunks)
  • openmeter/server/server.go (2 hunks)
💤 Files with no reviewable changes (3)
  • api/spec/src/v3/shared/pagination.tsp
  • api/spec/src/v3/shared/rest.tsp
  • api/spec/src/v3/events/event.tsp
🧰 Additional context used
📓 Path-based instructions (3)
**/*.tsp

⚙️ CodeRabbit configuration file

**/*.tsp: Review the TypeSpec code for conformity with TypeSpec best practices. When recommending changes also consider the fact that multiple codegeneration toolchains depend on the TypeSpec code, each of which have their idiosyncrasies and bugs.

The declared API should be accurate, in parity with the actual implementation, and easy to understand for the user.

Files:

  • api/spec/src/v3/common/pagination.tsp
  • api/spec/src/v3/common/properties.tsp
  • api/spec/src/v3/shared/properties.tsp
  • api/spec/src/v3/events/operations.tsp
  • api/spec/src/v3/shared/request.tsp
  • api/spec/src/v3/shared/responses.tsp
  • api/spec/src/v3/shared/index.tsp
  • api/spec/src/v3/konnect.tsp
  • api/spec/src/v3/shared/consts.tsp
  • api/spec/src/v3/shared/resource.tsp
  • api/spec/src/v3/openmeter.tsp
**/*.go

⚙️ CodeRabbit configuration file

**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

Files:

  • api/v3/server/handlers.go
  • api/v3/request/filter.go
  • api/v3/api.gen.go
  • api/v3/oasmiddleware/error.go
  • api/v3/request/sort.go
  • api/v3/oasmiddleware/hook.go
  • api/v3/request/body.go
  • api/v3/handlers/convert.go
  • api/v3/oasmiddleware/response.go
  • api/v3/request/request.go
  • api/v3/oasmiddleware/decoder.go
  • api/v3/request/request_test.go
  • api/v3/request/query/query_test.go
  • openmeter/server/server.go
  • api/v3/apierrors/errors.go
  • api/v3/handlers/events.go
  • api/v3/render/render.go
  • api/v3/response/pagination.go
  • api/v3/server/server.go
  • api/v3/apierrors/invalidparameterrules/rules.go
  • api/v3/request/query/query.go
  • api/v3/request/pagination.go
  • api/v3/apierrors/errors_ctors.go
**/*_test.go

⚙️ CodeRabbit configuration file

**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.
When appropriate, recommend e2e tests for critical changes.

Files:

  • api/v3/request/request_test.go
  • api/v3/request/query/query_test.go
🧠 Learnings (5)
📚 Learning: 2025-11-07T11:28:40.430Z
Learnt from: chrisgacsal
Repo: openmeterio/openmeter PR: 3581
File: openmeter/notification/webhook/svix/webhook.go:253-257
Timestamp: 2025-11-07T11:28:40.430Z
Learning: In the openmeter notification system (specifically in openmeter/notification/webhook/svix/webhook.go), event type filtering for webhooks is not allowed or supported. Only channel-based filtering is used.

Applied to files:

  • api/v3/api.gen.go
📚 Learning: 2025-03-25T09:13:03.300Z
Learnt from: chrisgacsal
Repo: openmeterio/openmeter PR: 2522
File: api/spec/src/productcatalog/routes.tsp:163-314
Timestamp: 2025-03-25T09:13:03.300Z
Learning: ULIDOrKey is defined in api/spec/src/types.tsp as a scalar type with a pattern that validates against both ULID and Key formats, not as a type alias like PlanIdOrKey.

Applied to files:

  • api/spec/src/v3/shared/properties.tsp
📚 Learning: 2025-11-25T15:10:24.409Z
Learnt from: CR
Repo: openmeterio/openmeter PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T15:10:24.409Z
Learning: Generate Go code via `make generate` to produce database access code from ent schema and dependency injection wire code

Applied to files:

  • api/v3/handlers/convert.go
📚 Learning: 2025-11-25T15:10:24.409Z
Learnt from: CR
Repo: openmeterio/openmeter PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T15:10:24.409Z
Learning: Never manually edit generated directories including `api/client` (generated from TypeSpec), `api/openapi.yaml`, `**/ent/db` (generated from ent schema), `**/wire_gen.go` (generated from wire.go), and `tools/migrate/migrations` (generated migrations)

Applied to files:

  • api/v3/handlers/convert.go
📚 Learning: 2025-11-25T15:10:24.409Z
Learnt from: CR
Repo: openmeterio/openmeter PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T15:10:24.409Z
Learning: Generate API clients and OpenAPI spec via `make gen-api` from TypeSpec definitions

Applied to files:

  • api/spec/src/v3/openmeter.tsp
🧬 Code graph analysis (14)
api/v3/server/handlers.go (2)
api/v3/server/server.go (1)
  • Server (58-65)
openmeter/server/server.go (1)
  • Server (27-29)
api/v3/request/filter.go (1)
pkg/models/validator.go (1)
  • Validate (16-26)
api/v3/request/sort.go (1)
pkg/sortx/order.go (1)
  • Order (3-3)
api/v3/oasmiddleware/hook.go (3)
api/v3/apierrors/errors_ctors.go (2)
  • NewNotFoundError (140-160)
  • NewBadRequestError (193-204)
api/v3/oasmiddleware/error.go (1)
  • ToAipError (21-23)
api/v3/apierrors/errors.go (1)
  • InvalidParamSourcePath (63-63)
api/v3/request/body.go (2)
api/v3/apierrors/errors.go (4)
  • BaseAPIError (18-55)
  • InvalidParameters (58-58)
  • InvalidParameter (111-138)
  • InvalidParamSourceBody (65-65)
api/v3/apierrors/errors_ctors.go (1)
  • NewBadRequestError (193-204)
api/v3/request/request.go (5)
api/v3/request/sort.go (4)
  • SortBy (32-35)
  • ErrSortFieldRequired (19-19)
  • ErrSortOrderInvalid (20-20)
  • ErrSortByInvalid (18-18)
api/v3/request/query/query.go (2)
  • ParseOptions (22-99)
  • Unmarshal (1549-1575)
api/v3/request/pagination.go (7)
  • DefaultPaginationMaxSize (18-18)
  • DefaultPaginationSize (17-17)
  • Pagination (29-39)
  • ErrCursorPaginationSizeInvalid (23-23)
  • ErrCursorPaginationRange (24-24)
  • ErrCursorPaginationAfterInvalid (25-25)
  • ErrCursorPaginationBeforeInvalid (26-26)
api/v3/request/filter.go (1)
  • Filter (11-32)
api/v3/apierrors/errors_ctors.go (1)
  • NewBadRequestError (193-204)
api/v3/request/request_test.go (5)
pkg/pagination/v2/cursor.go (1)
  • NewCursor (22-27)
api/v3/request/request.go (4)
  • AttributesOption (37-37)
  • QueryAttributes (31-35)
  • WithPagePagination (51-55)
  • WithCursorPagination (43-47)
api/v3/request/pagination.go (2)
  • Pagination (29-39)
  • DefaultPaginationSize (17-17)
api/v3/request/sort.go (3)
  • SortBy (32-35)
  • SortOrderAsc (13-13)
  • SortOrderDesc (14-14)
api/v3/request/filter.go (1)
  • Filter (11-32)
api/v3/request/query/query_test.go (1)
api/v3/request/query/query.go (10)
  • Parse (242-394)
  • ParseOptions (22-99)
  • Stringify (921-1053)
  • StringifyOptions (710-787)
  • ParseToStruct (1102-1111)
  • StructToQueryString (1404-1411)
  • MapToStruct (1114-1130)
  • StructToMap (1414-1480)
  • Unmarshal (1549-1575)
  • Marshal (1649-1660)
openmeter/server/server.go (5)
api/v3/server/server.go (2)
  • NewServer (70-105)
  • Config (26-34)
openmeter/server/router/router.go (2)
  • Config (89-121)
  • Router (220-247)
api/api.gen.go (3)
  • Handler (20152-20154)
  • HandlerWithOptions (20178-20656)
  • ChiServerOptions (20156-20161)
pkg/contextx/attr.go (1)
  • WithAttrs (22-33)
pkg/models/problem.go (1)
  • NewStatusProblem (104-137)
api/v3/render/render.go (1)
api/v3/apierrors/errors_ctors.go (1)
  • ContentTypeKey (14-14)
api/v3/server/server.go (5)
pkg/framework/transport/httptransport/handler.go (1)
  • ErrorHandler (73-75)
api/v3/handlers/events.go (2)
  • EventsHandler (18-20)
  • NewEventsHandler (28-38)
openmeter/notification/webhook/svix/svix.go (1)
  • Error (28-28)
pkg/framework/transport/httptransport/options.go (1)
  • WithErrorHandler (29-33)
api/v3/oasmiddleware/hook.go (1)
  • OasValidationErrorHook (31-66)
api/v3/request/query/query.go (3)
api/v3/apierrors/errors.go (4)
  • BaseAPIError (18-55)
  • InvalidParameters (58-58)
  • InvalidParamSourceQuery (64-64)
  • InvalidParameter (111-138)
api/v3/apierrors/errors_ctors.go (1)
  • NewBadRequestError (193-204)
api/v3/apierrors/invalidparameterrules/rules.go (7)
  • UnknownProperty (29-29)
  • IsBoolean (21-21)
  • IsInteger (23-23)
  • IsNumber (25-25)
  • IsObject (26-26)
  • IsArray (20-20)
  • IsString (27-27)
api/v3/request/pagination.go (2)
pkg/pagination/v2/cursor.go (1)
  • Cursor (13-16)
pkg/models/validator.go (1)
  • Validate (16-26)
api/v3/apierrors/errors_ctors.go (1)
api/v3/apierrors/errors.go (2)
  • BaseAPIError (18-55)
  • InvalidParameters (58-58)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Build
  • GitHub Check: Lint
  • GitHub Check: Code Generators
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Repository Scan
  • GitHub Check: Analyze (go)
🔇 Additional comments (45)
api/spec/src/v3/events/operations.tsp (2)

19-22: Nice improvement to semantic accuracy!

The status code change from 204 to 202 correctly signals async processing, which aligns perfectly with the doc comment about events "being processed asynchronously." This is the right HTTP status for fire-and-forget event ingestion.

Note: This is a breaking change for clients expecting 204, so ensure it's documented in release notes.


24-24: LGTM on the interface rename.

The rename from MeteringEventsOperations to EventsOperations is cleaner and aligns with the broader naming simplification across the v3 API surface.

api/spec/src/v3/shared/properties.tsp (1)

29-37: Nice discriminated union pattern!

The ULIDOrResourceKey union is well-structured and provides clear alternatives for identifying resources. The naming and documentation are solid.

api/spec/src/v3/common/pagination.tsp (1)

164-196: Solid pagination metadata structure!

The PaginatedMeta and PageMeta models follow consistent patterns with the existing cursor pagination approach. The structure is clear and well-documented.

One thing to consider: all fields in PageMeta are required. Make sure total is always computable for your use cases (some large datasets might need estimated counts instead).

api/spec/src/v3/shared/resource.tsp (2)

36-36: Good consolidation with Common.Labels.

The shift to Common.Labels is cleaner and aligns with the broader property restructuring mentioned in the PR context.


38-54: Nice refactoring of timestamp fields!

Moving from Common.CreatedAt/UpdatedAt/DeletedAt to direct DateTime types with explicit doc comments is cleaner and reduces indirection. The documentation correctly references ISO-8601 format.

api/spec/src/v3/shared/consts.tsp (3)

4-4: LGTM on the OpenMeterTitle constant.

Clean addition that provides a consistent title reference across the API surface.


8-18: Nice API surface expansion!

The rename to EventsTag is cleaner, and the new tag/description pairs for Customers, Entitlements, and Subscriptions follow a consistent pattern. The descriptions clearly explain each concept.


22-22: Good addition of PrivateExtension.

Completes the extension visibility options with a consistent pattern. The x-private naming follows OpenAPI extension conventions.

api/spec/src/v3/shared/responses.tsp (6)

7-12: Solid GetResponse model!

Clean generic response pattern with the correct 200 status code. The @doc and @friendlyName annotations will generate good API documentation.


14-19: Perfect CreateResponse implementation!

The 201 status code is semantically correct for resource creation. Nice consistency with the other response models.


21-26: UpdateResponse looks good!

The 200 status with body return is the right choice for updates where you return the updated resource.


28-32: Clean DeleteResponse!

The 204 No Content status is perfect for successful deletes with no response body.


34-45: Excellent CursorPaginatedResponse!

The use of @pageItems on the data array and the separate meta field with Common.CursorMeta follows TypeSpec pagination best practices. This will generate proper pagination support in client SDKs.


47-58: Great PagePaginatedResponse implementation!

The parallel structure with CursorPaginatedResponse is excellent for consistency. Using the new Common.PaginatedMeta (added in this PR) provides the page/size/total metadata that traditional pagination needs.

openmeter/server/server.go (2)

91-118: LGTM on the v3 API server wiring!

The configuration setup looks solid - namespace decoder, error handler, and ingest service are properly passed through. Good use of chi.Router grouping to isolate v3 routes.


174-176: Request context is unavailable in the middleware's ErrorHandler callback.

The oapimiddleware.Options.ErrorHandler callback signature from the oapi-codegen middleware only receives (w http.ResponseWriter, message string, statusCode int) — it doesn't include access to the request. This means context.Background() is actually the only option here. The suggested fix of using r.Context() won't work since r isn't available in this callback's scope.

That said, this is a real limitation of the middleware choice: validation errors lose request context and any associated request IDs. Consider whether the oapi-codegen middleware's constraints are acceptable here, or if there's an alternative that provides request-aware error handling.

api/v3/render/render.go (2)

53-61: Write errors after WriteHeader may be silently ignored.

Once WriteHeader is called (line 53), the status code is committed. If json.Marshal or w.Write fails, the client receives a partial/empty response with a 200 OK (or whatever status was set). The caller typically can't do much with the returned error at this point.

This is a common pattern and often acceptable, but worth noting that logging or metrics on write failures might be helpful in production.


39-62: Solid implementation of the functional options pattern!

Clean and idiomatic Go. The generic approach with [O any] keeps it flexible.

api/v3/apierrors/errors.go (1)

17-55: Well-structured API error type!

The BaseAPIError struct follows AIP-compliant patterns nicely. Good separation of user-facing fields (JSON-tagged) from internal fields (UnderlyingError with json:"-" and unexported ctx).

api/spec/src/v3/shared/index.tsp (1)

1-7: LGTM!

Clean restructuring of the imports. Moving from pagination.tsp/rest.tsp to request.tsp/responses.tsp aligns well with the new v3 API abstractions introduced in this PR.

api/v3/api.gen.go (1)

445-460: Generated changes around /openmeter/events look fine; treat this file as read‑only

The interface, wrapper, router registration, and embedded swagger blob all reflect the move to POST /openmeter/events. As long as the underlying OpenAPI spec is correct, these generated diffs look good and shouldn’t be hand‑edited—keeping all behavioral changes in the spec and regeneration pipeline will save pain later.

Also applies to: 472-483, 598-603, 606-659

api/v3/oasmiddleware/decoder.go (1)

14-25: JSON body decoder matches kin‑openapi expectations

This is a nice, minimal JsonBodyDecoder:

  • Uses json.Decoder with UseNumber() (good for preserving numeric precision).
  • Wraps failures in openapi3filter.ParseError{Kind: KindInvalidFormat}, which should integrate cleanly with the rest of your OAS validation error handling.

As long as you register it for the relevant +json vendor content types, you’re in good shape.

api/spec/common/definitions/konnect_properties.yaml (1)

3-36: [rewritten comment]
[classification tag]

api/spec/src/v3/shared/request.tsp (1)

1-22: Looks good! Clean TypeSpec request model patterns.

The visibility decorators and model compositions follow good practices:

  • CreateRequest properly restricts to create visibility
  • UpsertRequest combines create and update visibility
  • UpdateRequest makes all updateable properties optional, which is the right approach for partial updates

Nice and clean!

api/v3/oasmiddleware/hook.go (1)

18-26: The hook handles any non-nil error as a "route not found"—is that intentional?

Right now, if any error is passed to this hook (not just route-not-found errors), it'll return a 404. Usually these hooks check for a specific error type or sentinel. If the router is guaranteed to only call this for route-not-found scenarios, this is fine, but worth confirming.

api/v3/request/query/query_test.go (2)

13-67: Nice test coverage for basic parsing scenarios!

Table-driven tests are clean and cover the essentials: simple key-value, nested objects, arrays, and nested arrays. Good stuff!


838-903: Round-trip tests are excellent!

These tests verifying Marshal/Unmarshal symmetry are really valuable for catching subtle serialization bugs. Nice use of reflection to create the target type dynamically.

api/v3/request/sort.go (2)

24-30: Validation logic looks solid!

Clean implementation with clear error messages. The separation of SortOrder.Validate() and SortBy.Validate() makes the validation composable and easy to understand.

Also applies to: 37-47


65-71: Nice mapping to the internal sortx package.

Clean and simple. Since SortOrder is already validated before this is typically called, the implicit fallback to OrderDesc for invalid values is fine.

api/spec/src/v3/konnect.tsp (2)

27-29: Looks good!

Nice addition of the three separate tag metadata entries for Events, Customers, and Meters. This keeps the API documentation organized and consistent with the OpenMeter spec.


33-36: Clean rename and route update.

The rename from MeteringEventsEndpoints to EventsEndpoints and route change to /openmeter/events aligns well with the broader API restructuring. The interface extension is properly updated to Events.EventsOperations.

api/v3/request/pagination.go (1)

41-61: Validation logic looks solid.

The cursor pagination validation correctly prevents both After and Before being set simultaneously, and properly validates each cursor individually. Nice and clean!

api/v3/request/request.go (2)

187-201: Sort validation handles errors well.

Nice comprehensive error checking for all sort-related errors. The field-level error mapping to sort makes debugging straightforward for API consumers.


203-215: Filter validation is clean and informative.

Good job including the filter key in the error field (filter[%s]). This will help API users identify exactly which filter caused the issue.

api/v3/handlers/events.go (1)

109-116: Good handler structure.

The response handling is clean - returning 202 Accepted with an empty body is the right pattern for async event ingestion.

api/spec/src/v3/openmeter.tsp (1)

26-34: Consistent with konnect.tsp - looks great!

The tag metadata, route, and interface changes align well with the konnect.tsp updates. The friendlyName using Shared.OpenMeterTitle and Shared.EventsTag keeps things DRY.

api/v3/server/server.go (4)

36-56: Nice validation pattern.

Clean and comprehensive config validation using error aggregation. This ensures all required fields are checked before the server starts.


89-96: Good namespace resolution wrapper.

Wrapping the namespace decoder and converting failures to API errors is a nice touch. Keeps error handling consistent.


137-142: Verify ExcludeRequestQueryParams: true is intentional.

This disables OpenAPI validation for query parameters. Is this intentional because you're handling query parsing/validation separately in GetAttributes? If so, a brief comment explaining why would be helpful for future maintainers.


130-147: Solid OpenAPI middleware integration.

Good use of OapiRequestValidatorWithOptions with custom error handling via OasValidationErrorHook. The SilenceServersWarning and NoopAuthenticationFunc settings show thoughtful configuration. The multi-error support is nice for returning all validation failures at once.

api/v3/apierrors/invalidparameterrules/rules.go (1)

1-31: Clean and well-organized constants!

This is a nice, centralized vocabulary for validation rule identifiers. The naming is consistent (PascalCase exports with snake_case values), and having these in one place makes it easy to maintain consistency across the error handling framework.

api/v3/apierrors/errors_ctors.go (1)

12-73: Constants look good overall.

The error type URLs and messages are well-organized. I notice EmptySetType and EmptySetCursorType don't follow the URL pattern of other types - looks intentional for internal markers, which is fine.

api/v3/request/query/query.go (2)

19-128: Well-documented options struct!

The ParseOptions struct is thoroughly documented with clear explanations of each option. The defaults are sensible and the compatibility notes with JavaScript's qs library are helpful.


1195-1221: Nice TextUnmarshaler support!

The tryUnmarshalText function properly handles both direct implementations and pointer receiver implementations of encoding.TextUnmarshaler. This allows custom types to define their own parsing logic, which is a clean extensibility point.

Comment thread api/spec/src/v3/common/properties.tsp Resolved
Comment thread api/v3/apierrors/errors_ctors.go Resolved
Comment thread api/v3/apierrors/errors_ctors.go Resolved
Comment thread api/v3/apierrors/errors_ctors.go Resolved
Comment thread api/v3/apierrors/errors_ctors.go Resolved
Comment thread api/v3/request/request.go Outdated
Comment on lines +175 to +185
if a.Pagination.Size > conf.maxPageSize {
return nil, apierrors.NewBadRequestError(r.Context(), err,
apierrors.InvalidParameters{
apierrors.InvalidParameter{
Field: "page[size]",
Reason: fmt.Sprintf("page size must be less than or equal to %d", conf.maxPageSize),
Source: apierrors.InvalidParamSourceQuery,
},
},
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Potential bug: reusing err variable that may be nil.

On line 176, the error returned by NewBadRequestError uses err from the pagination validation block, but if validation passed, err is nil. This could lead to confusing error reporting. Consider creating a new error for this case.

 	if a.Pagination.Size > conf.maxPageSize {
-		return nil, apierrors.NewBadRequestError(r.Context(), err,
+		return nil, apierrors.NewBadRequestError(r.Context(), 
+			fmt.Errorf("page size %d exceeds maximum %d", a.Pagination.Size, conf.maxPageSize),
 			apierrors.InvalidParameters{
 				apierrors.InvalidParameter{
 					Field:  "page[size]",
 					Reason: fmt.Sprintf("page size must be less than or equal to %d", conf.maxPageSize),
 					Source: apierrors.InvalidParamSourceQuery,
 				},
 			},
 		)
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if a.Pagination.Size > conf.maxPageSize {
return nil, apierrors.NewBadRequestError(r.Context(), err,
apierrors.InvalidParameters{
apierrors.InvalidParameter{
Field: "page[size]",
Reason: fmt.Sprintf("page size must be less than or equal to %d", conf.maxPageSize),
Source: apierrors.InvalidParamSourceQuery,
},
},
)
}
if a.Pagination.Size > conf.maxPageSize {
return nil, apierrors.NewBadRequestError(r.Context(),
fmt.Errorf("page size %d exceeds maximum %d", a.Pagination.Size, conf.maxPageSize),
apierrors.InvalidParameters{
apierrors.InvalidParameter{
Field: "page[size]",
Reason: fmt.Sprintf("page size must be less than or equal to %d", conf.maxPageSize),
Source: apierrors.InvalidParamSourceQuery,
},
},
)
}
🤖 Prompt for AI Agents
In api/v3/request/request.go around lines 175 to 185, the code reuses an outer
variable `err` (which may be nil) when constructing the BadRequest error for an
oversized page; create a new local error describing the page size violation
(e.g., using fmt.Errorf or errors.New with the actual sizes) and pass that new
error into apierrors.NewBadRequestError instead of the possibly-nil `err`,
ensuring the error variable is scoped locally to this block so the returned
error always contains meaningful details.

Comment thread api/v3/request/sort.go Resolved
Comment thread api/v3/response/pagination.go Outdated
Comment on lines +29 to +30
// Size of the requested page
Size float32 `json:"size"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

rg -n "Size.*float" --type go -C 2

Repository: openmeterio/openmeter

Length of output: 292


🏁 Script executed:

# Let's also check the pagination.go file to see the full context
cat -n api/v3/response/pagination.go

Repository: openmeterio/openmeter

Length of output: 3197


🏁 Script executed:

# Check if there's an OpenAPI spec or similar documentation
fd -e yaml -e json -e go | xargs rg -l "openapi\|swagger\|Size" | head -20

Repository: openmeterio/openmeter

Length of output: 47


🏁 Script executed:

# Look for how Size is used in the codebase
rg -n "\.Size" --type go | head -30

Repository: openmeterio/openmeter

Length of output: 636


Size should be int, not float32.

Pagination sizes are always whole numbers. The offset pagination response at the same line uses int for Size (line 72), so there's an inconsistency here. Also, the field is never populated in NewCursorPaginationResponse, which suggests it might be unfinished. Change it to int to match the standard pagination behavior.

🤖 Prompt for AI Agents
In api/v3/response/pagination.go around lines 29-30, the Cursor pagination
struct defines Size as float32 which is incorrect; change the Size field type to
int to match the offset pagination and standard whole-number page sizes, update
any JSON tags if needed, and then update NewCursorPaginationResponse to set the
Size field (populate it from the incoming request or default) so the cursor
response returns a valid integer Size consistent with the offset response.

Comment thread api/v3/response/pagination.go Outdated
Comment on lines +41 to +63
// NewCursorPaginationResponse creates a new pagination response from an ordered list of items.
// T must implement the Item interface for cursor generation.
func NewCursorPaginationResponse[T pagination.Item](items []T) CursorPaginationResponse[T] {
result := CursorPaginationResponse[T]{
Data: items,
Meta: CursorMeta{
Page: CursorMetaPage{
Next: nullable.NewNullNullable[string](),
Previous: nullable.NewNullNullable[string](),
},
},
}

// Generate first and last cursor from the first and last item if there are any items
if len(items) > 0 {
firstItem := items[0]
lastItem := items[len(items)-1]
result.Meta.Page.First = lo.ToPtr(firstItem.Cursor().Encode())
result.Meta.Page.Last = lo.ToPtr(lastItem.Cursor().Encode())
}

return result
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Size field is not populated in the response.

The CursorMetaPage.Size field remains at its zero value (0) since nothing sets it. Callers might expect this to reflect the page size requested or returned.

-func NewCursorPaginationResponse[T pagination.Item](items []T) CursorPaginationResponse[T] {
+func NewCursorPaginationResponse[T pagination.Item](items []T, size int) CursorPaginationResponse[T] {
 	result := CursorPaginationResponse[T]{
 		Data: items,
 		Meta: CursorMeta{
 			Page: CursorMetaPage{
 				Next:     nullable.NewNullNullable[string](),
 				Previous: nullable.NewNullNullable[string](),
+				Size:     float32(size),
 			},
 		},
 	}
🤖 Prompt for AI Agents
In api/v3/response/pagination.go around lines 41 to 63, the CursorMetaPage.Size
field is never set so it stays zero; set the Size to reflect the number of items
returned by assigning Meta.Page.Size = len(items) (or the requested page size if
that value is available from the caller) when building the
CursorPaginationResponse so the response accurately reports the page size.

Comment thread api/v3/response/pagination.go Outdated
Comment on lines +85 to +86
// NewPagePaginationResponse creates a new pagination response from an ordered list of items.
func NewOffsetPaginationResponse[T any](items []T, page PaginationMetaPage) PagePaginationResponse[T] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Comment/function name mismatch.

The comment says "NewPagePaginationResponse" but the function is named "NewOffsetPaginationResponse". Pick one naming convention and update accordingly.

-// NewPagePaginationResponse creates a new pagination response from an ordered list of items.
+// NewOffsetPaginationResponse creates a new pagination response from an ordered list of items.
 func NewOffsetPaginationResponse[T any](items []T, page PaginationMetaPage) PagePaginationResponse[T] {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// NewPagePaginationResponse creates a new pagination response from an ordered list of items.
func NewOffsetPaginationResponse[T any](items []T, page PaginationMetaPage) PagePaginationResponse[T] {
// NewOffsetPaginationResponse creates a new pagination response from an ordered list of items.
func NewOffsetPaginationResponse[T any](items []T, page PaginationMetaPage) PagePaginationResponse[T] {
🤖 Prompt for AI Agents
In api/v3/response/pagination.go around lines 85-86, the function comment and
the function name disagree: the comment says "NewPagePaginationResponse" while
the function is declared as "NewOffsetPaginationResponse"; pick one convention
and make them consistent by renaming either the comment or the function to match
the chosen name (update the doc comment to "NewOffsetPaginationResponse" if
keeping the function name, or rename the function to "NewPagePaginationResponse"
and update any usages), and ensure any references/tests/imports are updated
accordingly.

)

func (h *eventsHandler) IngestEvents() IngestEventsHandler {
return httptransport.NewHandler(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy paste, which is fine given we are going to deprecate the v1 api.

Comment thread api/v3/handlers/events.go Outdated
@@ -0,0 +1,124 @@
package handlers

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move this back to openmeter/ingest/httpdriver. The reason being is that I would avoid having this kitchen-sink package for handlers.

Once we rewrite all of our stuff to V3 this package will be quite huge and filled with helper and zillions of files and dependencies.

Events is a bad example as it's a single endpoint handler, but just imagine adding entitlements, subscriptions and billing here.

Comment thread api/v3/handlers/convert.go Outdated
@@ -0,0 +1,3 @@
//go:generate go tool github.com/jmattheis/goverter/cmd/goverter gen ./

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is unused, please remove.

)

// BaseAPIError is the schema for all API apierrors.
type BaseAPIError struct {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder: let's use the same in cloud, so that we are not mixing the closed/open source references.

@@ -0,0 +1,31 @@
package invalidparameterrules

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems to be unused, please remove if not needed.

Comment thread api/v3/request/body.go Outdated
"github.com/openmeterio/openmeter/api/v3/apierrors"
)

func ParseBody(r *http.Request, payload any) *apierrors.BaseAPIError {

@turip turip Dec 11, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused or please use it.


switch contentType {
case "application/json":
var apiRequest api.IngestEventsBody

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use ParseBody here

Comment on lines +15 to +18
"minLength": "min_length",
"maxLength": "max_length",
"minItems": "min_items",
"maxItems": "max_items",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use invalidaparameterrules or remove that package.

Comment thread api/v3/apierrors/errors.go Resolved
Comment thread api/v3/request/request.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
api/v3/apierrors/errors_ctors.go (2)

270-276: MakeSentenceCase is ASCII-only; consider a Unicode-safe version

The empty-string guard is great, but strings.ToUpper(msg[:1]) operates on raw bytes, so it can mangle non-ASCII leading characters (multi-byte runes).

If you ever expect localized / non-ASCII messages here, a rune-based version would be safer:

func MakeSentenceCase(msg string) string {
	if msg == "" {
		return ""
	}

	runes := []rune(msg)
	runes[0] = unicode.ToUpper(runes[0])

	return string(runes)
}

You’d need to import unicode for this. If everything going through here is plain ASCII, this is more of a nice-to-have than a must-do.


88-99: Outdated comment on NewServiceUnavailable

The comment still says “generates a not found error”, but the ctor clearly creates a 503 Service Unavailable error now.

Might be worth updating to avoid future confusion:

// NewServiceUnavailable generates a service unavailable error.
func NewServiceUnavailable(ctx context.Context, err error) *BaseAPIError {
    // ...
}
🧹 Nitpick comments (4)
api/v3/apierrors/errors.go (2)

152-166: Tighten up Error() for nil underlying errors and optional nil receiver guard

Two small tweaks you might consider here:

  1. When InvalidParameters != nil but UnderlyingError is nil, the first case formats as "<nil>: field: reason". That’s a bit noisy for logs. You could special‑case that path to omit the underlying error when it’s nil.

  2. If there’s any chance this is called on a nil *BaseAPIError (e.g. var e *BaseAPIError; return e), a quick guard avoids a panic:

func (bae *BaseAPIError) Error() string {
	if bae == nil {
		return ""
	}
	// existing switch...
}

Neither is correctness‑critical, but both make behavior a bit more predictable.


178-184: Consider handling/logging RenderJSON errors

HandleAPIError currently ignores the error from render.RenderJSON. That’s totally fine if upstream logging already covers marshal/write failures, but if not, a best‑effort log on failure here could be handy for debugging partial responses / client disconnects.

Not a blocker, just something to keep in mind if you end up troubleshooting odd response behavior later.

api/v3/apierrors/encoder.go (1)

12-21: Nice layering; maybe add a cheap nil guard

I like the flow here: prefer *BaseAPIError via lo.ErrorsAs, then delegate to HandleIssueIfHTTPStatusKnown for the validation-issue path.

One small optional tweak: if there’s any chance the encoder gets called with err == nil, an early return keeps both branches from doing extra work / logging based on a non-error:

return func(ctx context.Context, err error, w http.ResponseWriter, r *http.Request) bool {
	if err == nil {
		return false
	}
	if apiErr, ok := lo.ErrorsAs[*BaseAPIError](err); ok {
		apiErr.HandleAPIError(w, r)
		return true
	}

	return commonhttp.HandleIssueIfHTTPStatusKnown(ctx, err, w)
}

Totally fine as-is if the surrounding transport layer already guarantees non-nil errors.

api/v3/apierrors/errors_ctors.go (1)

243-256: NewEmptySetResponse semantics look intentional but worth double-checking

This returns a BaseAPIError with Status: http.StatusOK and a Type of either "Empty Set" or "Empty Set Cursor", with no Title/Detail. That means if it’s eventually rendered via HandleAPIError, clients will see a 200 with a problem-style body, not a conventional [] or {} payload.

If that’s matching an existing contract, all good. If this is new behavior, it may be worth confirming consumers are happy with “empty set as problem+json” rather than a more typical empty collection response.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b0698f and 7032226.

📒 Files selected for processing (6)
  • api/spec/common/definitions/konnect_properties.yaml (1 hunks)
  • api/v3/apierrors/encoder.go (1 hunks)
  • api/v3/apierrors/errors.go (1 hunks)
  • api/v3/apierrors/errors_ctors.go (1 hunks)
  • api/v3/handlers/events.go (1 hunks)
  • api/v3/oasmiddleware/hook.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • api/v3/handlers/events.go
  • api/spec/common/definitions/konnect_properties.yaml
  • api/v3/oasmiddleware/hook.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

Files:

  • api/v3/apierrors/encoder.go
  • api/v3/apierrors/errors.go
  • api/v3/apierrors/errors_ctors.go
🧬 Code graph analysis (3)
api/v3/apierrors/encoder.go (2)
api/v3/apierrors/errors.go (1)
  • BaseAPIError (14-51)
pkg/framework/commonhttp/errors.go (1)
  • HandleIssueIfHTTPStatusKnown (113-189)
api/v3/apierrors/errors.go (2)
api/v3/render/render.go (3)
  • RenderJSON (40-62)
  • WithContentType (35-37)
  • WithStatus (23-27)
api/v3/apierrors/errors_ctors.go (1)
  • ContentTypeProblemValue (15-15)
api/v3/apierrors/errors_ctors.go (1)
api/v3/apierrors/errors.go (2)
  • BaseAPIError (14-51)
  • InvalidParameters (54-54)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Build
  • GitHub Check: Lint
  • GitHub Check: Code Generators
  • GitHub Check: Migration Checks
  • GitHub Check: Test
  • GitHub Check: Repository Scan
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
api/v3/apierrors/errors.go (1)

136-150: InvalidParameters.String implementation looks good

The builder-based join logic is clear and efficient enough for the expected cardinality. Nice touch including the rule in brackets only when present.

api/v3/apierrors/errors_ctors.go (1)

12-73: Centralizing the error type/title/detail constants is 👍

Having all the Type/Title/Detail values in one const block is super helpful for consistency and future tweaks (and keeps the constructors nice and lean). This should make it a lot easier to keep API error responses aligned over time.

Comment on lines +114 to +125
// NewForbiddenError generates an unauthorized error.
func NewForbiddenError(ctx context.Context, err error) *BaseAPIError {
return &BaseAPIError{
Type: ForbiddenType,
Status: http.StatusForbidden,
Title: ForbiddenTitle,
Instance: instance(ctx),
Detail: ForbiddenDetail,
UnderlyingError: err,
ctx: ctx,
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

sed -n '114,125p' api/v3/apierrors/errors_ctors.go

Repository: openmeterio/openmeter

Length of output: 445


Fix comment terminology for NewForbiddenError

The docstring says "generates an unauthorized error" but this function returns a 403 Forbidden status, not 401 Unauthorized. They're different things! Just swap "unauthorized" to "forbidden" to keep the terminology straight.

🤖 Prompt for AI Agents
In api/v3/apierrors/errors_ctors.go around lines 114 to 125, the function
comment for NewForbiddenError incorrectly uses the term "unauthorized"; update
the docstring to say "generates a forbidden error" (or similar wording using
"forbidden" / HTTP 403) so it accurately reflects that it returns a 403
Forbidden status, ensuring consistency between the comment and the function
behavior.

Comment on lines +56 to +105
type InvalidParameterSource uint8

const (
InvalidParamSourcePath InvalidParameterSource = iota + 1
InvalidParamSourceQuery
InvalidParamSourceBody
InvalidParamSourceHeader
)

func (i InvalidParameterSource) String() string {
switch i {
case InvalidParamSourceBody:
return "body"
case InvalidParamSourcePath:
return "path"
case InvalidParamSourceHeader:
return "header"
case InvalidParamSourceQuery:
return "query"
}
return ""
}

func ToInvalid(s string) InvalidParameterSource {
switch s {
case "query":
return InvalidParamSourceQuery
case "path":
return InvalidParamSourcePath
case "body":
return InvalidParamSourceBody
case "header":
return InvalidParamSourceHeader
}
return InvalidParameterSource(0)
}

func (i InvalidParameterSource) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}

func (i *InvalidParameterSource) UnmarshalJSON(data []byte) error {
var source string
if err := json.Unmarshal(data, &source); err != nil {
return err
}
*i = ToInvalid(source)
return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# Search for usages of InvalidParameterSource and ToInvalid
rg -n "InvalidParameterSource|ToInvalid" --type go

Repository: openmeterio/openmeter

Length of output: 852


🏁 Script executed:

# Check the full file context to understand the error handling pattern
cat -n api/v3/apierrors/errors.go | head -150

Repository: openmeterio/openmeter

Length of output: 5575


🏁 Script executed:

# Look for tests related to InvalidParameterSource
fd -e "test.go" | xargs grep -l "InvalidParameterSource" 2>/dev/null

Repository: openmeterio/openmeter

Length of output: 49


🏁 Script executed:

# Check the context of where ToInvalid is called
cat -n api/v3/oasmiddleware/error.go | sed -n '35,55p'

Repository: openmeterio/openmeter

Length of output: 792


🏁 Script executed:

# Look for any OpenAPI-related imports to understand the source of err.Parameter.In
rg -n "err\.Parameter" api/v3/oasmiddleware/error.go -B 5 -A 5

Repository: openmeterio/openmeter

Length of output: 642


Be stricter about unknown InvalidParameterSource values during deserialization

Currently, UnmarshalJSON maps any unknown string (or typo) to the zero value via ToInvalid, which then round-trips back as an empty string. This silently hides bad input.

Since this field is meant to be an enum (query, path, body, header), consider treating unknown non-empty values as a decode error instead. You could check if ToInvalid(source) returns 0 but source is non-empty, and return a decode error in that case. This makes bad payloads fail fast rather than silently normalizing them to empty strings, making issues easier to spot during testing and debugging.

🤖 Prompt for AI Agents
In api/v3/apierrors/errors.go around lines 56 to 105, UnmarshalJSON currently
maps any unknown string to the zero value which round-trips to an empty string;
change it to validate the decoded string: after unmarshalling into source, call
ToInvalid(source) and if it returns 0 and source is non-empty return a decode
error (e.g. fmt.Errorf("invalid InvalidParameterSource: %q", source)); if source
is empty you may keep the zero value behavior; update imports if necessary.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
api/v3/handlers/events/ingest.go (1)

42-49: Reuse the shared body parsing helper instead of manual json.NewDecoder

You’re doing raw json.NewDecoder(r.Body).Decode(&apiRequest) here (and similarly in the other branches). If there’s already a shared ParseBody/helper in the stack (as suggested in the earlier review), it’d be nice to route through that for consistent limits, logging, and error translation across endpoints.

That keeps all the “how do we read and bound the body?” concerns in one place and avoids subtle drift between handlers.

🧹 Nitpick comments (2)
api/v3/apierrors/encoder.go (1)

13-22: Avoid reusing err name for the typed *BaseAPIError

Tiny readability nit: inside

if err, ok := lo.ErrorsAs[*BaseAPIError](err); ok {
    err.HandleAPIError(w, r)
    return true
}

the inner err shadows the original error. It works fine, but it’s a little mentally jarring when reading.

Renaming the inner variable makes the intent clearer:

if apiErr, ok := lo.ErrorsAs[*BaseAPIError](err); ok {
    apiErr.HandleAPIError(w, r)
    return true
}

Mechanically identical, just easier to follow when scanning the error path.

api/v3/handlers/events/ingest.go (1)

51-66: Consider surfacing the underlying parse error instead of generic “no events found”

Right now, if both AsEvent() and AsIngestEventsBody1() fail, you drop their errors and respond with a generic:

if len(req.Events) == 0 {
    return req, apierrors.NewBadRequestError(ctx, errors.New("no events found"), nil)
}

From a caller’s perspective, this can be a bit opaque when the body is structurally wrong rather than just “empty”. If you still have one of the original errors handy, you could wrap or reuse that so clients get a more actionable message (and you get better logs), e.g. “invalid event payload” with details.

Not a blocker, but could make debugging bad requests easier both for users and for you.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7032226 and 0e2cf7a.

⛔ Files ignored due to path filters (1)
  • go.mod is excluded by !**/*.mod
📒 Files selected for processing (5)
  • api/v3/apierrors/encoder.go (1 hunks)
  • api/v3/handlers/events/handler.go (1 hunks)
  • api/v3/handlers/events/ingest.go (1 hunks)
  • api/v3/server/routes.go (1 hunks)
  • api/v3/server/server.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/v3/server/server.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

Files:

  • api/v3/handlers/events/handler.go
  • api/v3/server/routes.go
  • api/v3/handlers/events/ingest.go
  • api/v3/apierrors/encoder.go
🧬 Code graph analysis (3)
api/v3/handlers/events/handler.go (2)
api/v3/handlers/events/ingest.go (1)
  • IngestEventsHandler (22-22)
pkg/framework/transport/httptransport/options.go (1)
  • HandlerOption (19-21)
api/v3/server/routes.go (1)
api/v3/server/server.go (1)
  • Server (58-65)
api/v3/apierrors/encoder.go (2)
api/v3/apierrors/errors.go (1)
  • BaseAPIError (14-51)
pkg/framework/commonhttp/errors.go (1)
  • HandleIssueIfHTTPStatusKnown (113-189)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Test
  • GitHub Check: Lint
  • GitHub Check: Code Generators
  • GitHub Check: Migration Checks
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
api/v3/server/routes.go (1)

7-9: Nice, straightforward routing glue

The wrapper cleanly delegates to the events handler and keeps routes.go thin, which matches the usual pattern in this codebase. As long as eventsHandler is wired in Server construction (which it appears to be), this looks good to me.

api/v3/handlers/events/handler.go (1)

10-30: Clean handler wiring

The interface + private struct + New constructor pattern here is clear and keeps dependencies explicit (resolveNamespace, ingest.Service, options). No issues from my side — this is easy to read and extend.

api/v3/handlers/events/ingest.go (1)

89-105: Handler construction and response semantics look solid

The business part and wiring look good to me:

  • Endpoint just delegates to h.service.IngestEvents and ignores the service’s return value, which matches the 202/empty‑body contract.
  • EmptyResponseEncoder[IngestEventsResponse](http.StatusAccepted) plus IngestEventsResponse = *struct{} keeps the generic signature happy while clearly signaling “no payload”.
  • Options (WithOperationName("ingest-metering-events") and WithErrorEncoder(apierrors.GenericErrorEncoder())) plug this neatly into the existing tracing/error stack.

Nice, clean integration of the new ingest flow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants