Skip to content

feat(subscriptions): add new list filters and order by - #4266

Merged
tothandras merged 7 commits into
mainfrom
feat/subscription-filter
May 11, 2026
Merged

tothandras merged 7 commits into
mainfrom
feat/subscription-filter

Conversation

@borosr

@borosr borosr commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Extend the GET /api/v3/openmeter/subscriptions endpoint with filter (plan_id, status, customer_id, id) and sort query params.

Notes for review

List the subscriptions and sort

curl --request GET \
  --url 'http://localhost:8888/api/v3/openmeter/subscriptions?sort=id%20desc&filter%5Bplan_id%5D%5Beq%5D=01KQJEAAD92721AYYCYV7DWGT0'

The response should look like this:

{
	"data": [
		{
			"billing_anchor": "2025-02-01T00:00:00Z",
			"created_at": "2026-05-01T19:11:48.535761Z",
			"customer_id": "01KQJEAACCQXR3VN5ZHJGG7Q9E",
			"id": "01KQJF8JSQ0NJDFZ1QREP84DQF",
			"labels": {},
			"plan_id": "01KQJEAAD92721AYYCYV7DWGT0",
			"status": "active",
			"updated_at": "2026-05-01T19:11:48.535762Z"
		},
		{
			"billing_anchor": "2025-01-01T00:00:00Z",
			"created_at": "2026-05-01T18:59:36.342583Z",
			"customer_id": "01KQJEAABS4P12MQ840VTKTMWH",
			"id": "01KQJEJ7RPZWPWJT9JACYGGEZC",
			"labels": {},
			"plan_id": "01KQJEAACPHYFNZ2RHA3BS6H1K",
			"status": "active",
			"updated_at": "2026-05-01T18:59:36.342585Z"
		}
	],
	"meta": {
		"page": {
			"size": 20,
			"number": 1,
			"total": 2
		}
	}
}

Summary by CodeRabbit

  • New Features

    • Enhanced subscription listing: filter by subscription ID, customer, plan, and status; optional sort query and new order-by ID option.
    • Exposed complete set of subscription status values.
  • Bug Fixes

    • Improved validation and clearer 400 responses for invalid filter/sort inputs.
    • Consistent customer-scoped subscription lookups across listing flows.
  • Tests

    • Added tests covering new filtering and ordering behaviors.

@borosr borosr self-assigned this May 1, 2026
@borosr
borosr requested a review from a team as a code owner May 1, 2026 19:58
@borosr borosr added the release-note/ignore Ignore this change when generating release notes label May 1, 2026
@coderabbitai

coderabbitai Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a typed deep-object filter model and optional sort to the subscriptions list API; updates generated types and handler parsing; moves callers, service, repo, validators, workers, and tests to use typed ULID/string filters and adds an id order-by plus snake_case active order keys.

Changes

Subscription listing (single cohesive change DAG)

Layer / File(s) Summary
API spec / Data shape
api/spec/packages/aip/src/subscriptions/operations.tsp, api/v3/api.gen.go
Add ListSubscriptionsParamsFilter (id, customer_id, status, plan_id, plan_key) and sort?: Common.SortQuery; update generated ListSubscriptionsParams to use filter?: ListSubscriptionsParamsFilter.
Handler request parsing
api/v3/handlers/subscriptions/list.go
Parse filter[id], filter[customer_id], filter[status], filter[plan_id], filter[plan_key] into request fields; parse sort into OrderBy/Order; return 400 InvalidParameters on parse/validation errors.
API consumer mapping / HTTP callers
openmeter/productcatalog/subscription/http/get.go, openmeter/customer/httpdriver/customer.go
Map API order-by values to subscription.OrderBy*; replace CustomerIDs []string usage with CustomerID *filter.FilterULID (Eq or In) when calling subscription list.
Domain model / Service
openmeter/subscription/list.go, openmeter/subscription/state.go
Replace CustomerIDs []string with CustomerID *filter.FilterULID; add ID and PlanID filter fields; add OrderByID and rename activeFrom/activeTo keys to active_from/active_to; add SubscriptionStatus.Values().
Repository query wiring
openmeter/subscription/repo/subscriptionrepo.go
Use filter.ApplyToQuery to apply ID, CustomerID, PlanID predicates; add optional PlanKey predicate via HasPlanWith; add ordering case for OrderByID.
Callers / validators / workers
openmeter/billing/..., openmeter/subscription/.../validators/*, openmeter/billing/worker/..., openmeter/subscription/workflow/service/subscription.go
Update callers and validators to construct filter.FilterULID (Eq or In) for customer scoping; preserve namespaces/pagination/active-at semantics.
Tests
openmeter/subscription/service/service_test.go
Add tests exercising new ULID filter expressions (ID Eq/In, CustomerID, PlanID) and sorting by OrderByID ascending.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant API as API_Handler
  participant Svc as Service
  participant Repo as Repo
  participant DB as Database

  Client->>API: GET /subscriptions?filter[id]=...&filter[customer_id]=...&sort=active_from:asc
  API->>Svc: Build ListSubscriptionsInput (ID, CustomerID, PlanID, Status, OrderBy, Order)
  Svc->>Repo: List(ctx, ListSubscriptionsInput)
  Repo->>DB: Apply filters and ORDER BY (id / active_from / active_to)
  DB-->>Repo: Rows
  Repo-->>Svc: Subscriptions
  Svc-->>API: Result page
  API-->>Client: 200 OK (subscriptions JSON)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~55 minutes

Possibly related PRs

Suggested labels

area/api, release-note/feature

Suggested reviewers

  • tothandras
  • gergely-kurucz-konghq
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: adding new filters (id, customer_id, status, plan_id, plan_key) and sort/order by functionality to subscriptions list operations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/subscription-filter

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

🧹 Nitpick comments (4)
openmeter/subscription/service/service_test.go (2)

781-790: ⚡ Quick win

Please cover the DESC branch here too.

This new test only exercises OrderByID with ascending order, so half of the newly added sort behavior is still untested. A tiny DESC case alongside this one would make the new path a lot safer.

As per coding guidelines, "Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/subscription/service/service_test.go` around lines 781 - 790, Add a
companion test for the descending case next to the existing "SortByID" subtest:
call service.List with subscription.ListSubscriptionsInput using OrderBy:
subscription.OrderByID and Order: "DESC", assert err == nil, assert
len(list.Items) == 2, and assert that list.Items[0].ID > list.Items[1].ID; place
it as a sibling t.Run (e.g., "SortByID_DESC") so both ASC and DESC branches of
the sorting logic in service.List are covered.

679-681: ⚡ Quick win

Use t.Context() for this new test block.

Line 680 starts from context.Background(), but this is exactly the kind of case where t.Context() keeps cleanup and cancellation tied to the test harness. If the repo’s Go version already has it, I’d switch this block over.

Suggested fix
-		ctx, cancel := context.WithCancel(context.Background())
-		defer cancel()
+		ctx := t.Context()

As per coding guidelines, "In tests, prefer t.Context() when a testing.T or testing.TB is available instead of using context.Background() to keep cancellation and lifecycle tied to the test harness."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/subscription/service/service_test.go` around lines 679 - 681, In
the "Should filter and sort by new fields" t.Run block replace the manual
context.WithCancel(context.Background()) and deferred cancel with the test
harness context by calling ctx := t.Context() so the test lifecycle controls
cancellation; remove the cancel variable and its defer and ensure any uses of
ctx in that block use the new t.Context()-derived ctx.
openmeter/subscription/state.go (1)

25-31: ⚡ Quick win

Keep the valid status set in one place.

Values() and Validate() now hard-code the same enum separately. That makes the next status addition easy to miss in one of the two places, which would leave listing/parsing behavior out of sync. I’d pull these into one private source of truth and have both helpers read from it.

Also applies to: 34-36

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/subscription/state.go` around lines 25 - 31, The Values() and
Validate() implementations duplicate the same hard-coded enum list; consolidate
into a single private source of truth (e.g., a package-level variable like
allSubscriptionStatuses []SubscriptionStatus) and have
SubscriptionStatus.Values() return that slice (or a copy) and have
SubscriptionStatus.Validate() iterate over the same allSubscriptionStatuses to
check membership; update both the Values and Validate functions to read from
that single variable so adding a new status requires one change.
openmeter/subscription/list.go (1)

67-83: 💤 Low value

Inconsistent error wrapping pattern.

The new filter validations wrap errors in models.NewGenericValidationError(fmt.Errorf(...)), but the existing validations above (lines 50-58, 61-64) use plain fmt.Errorf(...). Since FilterULID.Validate() already returns a models.NewNillableGenericValidationError and the final return wraps everything in models.NewNillableGenericValidationError anyway, this extra wrapper seems redundant and creates inconsistency.

♻️ Suggested fix to align with existing pattern
 	if i.ID != nil {
 		if err := i.ID.Validate(); err != nil {
-			errs = append(errs, models.NewGenericValidationError(fmt.Errorf("invalid id filter: %w", err)))
+			errs = append(errs, fmt.Errorf("id filter: %w", err))
 		}
 	}

 	if i.CustomerID != nil {
 		if err := i.CustomerID.Validate(); err != nil {
-			errs = append(errs, models.NewGenericValidationError(fmt.Errorf("invalid customer_id filter: %w", err)))
+			errs = append(errs, fmt.Errorf("customer_id filter: %w", err))
 		}
 	}

 	if i.PlanID != nil {
 		if err := i.PlanID.Validate(); err != nil {
-			errs = append(errs, models.NewGenericValidationError(fmt.Errorf("invalid plan_id filter: %w", err)))
+			errs = append(errs, fmt.Errorf("plan_id filter: %w", err))
 		}
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/subscription/list.go` around lines 67 - 83, The ID, CustomerID and
PlanID validation blocks introduce an extra models.NewGenericValidationError
wrapper which is inconsistent—change the three places that currently do
models.NewGenericValidationError(fmt.Errorf(...)) to append the plain
fmt.Errorf("invalid <field> filter: %w", err) (matching the existing pattern
used elsewhere and relying on FilterULID.Validate + the final
models.NewNillableGenericValidationError wrapping); update the i.ID,
i.CustomerID and i.PlanID validation branches accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openmeter/subscription/validators/subscription/validator.go`:
- Around line 235-240: The paginator callback is ignoring the page parameter,
causing CollectAll to repeatedly fetch the first page; update the callback used
in pagination.NewPaginator so it forwards the received page into
v.Config.QueryService.List by including the page in
subscription.ListSubscriptionsInput (e.g., set the input's
Page/PageToken/pagination field to the page value) so List consumes pagination
state and the paginator can iterate all pages.

---

Nitpick comments:
In `@openmeter/subscription/list.go`:
- Around line 67-83: The ID, CustomerID and PlanID validation blocks introduce
an extra models.NewGenericValidationError wrapper which is inconsistent—change
the three places that currently do
models.NewGenericValidationError(fmt.Errorf(...)) to append the plain
fmt.Errorf("invalid <field> filter: %w", err) (matching the existing pattern
used elsewhere and relying on FilterULID.Validate + the final
models.NewNillableGenericValidationError wrapping); update the i.ID,
i.CustomerID and i.PlanID validation branches accordingly.

In `@openmeter/subscription/service/service_test.go`:
- Around line 781-790: Add a companion test for the descending case next to the
existing "SortByID" subtest: call service.List with
subscription.ListSubscriptionsInput using OrderBy: subscription.OrderByID and
Order: "DESC", assert err == nil, assert len(list.Items) == 2, and assert that
list.Items[0].ID > list.Items[1].ID; place it as a sibling t.Run (e.g.,
"SortByID_DESC") so both ASC and DESC branches of the sorting logic in
service.List are covered.
- Around line 679-681: In the "Should filter and sort by new fields" t.Run block
replace the manual context.WithCancel(context.Background()) and deferred cancel
with the test harness context by calling ctx := t.Context() so the test
lifecycle controls cancellation; remove the cancel variable and its defer and
ensure any uses of ctx in that block use the new t.Context()-derived ctx.

In `@openmeter/subscription/state.go`:
- Around line 25-31: The Values() and Validate() implementations duplicate the
same hard-coded enum list; consolidate into a single private source of truth
(e.g., a package-level variable like allSubscriptionStatuses
[]SubscriptionStatus) and have SubscriptionStatus.Values() return that slice (or
a copy) and have SubscriptionStatus.Validate() iterate over the same
allSubscriptionStatuses to check membership; update both the Values and Validate
functions to read from that single variable so adding a new status requires one
change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 761d14f8-4e1e-474f-8d59-eab0ad52f506

📥 Commits

Reviewing files that changed from the base of the PR and between ff379af and 9f5b8a6.

⛔ Files ignored due to path filters (1)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
📒 Files selected for processing (14)
  • api/spec/packages/aip/src/subscriptions/operations.tsp
  • api/v3/api.gen.go
  • api/v3/handlers/subscriptions/list.go
  • openmeter/billing/validators/customer/customer.go
  • openmeter/billing/worker/subscriptionsync/reconciler/reconciler.go
  • openmeter/customer/httpdriver/customer.go
  • openmeter/productcatalog/subscription/http/get.go
  • openmeter/subscription/list.go
  • openmeter/subscription/repo/subscriptionrepo.go
  • openmeter/subscription/service/service_test.go
  • openmeter/subscription/state.go
  • openmeter/subscription/validators/customer/validator.go
  • openmeter/subscription/validators/subscription/validator.go
  • openmeter/subscription/workflow/service/subscription.go

Comment on lines 235 to 240
return pagination.CollectAll(ctx, pagination.NewPaginator(func(ctx context.Context, page pagination.Page) (pagination.Result[subscription.Subscription], error) {
return v.Config.QueryService.List(ctx, subscription.ListSubscriptionsInput{
CustomerIDs: []string{customerID},
CustomerID: &filter.FilterULID{FilterString: filter.FilterString{Eq: &customerID}},
Namespaces: []string{namespace},
ActiveInPeriod: &timeutil.StartBoundedPeriod{From: starting},
})

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 | 🟠 Major | ⚡ Quick win

Pass page through this paginator callback.

Line 235 takes a page, but the List call never uses it. That means CollectAll keeps asking for the same first page once this customer has enough subscriptions to paginate, so this validator won’t reliably walk the full result set.

Suggested fix
 func (v SubscriptionUniqueConstraintValidator) collectCustomerSubscriptionsStarting(ctx context.Context, namespace string, customerID string, starting time.Time) ([]subscription.Subscription, error) {
 	return pagination.CollectAll(ctx, pagination.NewPaginator(func(ctx context.Context, page pagination.Page) (pagination.Result[subscription.Subscription], error) {
 		return v.Config.QueryService.List(ctx, subscription.ListSubscriptionsInput{
 			CustomerID:     &filter.FilterULID{FilterString: filter.FilterString{Eq: &customerID}},
 			Namespaces:     []string{namespace},
 			ActiveInPeriod: &timeutil.StartBoundedPeriod{From: starting},
+			Page:           page,
 		})
 	}), 1000)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/subscription/validators/subscription/validator.go` around lines 235
- 240, The paginator callback is ignoring the page parameter, causing CollectAll
to repeatedly fetch the first page; update the callback used in
pagination.NewPaginator so it forwards the received page into
v.Config.QueryService.List by including the page in
subscription.ListSubscriptionsInput (e.g., set the input's
Page/PageToken/pagination field to the page value) so List consumes pagination
state and the paginator can iterate all pages.

@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: 1

🧹 Nitpick comments (1)
openmeter/subscription/service/service_test.go (1)

781-790: ⚡ Quick win

Cover the descending sort branch too.

This subtest only checks Order: "ASC", so the new sort=id desc path from the PR still isn’t exercised. A tiny extra assertion would make the coverage complete and catch regressions in reverse ordering as well.

♻️ Suggested test addition
+		t.Run("SortByIDDesc", func(t *testing.T) {
+			list, err := service.List(ctx, subscription.ListSubscriptionsInput{
+				Namespaces: []string{ns},
+				OrderBy:    subscription.OrderByID,
+				Order:      "DESC",
+			})
+			require.Nil(t, err)
+			require.Equal(t, 2, len(list.Items))
+			require.True(t, list.Items[0].ID > list.Items[1].ID)
+		})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/subscription/service/service_test.go` around lines 781 - 790, The
"SortByID" subtest only asserts ascending order; add a second call to
service.List inside the same subtest (or a new subtest) with Order: "DESC" to
exercise the descending branch: invoke service.List(ctx,
subscription.ListSubscriptionsInput{Namespaces: []string{ns}, OrderBy:
subscription.OrderByID, Order: "DESC"}), assert err is nil, assert
len(list.Items) == 2, and assert list.Items[0].ID > list.Items[1].ID to validate
reverse ordering for the sort by ID path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/v3/handlers/subscriptions/list.go`:
- Around line 97-105: When handling params.Sort after calling
request.ParseSortBy, validate that sort.Field is one of the allowed fields (the
documented allow-list: the subscription sort keys such as id, active_from,
active_to) before assigning req.OrderBy = subscription.OrderBy(sort.Field); if
the field is not in that allow-list return a 400 BadRequest using
apierrors.NewBadRequestError with an InvalidParameters entry for "sort" (similar
to the existing parse error path). Update the logic around params.Sort /
request.ParseSortBy / req.OrderBy to perform this explicit whitelist check and
only map to subscription.OrderBy for supported values.

---

Nitpick comments:
In `@openmeter/subscription/service/service_test.go`:
- Around line 781-790: The "SortByID" subtest only asserts ascending order; add
a second call to service.List inside the same subtest (or a new subtest) with
Order: "DESC" to exercise the descending branch: invoke service.List(ctx,
subscription.ListSubscriptionsInput{Namespaces: []string{ns}, OrderBy:
subscription.OrderByID, Order: "DESC"}), assert err is nil, assert
len(list.Items) == 2, and assert list.Items[0].ID > list.Items[1].ID to validate
reverse ordering for the sort by ID path.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 48ad4689-20b3-4d37-b480-a681c7f976d3

📥 Commits

Reviewing files that changed from the base of the PR and between 3a6e7bc and 7e65b3d.

⛔ Files ignored due to path filters (1)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
📒 Files selected for processing (14)
  • api/spec/packages/aip/src/subscriptions/operations.tsp
  • api/v3/api.gen.go
  • api/v3/handlers/subscriptions/list.go
  • openmeter/billing/validators/customer/customer.go
  • openmeter/billing/worker/subscriptionsync/reconciler/reconciler.go
  • openmeter/customer/httpdriver/customer.go
  • openmeter/productcatalog/subscription/http/get.go
  • openmeter/subscription/list.go
  • openmeter/subscription/repo/subscriptionrepo.go
  • openmeter/subscription/service/service_test.go
  • openmeter/subscription/state.go
  • openmeter/subscription/validators/customer/validator.go
  • openmeter/subscription/validators/subscription/validator.go
  • openmeter/subscription/workflow/service/subscription.go
✅ Files skipped from review due to trivial changes (1)
  • openmeter/customer/httpdriver/customer.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • openmeter/billing/validators/customer/customer.go
  • openmeter/productcatalog/subscription/http/get.go
  • openmeter/subscription/validators/subscription/validator.go
  • api/v3/api.gen.go
  • openmeter/subscription/repo/subscriptionrepo.go
  • openmeter/subscription/list.go

Comment on lines +97 to +105
if params.Sort != nil {
sort, err := request.ParseSortBy(*params.Sort)
if err != nil {
return ListSubscriptionsRequest{}, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
{Field: "sort", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
})
}
req.OrderBy = subscription.OrderBy(sort.Field)
req.Order = sort.Order.ToSortxOrder()

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 | 🟠 Major | ⚡ Quick win

Validate sort field against the documented allow-list before setting OrderBy.

Right now any parsed field is cast into subscription.OrderBy. That can accept unsupported values even though the API contract documents only id, active_from, and active_to. It’s safer to reject unknown sort fields here with 400.

Suggested patch
 import (
 	"context"
+	"fmt"
 	"net/http"
@@
 			// Sort
 			if params.Sort != nil {
 				sort, err := request.ParseSortBy(*params.Sort)
 				if err != nil {
 					return ListSubscriptionsRequest{}, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
 						{Field: "sort", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
 					})
 				}
+
+				switch sort.Field {
+				case "id", "active_from", "active_to":
+					// supported
+				default:
+					err := fmt.Errorf("unsupported sort field: %s", sort.Field)
+					return ListSubscriptionsRequest{}, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
+						{Field: "sort", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
+					})
+				}
+
 				req.OrderBy = subscription.OrderBy(sort.Field)
 				req.Order = sort.Order.ToSortxOrder()
 			}

As per coding guidelines: "The declared API should be accurate, in parity with the actual implementation, and easy to understand for the user."

📝 Committable suggestion

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

Suggested change
if params.Sort != nil {
sort, err := request.ParseSortBy(*params.Sort)
if err != nil {
return ListSubscriptionsRequest{}, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
{Field: "sort", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
})
}
req.OrderBy = subscription.OrderBy(sort.Field)
req.Order = sort.Order.ToSortxOrder()
if params.Sort != nil {
sort, err := request.ParseSortBy(*params.Sort)
if err != nil {
return ListSubscriptionsRequest{}, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
{Field: "sort", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
})
}
switch sort.Field {
case "id", "active_from", "active_to":
// supported
default:
err := fmt.Errorf("unsupported sort field: %s", sort.Field)
return ListSubscriptionsRequest{}, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
{Field: "sort", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
})
}
req.OrderBy = subscription.OrderBy(sort.Field)
req.Order = sort.Order.ToSortxOrder()
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/v3/handlers/subscriptions/list.go` around lines 97 - 105, When handling
params.Sort after calling request.ParseSortBy, validate that sort.Field is one
of the allowed fields (the documented allow-list: the subscription sort keys
such as id, active_from, active_to) before assigning req.OrderBy =
subscription.OrderBy(sort.Field); if the field is not in that allow-list return
a 400 BadRequest using apierrors.NewBadRequestError with an InvalidParameters
entry for "sort" (similar to the existing parse error path). Update the logic
around params.Sort / request.ParseSortBy / req.OrderBy to perform this explicit
whitelist check and only map to subscription.OrderBy for supported values.

@borosr
borosr force-pushed the feat/subscription-filter branch from 7e65b3d to e151e52 Compare May 4, 2026 14:37

@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.

♻️ Duplicate comments (1)
openmeter/subscription/validators/subscription/validator.go (1)

235-241: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

page still not forwarded to List — paginator stuck on page 1

The closure captures page but never includes it in ListSubscriptionsInput, so CollectAll would endlessly refetch the first page for any customer with a large subscription set.

🐛 Quick fix
 return v.Config.QueryService.List(ctx, subscription.ListSubscriptionsInput{
     CustomerID:     &filter.FilterULID{FilterString: filter.FilterString{Eq: &customerID}},
     Namespaces:     []string{namespace},
     ActiveInPeriod: &timeutil.StartBoundedPeriod{From: starting},
+    Page:           page,
 })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/subscription/validators/subscription/validator.go` around lines 235
- 241, The paginator closure captures pagination.Page but never forwards it to
the list call, causing CollectAll to repeatedly fetch page 1; update the call
inside pagination.NewPaginator so v.Config.QueryService.List receives the
current page (forward pagination.Page from the closure into
subscription.ListSubscriptionsInput—e.g., populate the input's pagination/page
field or token) so the List method can fetch the requested page; modify the
closure that builds subscription.ListSubscriptionsInput and pass page through to
the List invocation used by pagination.CollectAll.
🧹 Nitpick comments (1)
api/spec/packages/aip/src/subscriptions/operations.tsp (1)

56-71: 💤 Low value

Nicely structured filter model — and plan_key made it in! 🎉

The plan_key addition via Common.StringFieldFilterExact addresses the request from @tothandras. One thing to be aware of: using StringFieldFilterExact for status means no enum constraint at the spec/codegen level. An API consumer passing a typo (e.g., filter[status][eq]=activ) won't get a type-error — it'll pass validation all the way to the repo where it quietly becomes a no-op.

If there's a Common.EnumFieldFilter or similar in the shared types, it'd be worth using that here. Otherwise, at minimum, consider whether the generated handler validates the status string against the known SubscriptionStatus enum before forwarding it downstream.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/spec/packages/aip/src/subscriptions/operations.tsp` around lines 56 - 71,
The ListSubscriptionsParamsFilter uses status?: Common.StringFieldFilterExact
which allows any string and can silently accept typos; change the filter to use
a shared enum-aware filter (e.g., Common.EnumFieldFilter) for the status field
if available, otherwise add explicit validation of the status value against the
SubscriptionStatus enum in the request handler that processes
ListSubscriptionsParamsFilter (so the handler checks status before forwarding to
the repo) to ensure invalid values are rejected or normalized.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@openmeter/subscription/validators/subscription/validator.go`:
- Around line 235-241: The paginator closure captures pagination.Page but never
forwards it to the list call, causing CollectAll to repeatedly fetch page 1;
update the call inside pagination.NewPaginator so v.Config.QueryService.List
receives the current page (forward pagination.Page from the closure into
subscription.ListSubscriptionsInput—e.g., populate the input's pagination/page
field or token) so the List method can fetch the requested page; modify the
closure that builds subscription.ListSubscriptionsInput and pass page through to
the List invocation used by pagination.CollectAll.

---

Nitpick comments:
In `@api/spec/packages/aip/src/subscriptions/operations.tsp`:
- Around line 56-71: The ListSubscriptionsParamsFilter uses status?:
Common.StringFieldFilterExact which allows any string and can silently accept
typos; change the filter to use a shared enum-aware filter (e.g.,
Common.EnumFieldFilter) for the status field if available, otherwise add
explicit validation of the status value against the SubscriptionStatus enum in
the request handler that processes ListSubscriptionsParamsFilter (so the handler
checks status before forwarding to the repo) to ensure invalid values are
rejected or normalized.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 23983c7a-2d5e-4555-a8ef-1a0fa1327571

📥 Commits

Reviewing files that changed from the base of the PR and between 7e65b3d and e151e52.

⛔ Files ignored due to path filters (1)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
📒 Files selected for processing (14)
  • api/spec/packages/aip/src/subscriptions/operations.tsp
  • api/v3/api.gen.go
  • api/v3/handlers/subscriptions/list.go
  • openmeter/billing/validators/customer/customer.go
  • openmeter/billing/worker/subscriptionsync/reconciler/reconciler.go
  • openmeter/customer/httpdriver/customer.go
  • openmeter/productcatalog/subscription/http/get.go
  • openmeter/subscription/list.go
  • openmeter/subscription/repo/subscriptionrepo.go
  • openmeter/subscription/service/service_test.go
  • openmeter/subscription/state.go
  • openmeter/subscription/validators/customer/validator.go
  • openmeter/subscription/validators/subscription/validator.go
  • openmeter/subscription/workflow/service/subscription.go
✅ Files skipped from review due to trivial changes (4)
  • openmeter/subscription/validators/customer/validator.go
  • openmeter/subscription/state.go
  • openmeter/subscription/service/service_test.go
  • openmeter/productcatalog/subscription/http/get.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • openmeter/billing/validators/customer/customer.go
  • openmeter/customer/httpdriver/customer.go
  • openmeter/billing/worker/subscriptionsync/reconciler/reconciler.go
  • api/v3/handlers/subscriptions/list.go

Comment thread openmeter/subscription/list.go Resolved
Comment thread api/v3/handlers/subscriptions/list.go Resolved
@borosr
borosr force-pushed the feat/subscription-filter branch from 7144f75 to 4ac331b Compare May 6, 2026 06:29
@borosr
borosr force-pushed the feat/subscription-filter branch from 2c59586 to f7a5665 Compare May 6, 2026 13:30
@borosr
borosr requested a review from tothandras May 7, 2026 13:53
@borosr
borosr force-pushed the feat/subscription-filter branch from f7a5665 to 68ae084 Compare May 11, 2026 08:52
@borosr
borosr force-pushed the feat/subscription-filter branch from 68ae084 to db83bbe Compare May 11, 2026 12:01
@tothandras
tothandras merged commit ef1cc87 into main May 11, 2026
28 checks passed
@tothandras
tothandras deleted the feat/subscription-filter branch May 11, 2026 13:29

This branch was previously deployed

1 inactive deployment
dev — db83bbef Deployed May 11, 2026 by borosr via Migration Checks #14253
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants