Skip to content

refactor: pagination - #3393

Merged
GAlexIHU merged 2 commits into
mainfrom
galexi/refactor/pagination
Sep 17, 2025
Merged

GAlexIHU merged 2 commits into
mainfrom
galexi/refactor/pagination

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Sep 16, 2025 •

Copy link
Copy Markdown
Contributor

Updates Pagination and Pagination V2 packages

  • use unified naming for interfaces like Result[T], CollectAll[T], Paginator[T], ...
  • write CollectAll[T] for both which fetches all results using pagination
  • add some helpers

Note: there are a lot of file changes due to renames, relevant places are the

  • pagination packages
  • ListEventsV2
  • entitlementAdapter list method

Summary by CodeRabbit

  • Breaking Changes

    • All list APIs now return pagination.Result (page, totalCount, items) instead of the old paged type.
    • Cursor-based endpoints use a structured cursor (pointer/encoded nextCursor) in responses.
    • EntitlementGrant response shape changed: added entitlementId, nextRecurrence, maxRolloverAmount, minRolloverAmount; removed legacy rollover fields.
  • New Features

    • Added CollectAll helpers to fetch all items across pages/cursors.
    • Unified JSON shape for paginated responses (page fields flattened).
  • Refactor

    • Standardized pagination across services and drivers.

# Updates Pagination and Pagination V2 packages
- use unified naming for interfaces like Result[T], CollectAll[T], Paginator[T], ...
- write CollectAll[T] for both which fetches all results using pagination
- add some helpers

> Note: there are a lot of file changes due to renames, relevant places are the
> - pagination packages
> - ListEventsV2
> - entitlementAdapter list method
@GAlexIHU
GAlexIHU requested a review from a team as a code owner September 16, 2025 14:15
@GAlexIHU GAlexIHU added the release-note/misc Miscellaneous changes label Sep 16, 2025
@coderabbitai

coderabbitai Bot commented Sep 16, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The diff migrates list/pagination APIs from pagination.PagedResponse to pagination.Result across the codebase, introduces new pagination helpers (Result, MapResult/MapResultErr, CollectAll, Paginator/NewPaginator) for page- and cursor-based flows, and updates callers, interfaces, tests, and ent-generated Paginate methods to the new types and helpers.

Changes

Cohort / File(s) Summary
Pagination core (page-based)
pkg/pagination/page.go, pkg/pagination/pagination.go, pkg/pagination/result.go, pkg/pagination/pagination_test.go, pkg/pagination/collect.go, pkg/pagination/collect_test.go
Introduced generic Result[T], MapResult/MapResultErr, NewPaginator/Paginator, CollectAll and MAX_SAFE_ITER; removed/refactored older PagedResponse-based APIs and adjusted tests.
Pagination v2 (cursor-based)
pkg/pagination/v2/result.go, pkg/pagination/v2/pagination.go, pkg/pagination/v2/cursor.go, pkg/pagination/v2/collect.go, pkg/pagination/v2/collect_test.go, pkg/pagination/v2/pagination_test.go
Added v2 Result[T] with NextCursor, NewPaginator/Paginator wrapper, Cursor.EncodePtr, CollectAll (v2), and updated tests to pointer-cursor semantics.
Ent-generated Paginate methods
openmeter/ent/db/paginate.go, pkg/framework/entutils/testutils/ent1/db/paginate.go, pkg/framework/entutils/entpaginate/paginate.tpl
All Paginate(...) signatures and local variables switched from pagination.PagedResponse[*T] to pagination.Result[*T]; logic unchanged.
Framework mapping helpers
pkg/framework/entutils/mapping.go
MapPaged / MapPagedWithErr signatures updated to accept/return pagination.Result and error paths adjusted.
Core modules (bulk signature updates)
openmeter/* (many files across app, billing, credit, customer, entitlement, metered entitlement, meter, notification, portal, productcatalog, subscription, subject, server tests) — see raw summary for full list
Consistent migration: list method signatures, adapters, services, repositories, drivers, handlers, and type aliases updated from pagination.PagedResponse[T] to pagination.Result[T]; mapping calls replaced (MapPagedResponse/MapPagedResponseError -> MapResult/MapResultErr); some entropy-specific API changes (entitlement cursor type and EntitlementGrant field changes) and minor handler/test adjustments.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "refactor: pagination" is concise, a single short clause, and directly describes the primary change in the PR — a repository-wide pagination refactor (renames from PagedResponse→Result, new Paginator/Result APIs, CollectAll helpers, and v2 cursor adjustments) as shown in the diff, so a teammate scanning history can understand the main intent.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch galexi/refactor/pagination

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (7)
openmeter/entitlement/driver/v2/customer.go (1)

160-166: Adoption of MapResultErr is good; guard nil Customer and wrap errors for context.

Avoid potential nil deref on e.Customer and improve observability.

-			mapped, err := pagination.MapResultErr(ents, func(e entitlement.Entitlement) (api.EntitlementV2, error) {
-				v2, err := ParserV2.ToAPIGenericV2(&e, e.Customer.ID, e.Customer.Key)
-				if err != nil {
-					return api.EntitlementV2{}, err
-				}
-				return lo.FromPtr(v2), nil
-			})
+			mapped, err := pagination.MapResultErr(ents, func(e entitlement.Entitlement) (api.EntitlementV2, error) {
+				if e.Customer == nil {
+					return api.EntitlementV2{}, fmt.Errorf("entitlement missing customer: id=%s", e.ID)
+				}
+				v2, err := ParserV2.ToAPIGenericV2(&e, e.Customer.ID, e.Customer.Key)
+				if err != nil {
+					return api.EntitlementV2{}, fmt.Errorf("map entitlement id=%s: %w", e.ID, err)
+				}
+				return *v2, nil
+			})
openmeter/productcatalog/subscription/http/get.go (1)

90-111: Panic risk: possible nil customer dereference

If GetCustomer returns (nil, nil) for not-found, cus.GetID() will panic. Handle the nil case.

 			// Get the customer
 			cus, err := h.CustomerService.GetCustomer(ctx, customer.GetCustomerInput{
 				CustomerIDOrKey: &customer.CustomerIDOrKey{
 					IDOrKey:   params.CustomerIDOrKey,
 					Namespace: ns,
 				},
 			})
 			if err != nil {
 				return ListCustomerSubscriptionsRequest{}, err
 			}
 
+			if cus == nil {
+				return ListCustomerSubscriptionsRequest{}, models.NewGenericNotFoundError(
+					fmt.Errorf("customer not found [namespace=%s customer=%s]", ns, params.CustomerIDOrKey),
+				)
+			}
+
 			if cus != nil && cus.IsDeleted() {
 				return ListCustomerSubscriptionsRequest{}, models.NewGenericPreConditionFailedError(
 					fmt.Errorf("customer is deleted [namespace=%s customer.id=%s]", cus.Namespace, cus.ID),
 				)
 			}
openmeter/entitlement/driver/v2/entitlement.go (1)

86-93: OrderBy gets unintentionally overridden (loss of supported fields).

You compute p.OrderBy above (Lines 64-73) from params.OrderBy, but this switch overwrites it and only honors createdAt/updatedAt. Any other valid values pass validation earlier but get reset here.

Apply this diff to remove the unintended override:

-			switch defaultx.WithDefault(params.OrderBy, "") {
-			case "createdAt":
-				p.OrderBy = entitlement.ListEntitlementsOrderByCreatedAt
-			case "updatedAt":
-				p.OrderBy = entitlement.ListEntitlementsOrderByUpdatedAt
-			default:
-				p.OrderBy = entitlement.ListEntitlementsOrderByCreatedAt
-			}
openmeter/productcatalog/plan/adapter/plan.go (2)

56-57: Guard Or() with zero predicates

query.Where(plandb.Or(orFilters...)) is invoked even when orFilters is empty, which can yield incorrect SQL or a runtime issue depending on entgo’s generator. Gate it.

-    query = query.Where(plandb.Or(orFilters...))
+    if len(orFilters) > 0 {
+      query = query.Where(plandb.Or(orFilters...))
+    }

124-127: OrderByKey uses ByVersion — likely a bug

Ordering by key should use plandb.ByKey, not ByVersion.

-    case plan.OrderByKey:
-      query = query.Order(plandb.ByVersion(order...))
+    case plan.OrderByKey:
+      query = query.Order(plandb.ByKey(order...))
openmeter/productcatalog/planaddon/adapter/planaddon.go (2)

50-58: Bug: PlanKeyVersions filter never applied; potential panic on Or().

Inside the loop you append to planOrFilters instead of planKeyVersionFilters, leaving the latter empty; plandb.Or(planKeyVersionFilters...) can panic and the intended filter is skipped.

Apply this fix:

- if len(params.PlanKeyVersions) > 0 {
-   var planKeyVersionFilters []predicate.Plan
-
-   for key, version := range params.PlanKeyVersions {
-     planOrFilters = append(planOrFilters, plandb.And(plandb.Key(key), plandb.VersionIn(version...)))
-   }
-
-   planOrFilters = append(planOrFilters, plandb.Or(planKeyVersionFilters...))
- }
+ if len(params.PlanKeyVersions) > 0 {
+   var planKeyVersionFilters []predicate.Plan
+   for key, versions := range params.PlanKeyVersions {
+     planKeyVersionFilters = append(planKeyVersionFilters,
+       plandb.And(plandb.Key(key), plandb.VersionIn(versions...)),
+     )
+   }
+   planOrFilters = append(planOrFilters, plandb.Or(planKeyVersionFilters...))
+ }

82-90: Bug: Uses PlanKeyVersions in Addon section and misbuilds version filters.

  • Should use params.AddonKeyVersions, not params.PlanKeyVersions.
  • Same “append to the wrong slice” issue as above; may panic and skips filter.

Apply this fix:

- if len(params.PlanKeyVersions) > 0 {
-   var planKeyVersionFilters []predicate.Addon
-
-   for key, version := range params.PlanKeyVersions {
-     addonOrFilters = append(addonOrFilters, addondb.And(addondb.Key(key), addondb.VersionIn(version...)))
-   }
-
-   addonOrFilters = append(addonOrFilters, addondb.Or(planKeyVersionFilters...))
- }
+ if len(params.AddonKeyVersions) > 0 {
+   var addonKeyVersionFilters []predicate.Addon
+   for key, versions := range params.AddonKeyVersions {
+     addonKeyVersionFilters = append(addonKeyVersionFilters,
+       addondb.And(addondb.Key(key), addondb.VersionIn(versions...)),
+     )
+   }
+   addonOrFilters = append(addonOrFilters, addondb.Or(addonKeyVersionFilters...))
+ }
🧹 Nitpick comments (46)
pkg/pagination/page.go (3)

44-46: Avoid negative offsets when Validate isn’t called

Saturate Offset to 0 for unset/invalid inputs to prevent negative values if callers skip Validate.

 func (p Page) Offset() int {
-	return p.PageSize * (p.PageNumber - 1)
+	if p.PageNumber <= 1 || p.PageSize <= 0 {
+		return 0
+	}
+	return p.PageSize * (p.PageNumber - 1)
 }

52-62: Clarify zero-value semantics in Validate

If zero-value Page is a valid “unset” sentinel, consider allowing it in Validate to avoid forcing consumers to special-case IsZero().

 func (p Page) Validate() error {
+	if p.IsZero() {
+		return nil
+	}
 	if p.PageSize < 0 {
 		return &InvalidError{p, "pagesize cannot be negative"}
 	}
 
 	if p.PageNumber < 1 {
 		return &InvalidError{p, "page has to be at least 1"}
 	}
 
 	return nil
 }

53-59: Polish validation error messages

Minor copyedit for consistency and clarity.

-		return &InvalidError{p, "pagesize cannot be negative"}
+		return &InvalidError{p, "page size cannot be negative"}
@@
-		return &InvalidError{p, "page has to be at least 1"}
+		return &InvalidError{p, "page number must be at least 1"}
pkg/pagination/pagination.go (1)

21-23: Guard against nil fn in NewPaginator

Panic early to fail fast on programmer error.

 func NewPaginator[T any](fn func(ctx context.Context, page Page) (Result[T], error)) Paginator[T] {
-	return &paginator[T]{fn: fn}
+	if fn == nil {
+		panic("NewPaginator: fn cannot be nil")
+	}
+	return &paginator[T]{fn: fn}
 }
openmeter/portal/httphandler/portal.go (1)

39-47: Validate limit param to avoid zero/negative page sizes

Default to 25 unless a positive limit is provided.

-			if params.Limit != nil {
-				pageSize = *params.Limit
-			}
+			if params.Limit != nil && *params.Limit > 0 {
+				pageSize = *params.Limit
+			}
pkg/pagination/v2/cursor.go (1)

10-11: Drop lo dependency for EncodePtr

No need to pull samber/lo for a simple pointer; reduces deps and compile time.

Apply this diff:

-import (
+import (
   "encoding/base64"
   "errors"
   "fmt"
   "strings"
   "time"
- 
- "github.com/samber/lo"
 )
@@
-func (c *Cursor) EncodePtr() *string {
-  if c == nil {
-    return nil
-  }
-  return lo.ToPtr(c.Encode())
-}
+func (c *Cursor) EncodePtr() *string {
+  if c == nil {
+    return nil
+  }
+  s := c.Encode()
+  return &s
+}

Also applies to: 66-72

openmeter/subject/httphandler/subject.go (1)

95-99: MapResult migration looks correct; confirm API expects only items (no pagination meta).

You’re discarding Page/TotalCount and returning []api.Subject as before. If that’s the intended contract, LGTM. Minor tidy: inline the return.

-			resp := pagination.MapResult(result, func(sub subject.Subject) api.Subject {
-				return FromSubject(sub)
-			})
-
-			return resp.Items, nil
+			return pagination.MapResult(result, func(sub subject.Subject) api.Subject {
+				return FromSubject(sub)
+			}).Items, nil
openmeter/customer/httpdriver/customer.go (1)

109-123: Avoid package shadowing and clarify error message

Rename the lambda parameter to avoid shadowing the imported customer package and fix the error text for clarity.

-			return pagination.MapResultErr(resp, func(customer customer.Customer) (api.Customer, error) {
+			return pagination.MapResultErr(resp, func(c customer.Customer) (api.Customer, error) {
 				var item api.Customer
 
-				subs, ok := customerSubscriptions[customer.ID]
+				subs, ok := customerSubscriptions[c.ID]
 				if !ok {
 					subs = []subscription.Subscription{}
 				}
 
-				item, err = CustomerToAPI(customer, subs, request.Expand)
+				item, err = CustomerToAPI(c, subs, request.Expand)
 				if err != nil {
-					return item, fmt.Errorf("failed to cast customer customer: %w", err)
+					return item, fmt.Errorf("failed to map customer to API: %w", err)
 				}
 
 				return item, nil
 			})
test/notification/repository.go (1)

167-177: Rename helper to reflect new type (Result, not PagedResponse)

The function and its call sites still mention “PaginatedResponse”. Rename for clarity.

-	require.ElementsMatch(eventIDsFromEventPaginatedResponse(listedEvents), []string{s.eventWithFeature1.ID, s.eventWithFeatureAndSubject.ID})
+	require.ElementsMatch(eventIDsFromEventResult(listedEvents), []string{s.eventWithFeature1.ID, s.eventWithFeatureAndSubject.ID})
@@
-	require.ElementsMatch(eventIDsFromEventPaginatedResponse(listedEvents), []string{s.eventWithFeature1.ID, s.eventWithFeatureAndSubject.ID})
+	require.ElementsMatch(eventIDsFromEventResult(listedEvents), []string{s.eventWithFeature1.ID, s.eventWithFeatureAndSubject.ID})
@@
-	require.ElementsMatch(eventIDsFromEventPaginatedResponse(listedEvents), []string{s.eventWithSubject1.ID, s.eventWithFeatureAndSubject.ID})
+	require.ElementsMatch(eventIDsFromEventResult(listedEvents), []string{s.eventWithSubject1.ID, s.eventWithFeatureAndSubject.ID})
@@
-	require.ElementsMatch(eventIDsFromEventPaginatedResponse(listedEvents), []string{s.eventWithSubject1.ID, s.eventWithFeatureAndSubject.ID})
+	require.ElementsMatch(eventIDsFromEventResult(listedEvents), []string{s.eventWithSubject1.ID, s.eventWithFeatureAndSubject.ID})
@@
-func eventIDsFromEventPaginatedResponse(events pagination.Result[notification.Event]) []string {
+func eventIDsFromEventResult(events pagination.Result[notification.Event]) []string {

Also applies to: 200-209, 220-227

openmeter/billing/adapter/invoice.go (1)

249-272: Use MapResultErr; also ensures Page reflects the actual paginated result

Current code sets response.Page = input.Page, which may diverge from the normalized page returned by ent.Paginate. Using MapResultErr simplifies mapping and preserves paging metadata.

-		response := pagination.Result[billing.Invoice]{
-			Page: input.Page,
-		}
-
-		paged, err := query.Paginate(ctx, input.Page)
-		if err != nil {
-			return response, err
-		}
-
-		result := make([]billing.Invoice, 0, len(paged.Items))
-		for _, invoice := range paged.Items {
-			mapped, err := tx.mapInvoiceFromDB(ctx, invoice, input.Expand)
-			if err != nil {
-				return response, err
-			}
-
-			result = append(result, mapped)
-		}
-
-		response.TotalCount = paged.TotalCount
-		response.Items = result
-
-		return response, nil
+		paged, err := query.Paginate(ctx, input.Page)
+		if err != nil {
+			return billing.ListInvoicesResponse{}, err
+		}
+		return pagination.MapResultErr(paged, func(inv *db.BillingInvoice) (billing.Invoice, error) {
+			return tx.mapInvoiceFromDB(ctx, inv, input.Expand)
+		})
openmeter/productcatalog/subscription/http/get.go (2)

130-134: Use subs.Page to reflect actual pagination metadata

Responding with req.Page can diverge from the normalized page returned by the service.

-			return ListCustomerSubscriptionsResponse{
-				Page:       req.Page,
-				TotalCount: subs.TotalCount,
-				Items:      apiSubs,
-			}, nil
+			return ListCustomerSubscriptionsResponse{
+				Page:       subs.Page,
+				TotalCount: subs.TotalCount,
+				Items:      apiSubs,
+			}, nil

137-141: Operation name mismatch

This is a list endpoint; consider renaming the operation to “listCustomerSubscriptions”.

-			httptransport.WithOperationName("getSubscription"),
+			httptransport.WithOperationName("listCustomerSubscriptions"),
openmeter/productcatalog/plan/service.go (1)

361-362: Fix docstring typo (EffectiveTo vs EffectiveFrom).

The comment doesn’t match the field name.

-    // EffectiveFrom defines the time from the Plan is going to be unpublished.
+    // EffectiveTo defines the time when the Plan is going to be unpublished.
openmeter/portal/adapter/token.go (1)

18-29: Typo: JTWPortalTokenClaims → JWTPortalTokenClaims.

Minor naming fix; improves clarity and searchability.

-type JTWPortalTokenClaims struct {
+type JWTPortalTokenClaims struct {
   jwt.RegisteredClaims
@@
-	token := jwt.NewWithClaims(jwt.SigningMethodHS256, JTWPortalTokenClaims{
+	token := jwt.NewWithClaims(jwt.SigningMethodHS256, JWTPortalTokenClaims{
@@
-	jwtToken, err := jwt.ParseWithClaims(tokenString, &JTWPortalTokenClaims{}, keyFunc, opts...)
+	jwtToken, err := jwt.ParseWithClaims(tokenString, &JWTPortalTokenClaims{}, keyFunc, opts...)
@@
-	jwtClaims, ok := jwtToken.Claims.(*JTWPortalTokenClaims)
+	jwtClaims, ok := jwtToken.Claims.(*JWTPortalTokenClaims)

Also applies to: 49-59, 88-90, 93-96

pkg/pagination/v2/pagination_test.go (1)

17-20: Update comment to match method name.

Comment says “GetTime implements Item.GetTime” but method is Cursor().

-// GetTime implements Item.GetTime
+// Cursor implements Item.Cursor
 func (i TestItem) Cursor() Cursor {
openmeter/productcatalog/feature/repository.go (1)

14-14: Approve — ListFeatures now returns pagination.Result

No remaining pagination.PagedResponse usages found; repo-wide migration looks consistent. Optional: openmeter/productcatalog/driver/feature.go (around L173–196) performs manual mapping of paged -> api.Feature — consider using pagination.MapResult for consistency.

openmeter/entitlement/connector.go (2)

46-55: Clarify overlapping filters (precedence/semantics).

The four flags/time fields can conflict. Consider consolidating into a single tri-state or documenting precedence.


79-79: Typo in comment ("featueres").

Replace with “features” to avoid copy/paste propagation.

openmeter/credit/grant/repo.go (2)

51-54: Follow through on deprecation of Limit/Offset.

If Page is authoritative, mark these with deprecation tags and gate usage to avoid ambiguity.


75-76: Repo pagination return migrated — LGTM

Adapters and tests use pagination.Result[Grant] (verified in openmeter/credit/adapter/grant.go, openmeter/server/server_test.go, openmeter/credit/grant/repo.go). Only leftover reference to PagedResponse is the generator template: pkg/framework/entutils/entpaginate/paginate.tpl — update the template to avoid regenerating PagedResponse.

openmeter/app/service/customer.go (1)

12-14: Validate ListCustomerData input (align with other service methods).

Other service list methods validate and wrap with GenericValidationError. Add the same here or confirm adapter-level validation.

 import (
   "context"
 
   "github.com/openmeterio/openmeter/openmeter/app"
+  "github.com/openmeterio/openmeter/pkg/models"
   "github.com/openmeterio/openmeter/pkg/pagination"
 )
 
 func (s *Service) ListCustomerData(ctx context.Context, input app.ListCustomerInput) (pagination.Result[app.CustomerApp], error) {
+  if err := input.Validate(); err != nil {
+    return pagination.Result[app.CustomerApp]{}, models.NewGenericValidationError(err)
+  }
   return s.adapter.ListCustomerData(ctx, input)
 }
openmeter/credit/adapter/grant.go (3)

139-160: Populate TotalCount in non-paginated path (clients often rely on it).

When Page.IsZero() you return Items but TotalCount stays 0. Consider setting it via Count for consistent semantics.

   // we're using limit and offset
   if params.Page.IsZero() {
+    // Compute total before limit/offset to keep semantics consistent
+    total, err := query.Clone().Count(ctx)
+    if err != nil {
+      return response, err
+    }
     if params.Limit > 0 {
       query = query.Limit(params.Limit)
     }
     if params.Offset > 0 {
       query = query.Offset(params.Offset)
     }
 
     entities, err := query.All(ctx)
     if err != nil {
       return response, err
     }
 
     grants := make([]grant.Grant, 0, len(entities))
     for _, entity := range entities {
       grants = append(grants, mapGrantEntity(entity))
     }
 
     response.Items = grants
+    response.TotalCount = total
     return response, nil
   }

81-89: Avoid evaluating clock.Now() twice.

Minor: compute once and reuse to keep a consistent cutoff within the filter.

   if !params.IncludeDeleted {
-    query = query.Where(
-      db_grant.Or(db_grant.DeletedAtIsNil(), db_grant.DeletedAtGT(clock.Now())),
-      db_grant.HasEntitlementWith(db_entitlement.Or(
-        db_entitlement.DeletedAtIsNil(),
-        db_entitlement.DeletedAtGT(clock.Now()),
-      )),
-    )
+    now := clock.Now()
+    query = query.Where(
+      db_grant.Or(db_grant.DeletedAtIsNil(), db_grant.DeletedAtGT(now)),
+      db_grant.HasEntitlementWith(db_entitlement.Or(
+        db_entitlement.DeletedAtIsNil(),
+        db_entitlement.DeletedAtGT(now),
+      )),
+    )
   }

103-114: Replace O(n) OR chain with set-based IN predicates.

Current loop builds a deep OR tree. Using FeatureIDIn/FeatureKeyIn is simpler and can be more efficient.

-  if len(params.FeatureIdsOrKeys) > 0 {
-    var ep predicate.Entitlement
-    for i, key := range params.FeatureIdsOrKeys {
-      p := db_entitlement.Or(db_entitlement.FeatureID(key), db_entitlement.FeatureKey(key))
-      if i == 0 {
-        ep = p
-        continue
-      }
-      ep = db_entitlement.Or(ep, p)
-    }
-    query = query.Where(db_grant.HasEntitlementWith(ep))
-  }
+  if len(params.FeatureIdsOrKeys) > 0 {
+    query = query.Where(db_grant.HasEntitlementWith(
+      db_entitlement.Or(
+        db_entitlement.FeatureIDIn(params.FeatureIdsOrKeys...),
+        db_entitlement.FeatureKeyIn(params.FeatureIdsOrKeys...),
+      ),
+    ))
+  }
openmeter/app/adapter/marketplace.go (1)

16-24: Guard page params to avoid negative start/zero-length; keep behavior deterministic.

If PageNumber <= 0 or PageSize <= 0, lo.Subset semantics may be surprising. Clamp to sane defaults before slicing.

 func (a adapter) ListMarketplaceListings(ctx context.Context, input app.MarketplaceListInput) (pagination.Result[app.RegistryItem], error) {
   items := lo.Values(a.registry)
-  items = lo.Subset(items, (input.PageNumber-1)*input.PageSize, uint(input.PageSize))
+  pn := input.PageNumber
+  if pn < 1 {
+    pn = 1
+  }
+  ps := input.PageSize
+  if ps <= 0 {
+    ps = len(items)
+  }
+  start := (pn - 1) * ps
+  items = lo.Subset(items, start, uint(ps))
 
   response := pagination.Result[app.RegistryItem]{
     Page:       input.Page,
     Items:      items,
     TotalCount: len(a.registry),
   }

Also, if a.registry can be mutated concurrently (e.g., via RegisterMarketplaceListing) consider snapshotting under a lock. Please confirm thread-safety assumptions.

openmeter/entitlement/driver/v2/entitlement.go (1)

98-100: Stale comment about returning a simple array.

The handler now returns pagination.Result[T]; the “simple array” note is misleading here.

-			// due to backward compatibility, if pagination is not provided we return a simple array
+			// v2 always returns pagination.Result[T]; backward-compat array behavior applies to v1 only
openmeter/entitlement/adapter/entitlement_test.go (1)

406-406: Lower flake risk: increase the sleep between inserts.

1ms gaps can still collide on some environments. Prefer 5–10ms.

-			time.Sleep(1 * time.Millisecond)
+			time.Sleep(5 * time.Millisecond)
openmeter/billing/service/customeroverride.go (1)

244-257: Avoid shadowing outer variable name in mapper.

The inner res shadows the outer res (adapter result). Rename for clarity.

-        return pagination.MapResultErr(res, func(override billing.CustomerOverrideWithCustomerID) (billing.CustomerOverrideWithDetails, error) {
-            res, err := s.resolveCustomerOverrideWithDetails(ctx, resolveCustomerOverrideWithDetailsInput{
+        return pagination.MapResultErr(res, func(override billing.CustomerOverrideWithCustomerID) (billing.CustomerOverrideWithDetails, error) {
+            details, err := s.resolveCustomerOverrideWithDetails(ctx, resolveCustomerOverrideWithDetailsInput{
                 CustomerID:         override.CustomerID,
                 Override:           override.CustomerOverride,
                 DefaultProfile:     defaultProfile,
                 Expand:             input.Expand,
                 CustomersByIdCache: customersByID,
             })
             if err != nil {
                 return billing.CustomerOverrideWithDetails{}, err
             }
 
-            return res, nil
+            return details, nil
         })

Optional: consider renaming CustomersByIdCache to CustomersByIDCache project‑wide for Go style consistency.

openmeter/productcatalog/plan/service/plan.go (1)

211-224: Drop always-true length check.

len(allVersions.Items) >= 0 is always true. Either remove the if or change to > 0. Removing reads cleaner.

-        if len(allVersions.Items) >= 0 {
-            for _, p := range allVersions.Items {
+        for _, p := range allVersions.Items {
                 if p.DeletedAt == nil && p.Status() == productcatalog.PlanStatusDraft {
                     return nil, models.NewGenericValidationError(
                         fmt.Errorf("only a single draft version is allowed for Plan"),
                     )
                 }
 
                 if p.Version >= params.Version {
                     params.Version = p.Version + 1
                 }
-            }
-        }
+        }
openmeter/entitlement/repository.go (1)

23-26: Update Cursor field comment to reflect v2 composite cursor.

Comment still says “ID of the last entitlement”. It’s now a structured cursor (time, id).

-    // Cursor is the ID of the last entitlement in the previous page
-    // If not provided, the query will return the first page of results
+    // Cursor is the composite cursor (time, id) of the last entitlement from the previous page.
+    // If nil, the query returns the first page.
pkg/pagination/v2/result.go (1)

1-12: Remove lo dependency; compute pointer without extra import.

Keep v2 pagination minimal and avoid pulling samber/lo just for ToPtr.

-package pagination
-
-import "github.com/samber/lo"
+package pagination
-    if len(items) > 0 {
-        lastItem := items[len(items)-1]
-        result.NextCursor = lo.ToPtr(lastItem.Cursor())
-    }
+    if len(items) > 0 {
+        last := items[len(items)-1].Cursor()
+        result.NextCursor = &last
+    }

Optional: if all v2 uses require cursors, consider constraining the type as type Result[T Item] for stronger API guarantees.

Also applies to: 14-28

openmeter/app/service/marketplace.go (1)

29-32: Preserve Page in error returns for consistency

Return a zero-value Result carrying input.Page on validation errors, mirroring other modules (e.g., Plan adapter). Small ergonomics win for callers inspecting Page on errors.

-func (s *Service) ListMarketplaceListings(ctx context.Context, input app.MarketplaceListInput) (pagination.Result[app.RegistryItem], error) {
-  if err := input.Validate(); err != nil {
-    return pagination.Result[app.RegistryItem]{}, models.NewGenericValidationError(err)
-  }
+func (s *Service) ListMarketplaceListings(ctx context.Context, input app.MarketplaceListInput) (pagination.Result[app.RegistryItem], error) {
+  if err := input.Validate(); err != nil {
+    return pagination.Result[app.RegistryItem]{ Page: input.Page }, models.NewGenericValidationError(err)
+  }
openmeter/productcatalog/plan/adapter/plan.go (2)

84-90: Simplify “Scheduled” predicate

The Or wrapper around a single EffectiveFromGT is redundant.

-    if slices.Contains(params.Status, productcatalog.PlanStatusScheduled) {
-      predicates = append(predicates, plandb.And(
-        plandb.Or(
-          plandb.EffectiveFromGT(now),
-        ),
-      ))
-    }
+    if slices.Contains(params.Status, productcatalog.PlanStatusScheduled) {
+      predicates = append(predicates, plandb.EffectiveFromGT(now))
+    }

27-29: Preserve Page on early-validate error

Returning a Result with Page: params.Page keeps pagination echoes consistent in error paths.

-    if err := params.Validate(); err != nil {
-      return pagination.Result[plan.Plan]{}, fmt.Errorf("invalid list Plans parameters: %w", err)
-    }
+    if err := params.Validate(); err != nil {
+      return pagination.Result[plan.Plan]{ Page: params.Page }, fmt.Errorf("invalid list Plans parameters: %w", err)
+    }
openmeter/subscription/addon/service/service.go (1)

206-213: Result migration is fine; align validation error typing

Return a models.NewGenericValidationError for invalid input to match Create/ChangeQuantity and downstream HTTP mapping.

-func (s *service) List(ctx context.Context, ns string, input subscriptionaddon.ListSubscriptionAddonsInput) (pagination.Result[subscriptionaddon.SubscriptionAddon], error) {
-  def := pagination.Result[subscriptionaddon.SubscriptionAddon]{}
+func (s *service) List(ctx context.Context, ns string, input subscriptionaddon.ListSubscriptionAddonsInput) (pagination.Result[subscriptionaddon.SubscriptionAddon], error) {
+  def := pagination.Result[subscriptionaddon.SubscriptionAddon]{ Page: input.Page }
   if err := input.Validate(); err != nil {
-    return def, fmt.Errorf("invalid input: %w", err)
+    return def, models.NewGenericValidationError(fmt.Errorf("invalid input: %w", err))
   }
openmeter/entitlement/service/service.go (1)

183-190: Result migration OK; wrap page validation errors for consistency

Wrap the page validation error so callers can distinguish validation vs internal errors.

-func (c *service) ListEntitlements(ctx context.Context, params entitlement.ListEntitlementsParams) (pagination.Result[entitlement.Entitlement], error) {
+func (c *service) ListEntitlements(ctx context.Context, params entitlement.ListEntitlementsParams) (pagination.Result[entitlement.Entitlement], error) {
   if !params.Page.IsZero() {
     if err := params.Page.Validate(); err != nil {
-      return pagination.Result[entitlement.Entitlement]{}, err
+      return pagination.Result[entitlement.Entitlement]{ Page: params.Page }, models.NewGenericValidationError(err)
     }
   }
   return c.entitlementRepo.ListEntitlements(ctx, params)
 }
pkg/pagination/collect.go (2)

27-29: Consider using TotalCount for termination when available.

The current implementation relies on checking if len(res.Items) < pageSize to determine completion. However, if the last page happens to have exactly pageSize items, this will result in an unnecessary additional page fetch. Consider also checking against TotalCount if available in the response.

 all = append(all, res.Items...)

-if len(res.Items) < pageSize {
+// Stop if we got fewer items than requested, or if we've collected all items based on TotalCount
+if len(res.Items) < pageSize || (res.TotalCount > 0 && len(all) >= res.TotalCount) {
     break
 }

31-35: Use the NewPage helper for consistency.

Instead of manually incrementing page.PageNumber, use the NewPage helper function that's available in the package for better consistency with the codebase patterns.

-page.PageNumber += 1
+page = NewPage(page.PageNumber + 1, pageSize)

-if page.PageNumber > MAX_SAFE_ITER {
+if page.PageNumber > MAX_SAFE_ITER {
     return nil, fmt.Errorf("max safe iter reached: %d", page.PageNumber)
 }
openmeter/entitlement/metered/entitlement_grant.go (1)

131-144: Verify JSON serialization for EntitlementGrant (embedded grant.Grant + json:"-").

Repo uses this pattern elsewhere (e.g. openmeter/notification/event.go — HandlerDeduplicationHash json:"-"; openmeter/ent/db/grant.go — config json:"-"), but embedding is brittle: exported fields on grant.Grant can be promoted and change the JSON shape. Either document the intended JSON mapping or replace the embedding with explicit fields in openmeter/entitlement/metered/entitlement_grant.go (lines 131–144).

pkg/pagination/v2/collect.go (2)

9-9: Consider using a more descriptive constant name.

MAX_SAFE_ITER could be more descriptive. Consider MAX_PAGINATION_ITERATIONS or MAX_COLLECT_ITERATIONS to better convey its purpose.

-const MAX_SAFE_ITER = 10_000
+const MAX_PAGINATION_ITERATIONS = 10_000

22-22: Add error handling for iteration limit exceeded.

The current implementation doesn't return an error when the iteration limit is reached, which could lead to silent truncation of results.

 	for i := 0; i < MAX_SAFE_ITER; i++ {
 		res, err := paginator.Paginate(ctx, c)
 		if err != nil {
 			return all, err
 		}
 
 		all = append(all, res.Items...)
 
 		if res.NextCursor == nil {
 			break
 		}
 
 		c = res.NextCursor
 	}
 
+	if c != nil {
+		return all, fmt.Errorf("max safe iter reached: %d", MAX_SAFE_ITER+1)
+	}
+
 	return all, nil
pkg/pagination/collect_test.go (1)

126-131: Consider using Go 1.21+ built-in max function.

The local max helper function can be replaced with the built-in max function available in Go 1.21+.

-func max(a, b int) int {
-	if a > b {
-		return a
-	}
-	return b
-}

And update the usage:

-		items := make([]int, 0, max(0, end-start))
+		items := make([]int, 0, max(0, end-start))

This assumes the project is using Go 1.21+. If not, the current implementation is fine.

pkg/framework/entutils/mapping.go (2)

10-18: Function name no longer matches type (MapPaged now handles Result).

Consider adding aliases MapResult and MapResultWithErr here (or deprecate MapPaged*) to avoid confusion with the new pagination.Result.


20-31: Error handling discards partially mapped items.

If partial success is acceptable, consider returning the successfully mapped items plus the aggregated error (instead of empty items). Otherwise, current behavior is OK.

openmeter/app/adapter/customer.go (1)

49-61: Optional: fetch customer data concurrently for large pages.

If N is large, consider bounded goroutines + errgroup to reduce latency; preserve order if required.

pkg/pagination/result.go (1)

41-57: MapResultErr behavior — consider partial success semantics.

Current impl aborts on first error; if aggregation is desired, return collected items with the error.

Comment thread openmeter/billing/adapter.go Resolved
Comment on lines 427 to 431
next5Ents, err := repo.entRepo.ListActiveEntitlementsWithExpiredUsagePeriod(ctx, entitlement.ListExpiredEntitlementsParams{
Namespaces: []string{ns},
Highwatermark: time.Date(2025, 5, 1, 0, 0, 0, 0, time.UTC),
Cursor: resetableEnts[4].ID,
Cursor: lo.ToPtr(pagination.NewCursor(resetableEnts[4].CreatedAt, resetableEnts[4].ID)),
})

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

Missing Limit on the second page fetch can break the test.

The first call uses Limit: 5; the next page omits it and assumes default = 5. Make it explicit.

 		next5Ents, err := repo.entRepo.ListActiveEntitlementsWithExpiredUsagePeriod(ctx, entitlement.ListExpiredEntitlementsParams{
 			Namespaces:    []string{ns},
 			Highwatermark: time.Date(2025, 5, 1, 0, 0, 0, 0, time.UTC),
+			Limit:         5,
 			Cursor:        lo.ToPtr(pagination.NewCursor(resetableEnts[4].CreatedAt, resetableEnts[4].ID)),
 		})
📝 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
next5Ents, err := repo.entRepo.ListActiveEntitlementsWithExpiredUsagePeriod(ctx, entitlement.ListExpiredEntitlementsParams{
Namespaces: []string{ns},
Highwatermark: time.Date(2025, 5, 1, 0, 0, 0, 0, time.UTC),
Cursor: resetableEnts[4].ID,
Cursor: lo.ToPtr(pagination.NewCursor(resetableEnts[4].CreatedAt, resetableEnts[4].ID)),
})
next5Ents, err := repo.entRepo.ListActiveEntitlementsWithExpiredUsagePeriod(ctx, entitlement.ListExpiredEntitlementsParams{
Namespaces: []string{ns},
Highwatermark: time.Date(2025, 5, 1, 0, 0, 0, 0, time.UTC),
Limit: 5,
Cursor: lo.ToPtr(pagination.NewCursor(resetableEnts[4].CreatedAt, resetableEnts[4].ID)),
})
🤖 Prompt for AI Agents
In openmeter/entitlement/adapter/entitlement_test.go around lines 427 to 431,
the second ListActiveEntitlementsWithExpiredUsagePeriod call omits the Limit
parameter (first page used Limit: 5) which relies on an implicit default and can
break the test; update the second call to include Limit: 5 (same as the first
request) alongside Namespaces, Highwatermark and Cursor so pagination behavior
is explicit and deterministic.

@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

🧹 Nitpick comments (2)
pkg/framework/entutils/entpaginate/paginate.tpl (2)

33-35: Initialize Items to an empty slice for a consistent, non‑nil contract.

Pre‑initializing avoids nil vs empty inconsistencies on error paths.

-        pagedResponse := pagination.Result[*{{ $n.Name }}]{
-            Page: page,
-        }
+        pagedResponse := pagination.Result[*{{ $n.Name }}]{
+            Page:  page,
+            Items: make([]*{{ $n.Name }}, 0),
+        }

51-55: Zero page fetches “all” — consider guardrails.

Loading all rows can blow memory for large tables. Consider a soft cap or directing callers to CollectAll[T] to stream pages instead.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c7f999e and 15de1b2.

📒 Files selected for processing (1)
  • pkg/framework/entutils/entpaginate/paginate.tpl (2 hunks)
⏰ 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: E2E
  • GitHub Check: Quickstart
  • GitHub Check: Test
  • GitHub Check: Lint
  • GitHub Check: Migration Checks
  • GitHub Check: Code Generators
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
pkg/framework/entutils/entpaginate/paginate.tpl (2)

16-16: Return type migration to pagination.Result[T] looks good.

Signature aligns with the unified paginator API, and the interface assertion below guarantees compile‑time conformance.


20-27: ```shell
#!/bin/bash
set -euo pipefail

echo "PWD: $(pwd)"
echo "Listing repo root (top 40 entries):"
ls -la | sed -n '1,40p' || true

TARGET="pkg/framework/entutils/entpaginate/paginate.tpl"

echo
echo "Checking for target file: $TARGET"
if [ -f "$TARGET" ]; then
echo "FOUND: $TARGET"
echo "=== Begin file ($TARGET) ==="
sed -n '1,240p' "$TARGET" || true
echo "=== End file ==="
else
echo "NOT FOUND at expected path. Searching repository for paginate.tpl"
rg -n --hidden -S 'paginate.tpl' || true
fi

echo
echo "Searching repo for relevant pagination ctx uses and patterns"
rg -n --hidden -S '.ctx.(Offset|Limit)\b' -C3 || true
rg -n --hidden -S 'Offset\s*=\s*&zero|Limit\s*=\s*&zero|zero\s*:=\s*0' -C3 || true
rg -n --hidden -S '.Clone(' -C3 || true

echo
echo "Checking go.mod for ent dependency (if present)"
if [ -f go.mod ]; then
rg -n 'github.com/facebook/ent' go.mod || true
else
echo "no go.mod in repo root"
fi

echo
echo "Done."


</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

type (
ListFeaturesHandlerRequest = feature.ListFeaturesParams
ListFeaturesHandlerResponse = commonhttp.Union[[]api.Feature, pagination.PagedResponse[api.Feature]]
ListFeaturesHandlerResponse = commonhttp.Union[[]api.Feature, pagination.Result[api.Feature]]

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.

Not related to this PR, but we should get rid of this commonhttp.Union altogether and get rid of the untyped union in the typespec in the next api revision. cc @tothandras this might worth checking while creating the new api where we use untyped unions.

@GAlexIHU
GAlexIHU merged commit 7e18ee1 into main Sep 17, 2025
@GAlexIHU
GAlexIHU deleted the galexi/refactor/pagination branch September 17, 2025 11:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants