Repository navigation
feat(server): register v3 api router - #3683
Conversation
📝 WalkthroughWalkthroughThis 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 Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Suggested labels
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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:
Missing field context: The
InvalidParameterdoesn't specify which field failed, making debugging harder for API consumers. Consider adding the field name if the decoder error provides it.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 requestsThe 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
ExternalResourceKeyappropriately 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 toolpattern 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: DuplicateContentTypeKeyconstant.Per the relevant code snippets,
ContentTypeKeyis also defined inapi/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:ToInvalidreturns 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.RenderJSONis 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 handlerThe delegation to
s.eventsHandler.IngestEvents().ServeHTTP(w, r)keeps this nicely minimal. Just make sureeventsHandleris always non‑nil (e.g., enforced inServerconstruction), 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 readableThis 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
aipMappersilently drops any errors that aren’t*openapi3.SchemaErroror*openapi3filter.RequestError. If kin‑openapi ever adds new validation error types, they’ll just disappear. Adefaultcase that falls back to a genericInvalidParameter{Reason: err.Error()}would make this future‑proof without changing current behavior.- In the
RequestErrorbranch, the reuse and shadowing oferr(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
oneOfhandling,collectFromSchemaErrorcurrently drops any parent context (parameter name, source) because it callsinvalidParamFromSchemaErrorwithparent == nil. If you ever need parameter‑scopedfield/sourcein those nested errors, you may want to thread the parentInvalidParameterthrough that path too.Also applies to: 82-120, 122-143
api/v3/request/request_test.go (1)
15-281: Great coverage forGetAttributes; a couple of optional extensionsThis 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 inFilter).- Cover a negative path where multiple filter ops are set for the same field and you expect
ErrFilterMultipleFilterOperationsto surface viaGetAttributes.But as‑is, this is already very solid.
api/v3/oasmiddleware/response.go (2)
11-15: Consider storing thehttp.ResponseWriterdirectly 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.wdirectly instead of(*rww.w).
37-41: Comment is incorrect—it says "Header()" but describes theWritefunction.Quick copy-paste slip here. Also, while
bytes.Buffer.Writenever 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 butrequire.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 existsapi/v3/request/pagination.go (2)
22-27: Error naming could be more generic.The
ErrCursorPaginationSizeInvaliderror is used for all pagination kinds (line 42-44), not just cursor pagination. Consider renaming toErrPaginationSizeInvalidfor 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
Numberfield 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 validateNumber >= 0(or>= 1if 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.
WithDefaultPageSizeDefaulthas "Default" twice. Consider renaming toWithDefaultPageSizefor 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 andAsIngestEventsBody1()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: 0orArrayLimit: 0- they'll be ignored. Same goes for booleans if defaults ever change totrue.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=0orkey=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 handlesmap[string]interface{}and[]interface{}.Direct calls to
Stringifywith concrete types like[]stringormap[string]stringwill silently produce no output since they don't match the type switch cases. TheMarshalfunction handles this by converting first, butStringifyalone might surprise users.Consider adding a fallback that uses reflection, or document that
Stringifyexpects the generic interface types.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
api/v3/openapi.yamlis 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.tspapi/spec/src/v3/common/properties.tspapi/spec/src/v3/shared/properties.tspapi/spec/src/v3/events/operations.tspapi/spec/src/v3/shared/request.tspapi/spec/src/v3/shared/responses.tspapi/spec/src/v3/shared/index.tspapi/spec/src/v3/konnect.tspapi/spec/src/v3/shared/consts.tspapi/spec/src/v3/shared/resource.tspapi/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.goapi/v3/request/filter.goapi/v3/api.gen.goapi/v3/oasmiddleware/error.goapi/v3/request/sort.goapi/v3/oasmiddleware/hook.goapi/v3/request/body.goapi/v3/handlers/convert.goapi/v3/oasmiddleware/response.goapi/v3/request/request.goapi/v3/oasmiddleware/decoder.goapi/v3/request/request_test.goapi/v3/request/query/query_test.goopenmeter/server/server.goapi/v3/apierrors/errors.goapi/v3/handlers/events.goapi/v3/render/render.goapi/v3/response/pagination.goapi/v3/server/server.goapi/v3/apierrors/invalidparameterrules/rules.goapi/v3/request/query/query.goapi/v3/request/pagination.goapi/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.goapi/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
MeteringEventsOperationstoEventsOperationsis 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
ULIDOrResourceKeyunion 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
PaginatedMetaandPageMetamodels follow consistent patterns with the existing cursor pagination approach. The structure is clear and well-documented.One thing to consider: all fields in
PageMetaare required. Make suretotalis 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.Labelsis 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/DeletedAtto directDateTimetypes 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
EventsTagis 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-privatenaming 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
@docand@friendlyNameannotations 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
@pageItemson the data array and the separatemetafield withCommon.CursorMetafollows TypeSpec pagination best practices. This will generate proper pagination support in client SDKs.
47-58: Great PagePaginatedResponse implementation!The parallel structure with
CursorPaginatedResponseis excellent for consistency. Using the newCommon.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.Routergrouping to isolate v3 routes.
174-176: Request context is unavailable in the middleware's ErrorHandler callback.The
oapimiddleware.Options.ErrorHandlercallback signature from the oapi-codegen middleware only receives(w http.ResponseWriter, message string, statusCode int)— it doesn't include access to the request. This meanscontext.Background()is actually the only option here. The suggested fix of usingr.Context()won't work sincerisn'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 afterWriteHeadermay be silently ignored.Once
WriteHeaderis called (line 53), the status code is committed. Ifjson.Marshalorw.Writefails, 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
BaseAPIErrorstruct follows AIP-compliant patterns nicely. Good separation of user-facing fields (JSON-tagged) from internal fields (UnderlyingErrorwithjson:"-"and unexportedctx).api/spec/src/v3/shared/index.tsp (1)
1-7: LGTM!Clean restructuring of the imports. Moving from
pagination.tsp/rest.tsptorequest.tsp/responses.tspaligns well with the new v3 API abstractions introduced in this PR.api/v3/api.gen.go (1)
445-460: Generated changes around/openmeter/eventslook fine; treat this file as read‑onlyThe 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 expectationsThis is a nice, minimal
JsonBodyDecoder:
- Uses
json.DecoderwithUseNumber()(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
+jsonvendor 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:
CreateRequestproperly restricts to create visibilityUpsertRequestcombines create and update visibilityUpdateRequestmakes all updateable properties optional, which is the right approach for partial updatesNice 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()andSortBy.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
SortOrderis already validated before this is typically called, the implicit fallback toOrderDescfor 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
MeteringEventsEndpointstoEventsEndpointsand route change to/openmeter/eventsaligns well with the broader API restructuring. The interface extension is properly updated toEvents.EventsOperations.api/v3/request/pagination.go (1)
41-61: Validation logic looks solid.The cursor pagination validation correctly prevents both
AfterandBeforebeing 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
sortmakes 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.OpenMeterTitleandShared.EventsTagkeeps 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: VerifyExcludeRequestQueryParams: trueis 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
OapiRequestValidatorWithOptionswith custom error handling viaOasValidationErrorHook. TheSilenceServersWarningandNoopAuthenticationFuncsettings 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
EmptySetTypeandEmptySetCursorTypedon'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
ParseOptionsstruct 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
tryUnmarshalTextfunction properly handles both direct implementations and pointer receiver implementations ofencoding.TextUnmarshaler. This allows custom types to define their own parsing logic, which is a clean extensibility point.
| 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, | ||
| }, | ||
| }, | ||
| ) | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| // Size of the requested page | ||
| Size float32 `json:"size"` |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
rg -n "Size.*float" --type go -C 2Repository: 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.goRepository: 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 -20Repository: openmeterio/openmeter
Length of output: 47
🏁 Script executed:
# Look for how Size is used in the codebase
rg -n "\.Size" --type go | head -30Repository: 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.
| // 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 | ||
| } |
There was a problem hiding this comment.
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.
| // NewPagePaginationResponse creates a new pagination response from an ordered list of items. | ||
| func NewOffsetPaginationResponse[T any](items []T, page PaginationMetaPage) PagePaginationResponse[T] { |
There was a problem hiding this comment.
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.
| // 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( |
There was a problem hiding this comment.
Copy paste, which is fine given we are going to deprecate the v1 api.
| @@ -0,0 +1,124 @@ | |||
| package handlers | |||
There was a problem hiding this comment.
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.
| @@ -0,0 +1,3 @@ | |||
| //go:generate go tool github.com/jmattheis/goverter/cmd/goverter gen ./ | |||
There was a problem hiding this comment.
I think this is unused, please remove.
| ) | ||
|
|
||
| // BaseAPIError is the schema for all API apierrors. | ||
| type BaseAPIError struct { |
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
Seems to be unused, please remove if not needed.
| "github.com/openmeterio/openmeter/api/v3/apierrors" | ||
| ) | ||
|
|
||
| func ParseBody(r *http.Request, payload any) *apierrors.BaseAPIError { |
|
|
||
| switch contentType { | ||
| case "application/json": | ||
| var apiRequest api.IngestEventsBody |
| "minLength": "min_length", | ||
| "maxLength": "max_length", | ||
| "minItems": "min_items", | ||
| "maxItems": "max_items", |
There was a problem hiding this comment.
Please use invalidaparameterrules or remove that package.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
api/v3/apierrors/errors_ctors.go (2)
270-276:MakeSentenceCaseis ASCII-only; consider a Unicode-safe versionThe 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
unicodefor 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 onNewServiceUnavailableThe comment still says “generates a not found error”, but the ctor clearly creates a
503 Service Unavailableerror 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 upError()for nil underlying errors and optional nil receiver guardTwo small tweaks you might consider here:
When
InvalidParameters != nilbutUnderlyingErrorisnil, 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.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/loggingRenderJSONerrors
HandleAPIErrorcurrently ignores the error fromrender.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 guardI like the flow here: prefer
*BaseAPIErrorvialo.ErrorsAs, then delegate toHandleIssueIfHTTPStatusKnownfor 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:NewEmptySetResponsesemantics look intentional but worth double-checkingThis returns a
BaseAPIErrorwithStatus: http.StatusOKand aTypeof either"Empty Set"or"Empty Set Cursor", with noTitle/Detail. That means if it’s eventually rendered viaHandleAPIError, 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
📒 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.goapi/v3/apierrors/errors.goapi/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.Stringimplementation looks goodThe 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/Detailvalues 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.
| // 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, | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
sed -n '114,125p' api/v3/apierrors/errors_ctors.goRepository: 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.
| 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 | ||
| } | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# Search for usages of InvalidParameterSource and ToInvalid
rg -n "InvalidParameterSource|ToInvalid" --type goRepository: 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 -150Repository: openmeterio/openmeter
Length of output: 5575
🏁 Script executed:
# Look for tests related to InvalidParameterSource
fd -e "test.go" | xargs grep -l "InvalidParameterSource" 2>/dev/nullRepository: 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 5Repository: 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.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
api/v3/handlers/events/ingest.go (1)
42-49: Reuse the shared body parsing helper instead of manualjson.NewDecoderYou’re doing raw
json.NewDecoder(r.Body).Decode(&apiRequest)here (and similarly in the other branches). If there’s already a sharedParseBody/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 reusingerrname for the typed*BaseAPIErrorTiny readability nit: inside
if err, ok := lo.ErrorsAs[*BaseAPIError](err); ok { err.HandleAPIError(w, r) return true }the inner
errshadows 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()andAsIngestEventsBody1()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
⛔ Files ignored due to path filters (1)
go.modis 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.goapi/v3/server/routes.goapi/v3/handlers/events/ingest.goapi/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 glueThe wrapper cleanly delegates to the events handler and keeps
routes.gothin, which matches the usual pattern in this codebase. As long aseventsHandleris wired inServerconstruction (which it appears to be), this looks good to me.api/v3/handlers/events/handler.go (1)
10-30: Clean handler wiringThe interface + private struct +
Newconstructor 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 solidThe business part and wiring look good to me:
- Endpoint just delegates to
h.service.IngestEventsand ignores the service’s return value, which matches the 202/empty‑body contract.EmptyResponseEncoder[IngestEventsResponse](http.StatusAccepted)plusIngestEventsResponse = *struct{}keeps the generic signature happy while clearly signaling “no payload”.- Options (
WithOperationName("ingest-metering-events")andWithErrorEncoder(apierrors.GenericErrorEncoder())) plug this neatly into the existing tracing/error stack.Nice, clean integration of the new ingest flow.
Summary by CodeRabbit
New Features
Breaking Changes
/metering/eventsto/openmeter/events✏️ Tip: You can customize this high-level summary in your review settings.