Repository navigation
refactor(entitlement): subject-entitlement db linking - #3222
Conversation
📝 WalkthroughWalkthroughRemoves entitlement connector from customer service and shifts entitlement value/access retrieval to the entitlement service in HTTP handlers. Introduces Subject↔Entitlement relations in the Ent schema with migrations, updates adapters to resolve/load Subject/Customer, and updates router/handler wiring. Tests and utilities are updated to pre-create subjects and to wire a subject service. Changes
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
a8d83da to
a73e1b9
Compare
e05afcf to
8b1aa47
Compare
a73e1b9 to
87f9c4d
Compare
8b1aa47 to
8a16af5
Compare
87f9c4d to
726af66
Compare
8a16af5 to
de2457d
Compare
There was a problem hiding this comment.
Actionable comments posted: 15
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
openmeter/entitlement/service/access_test.go (1)
21-28: Handle missing‐subject error in GetAccess
The subject adapter returns aNewGenericNotFoundError("subject not found: …")whenever the subject key doesn’t exist, but inentitlementConnector.GetAccess(entitlement/service/service.go at line 167) we currently let that error bubble up. To satisfy this test’s expectation—which is to return emptyentitlement.Access{}and no error—you’ll need to catch the “not found” error and convert it to an empty result, e.g.:entitlements, err := c.GetEntitlementsOfSubject(ctx, namespace, subjectKey, now) if models.IsNotFoundError(err) { return entitlement.Access{}, nil } if err != nil { return entitlement.Access{}, err } // …map entitlements to Access…• Update
GetAccessinentitlement/service/service.goas shown above.
• Add a companion test for an existing subject with zero entitlements to ensure we return empty access for “no entitlements” as well.api/spec/src/entitlements/entitlements.tsp (1)
325-329: Typo: “THe” → “The”.Public docs—please fix.
- * THe usage period of the entitlement. + * The usage period of the entitlement.openmeter/customer/service/hooks/subject_test.go (1)
339-343: Fix assertion target: subjectService vs subjectAdapter.Asserting the wrong var hides real failures.
- require.NotNilf(t, subjectAdapter, "subject service must not be nil") + require.NotNilf(t, subjectService, "subject service must not be nil")e2e/e2e_test.go (1)
1219-1222: Bug: asserting status on the wrong response variable.Use resp2 (override call) in the assertion.
Apply this diff:
- require.NoError(t, err) - require.Equal(t, http.StatusCreated, resp.StatusCode(), "Invalid status code [response_body=%s]", string(resp.Body)) + require.NoError(t, err) + require.Equal(t, http.StatusCreated, resp2.StatusCode(), "Invalid status code [response_body=%s]", string(resp2.Body))openmeter/server/router/entitlement.go (1)
47-51: ListEntitlementGrants drops query paramsThe method signature accepts params but they aren’t forwarded to the handler, so pagination/ordering filters are ignored.
If supported by the driver, pass them through:
a.meteredEntitlementHandler.ListEntitlementGrants().With(entitlementdriver.ListEntitlementGrantsHandlerParams{ SubjectKey: subjectIdOrKey, EntitlementIdOrFeatureKey: entitlementIdOrFeatureKey, -}).ServeHTTP(w, r) + Params: params, +}).ServeHTTP(w, r)
♻️ Duplicate comments (4)
openmeter/entitlement/metered/balance_test.go (1)
1157-1159: Same: check Subject creation error.Apply the same fail-fast handling here as above.
e2e/productcatalog_test.go (3)
64-67: Apply the same helper for subject_2.- resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_2"}}) - require.Nil(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode()) + ensureSubject(t, ctx, client, "test_customer_subject_2")
104-107: Apply the same helper for abused subject.- resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_abused"}}) - require.Nil(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode()) + ensureSubject(t, ctx, client, "test_customer_subject_abused")
956-959: Apply the same helper for third customer subject.- resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_3"}}) - require.Nil(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode()) + ensureSubject(t, ctx, client, "test_customer_subject_3")
🧹 Nitpick comments (52)
openmeter/entitlement/service/access_test.go (1)
43-49: Create subject before entitlement—correct for hard link; DRY this across tests.
Extract a tiny helper to reduce duplication and improve readability across subtests.test/customer/testenv.go (1)
106-109: Reuse a Single Mock Publisher in TestEnvWe’ve verified that
eventbus.NewMock(t)is being called twice intest/customer/testenv.go(once for the entitlement registry at line 90 and once for the customer service at line 108). Defining onepublishervariable and reusing it simplifies test setup and ensures consistent event ordering.Suggested changes:
• Near the top of
NewTestEnv(before building the entitlement registry), add:publisher := eventbus.NewMock(t)• In the entitlement registry initialization (around line 90), update:
- Publisher: eventbus.NewMock(t), + Publisher: publisher,• In the customer service initialization (around lines 106–109), update:
- customerService, err := customerservice.New(customerservice.Config{ - Adapter: customerAdapter, - Publisher: eventbus.NewMock(t), - }) + customerService, err := customerservice.New(customerservice.Config{ + Adapter: customerAdapter, + Publisher: publisher, + })This refactor is optional but recommended to make your tests easier to maintain.
openmeter/entitlement/repository.go (1)
84-85: Prefer a proper field doc comment for SubjectKey (and clarify error semantics).Inline trailing comments don’t show up well in Go doc. Also, consider stating what happens when resolution fails (e.g., subject not found).
- SubjectKey string `json:"subjectKey"` // Note: Adapter will resolve this to SubjectID when creating in DB + // SubjectKey will be resolved by the adapter to the persisted subject_id on create. + // Resolution must fail if the subject does not exist. + SubjectKey string `json:"subjectKey"`openmeter/entitlement/service/scheduling_test.go (1)
25-52: Stabilize error assertions by removing reliance on validation order.This test expects a specific error before feature/subject existence is checked. To avoid future brittleness, either create the feature/subject upfront or assert error contains the message substring instead of full equality.
-assert.EqualError(t, err, "activeTo and activeFrom are not supported in CreateEntitlement") +assert.ErrorContains(t, err, "activeTo and activeFrom are not supported")e2e/entitlement_test.go (2)
37-44: Factor repeated “ensure subject exists” into a helper.Same upsert block appears 3x; extract to reduce duplication and keep tests consistent.
-// ensure subject exists -{ - resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{ - api.SubjectUpsert{Key: subject}, - }) - require.NoError(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode()) -} +ensureSubject(t, ctx, client, subject)Add once (outside these ranges) in this file:
func ensureSubject(t *testing.T, ctx context.Context, client *api.ClientWithResponses, key string) { t.Helper() resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{ api.SubjectUpsert{Key: key}, }) require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode(), "upsert subject failed [response_body=%s]", string(resp.Body)) }Also applies to: 205-213, 295-303
115-115: Fix format string usage to print response body.Use string(resp.Body) to avoid printing byte slices verbatim in error messages.
-require.Equal(t, http.StatusCreated, resp.StatusCode(), "Invalid status code [response_body=%s]", resp.Body) +require.Equal(t, http.StatusCreated, resp.StatusCode(), "Invalid status code [response_body=%s]", string(resp.Body))Also applies to: 279-279, 381-381
api/spec/src/entitlements/entitlements.tsp (1)
361-368: Align EntitlementBoolean with other models and avoid period fields leakage.If boolean entitlements should not expose currentUsagePeriod/usagePeriod, omit them like metered does. Otherwise, keep as-is. This change would be a breaking API tweak in v1—consider doing it only in v2.
model EntitlementBoolean { type: EntitlementType.boolean; ...OmitProperties< EntitlementBooleanCreateInputs, "type" | "metadata" | "usagePeriod" | "featureKey" | "featureId" >; - ...OmitProperties<EntitlementSharedFields, "type">; + ...OmitProperties<EntitlementSharedFields, "type" | "currentUsagePeriod" | "usagePeriod">; }openmeter/customer/service/hooks/subject_test.go (1)
352-355: LGTM: updated Customer service config. Also fix adjacent assertion target.Minor copy-paste: assert customerService instead of subjectAdapter.
customerService, err := customerservice.New(customerservice.Config{ Adapter: customerAdapter, Publisher: publisher, }) -require.NoErrorf(t, err, "initializing subject service must not fail") -require.NotNilf(t, subjectAdapter, "subject service must not be nil") +require.NoErrorf(t, err, "initializing customer service must not fail") +require.NotNilf(t, customerService, "customer service must not be nil")tools/migrate/entitlement_test.go (1)
1918-2256: Great coverage; add missing-case where migration must create Subject and tighten FK assertion
- Consider adding a case where an entitlement’s subject_key has no pre-existing Subject row; verify migration creates the Subject and backfills subject_id accordingly.
- The FK check with require.Contains(err.Error(), "foreign key") can be brittle. Prefer checking the SQLSTATE 23503 (foreign_key_violation).
Example additions:
@@ func TestEntitlementSubjectIdMigration(t *testing.T) { @@ - // Happy path - single subject per entitlement + // Happy path - single subject per entitlement entId1 := ulid.Make() @@ subId3 := ulid.Make() + // Entitlement whose subject does not exist pre-migration (should be created by migration) + entId4 := ulid.Make() + missingSubjectKey := "subject_missing" @@ action: func(t *testing.T, db *sql.DB) { @@ // 3. Create entitlements (without subject_id column yet) @@ + // Entitlement with non-existing subject (migration should create it) + _, err = db.Exec(` + INSERT INTO entitlements ( + namespace, id, created_at, updated_at, entitlement_type, + feature_key, feature_id, subject_key + ) + VALUES ('default', $1, NOW(), NOW(), 'METERED', 'feat_1', $2, $3)`, + entId4.String(), featId.String(), missingSubjectKey, + ) + require.NoError(t, err) @@ { // After our migration version: 20250818093933, direction: directionUp, action: func(t *testing.T, db *sql.DB) { @@ + // Verify subject was created and subject_id backfilled for entId4 + var subjectId4, subjectKey4 string + require.NoError(t, db.QueryRow(` + SELECT e.subject_id, s.key + FROM entitlements e + JOIN subjects s ON s.id = e.subject_id + WHERE e.id = $1 + `, entId4.String()).Scan(&subjectId4, &subjectKey4)) + require.Equal(t, missingSubjectKey, subjectKey4) @@ - require.Error(t, err, "should enforce foreign key constraint") - require.Contains(t, err.Error(), "foreign key", "error should mention foreign key constraint") + require.Error(t, err, "should enforce foreign key constraint") + // Prefer SQLSTATE check when available (pgx) + // if pgErr, ok := err.(*pgconn.PgError); ok { + // require.Equal(t, "23503", pgErr.Code) + // }Or keep the current assertion and additionally assert err != nil with a short explanatory comment.
api/spec/src/entitlements/v2/grants.tsp (2)
33-40: Add subject filter for parity with customer and feature filters.Operationally useful for admin list to filter by subject as well.
Apply:
@query(#{ explode: true }) customer?: ULIDOrExternalKey[], + /** + * Filtering by multiple subjects (either by ID or key). + * + * Usage: `?subject=subject-1&subject=subject-2` + */ + @query(#{ explode: true }) + subject?: ULIDOrExternalKey[],
46-49: Clarify/encode precedence when both page and limit/offset are sent.You include both QueryPagination and QueryLimitOffset. Either enforce mutual exclusivity (preferred) or explicitly document that page takes precedence and limit/offset are ignored when page is present.
Apply:
/** - * If page is provided that takes precedence and the paginated response is returned. + * If `page` is provided it takes precedence; `limit`/`offset` are ignored. */Optionally model as two operation overloads instead of mixing both query shapes.
api/spec/src/entitlements/v2/customer.tsp (3)
47-52: Pagination shape overlap (page vs limit/offset).Same concern as Grants: clarify precedence or make the two shapes mutually exclusive.
- ...OpenMeter.QueryPagination, - ...OpenMeter.QueryLimitOffset, + ...OpenMeter.QueryPagination, // When provided, limit/offset are ignored. + ...OpenMeter.QueryLimitOffset,
164-167: Unnecessary explode on scalar query parameter.explode is redundant for a single DateTime param; drop it.
- @query(#{ explode: true }) time?: DateTime, + @query time?: DateTime,
197-205: Nit: refine parameter docs.
- “Windowsize” → “Window size”.
- Specify that windowTimeZone expects an IANA TZ identifier.
- /** - * Windowsize - */ + /** + * Window size. + */ @query windowSize: OpenMeter.WindowSize, /** - * The timezone used when calculating the windows. + * The timezone (IANA TZ, e.g., "UTC", "America/Los_Angeles") used when calculating the windows. */ @query windowTimeZone?: string = "UTC",openmeter/ent/schema/subject.go (1)
61-61: Verify and enforce cascade delete on Subject→Entitlement edge– In
ent/schema/entitlement.go(lines 105–110), thesubjectedge is defined without anyOnDeleteannotation:edge.From("subject", Subject.Type). Ref("entitlements"). Field("subject_id"). Required(). Unique(). Immutable(),– Because there is a
DeleteSubjecthandler (inopenmeter/subject/httphandler/subject.go), deleting a subject today would leave orphaned entitlements or fail due to referential constraints.– To ensure entitlements are cleaned up automatically, update that edge to include:
edge.From("subject", Subject.Type). Ref("entitlements"). Field("subject_id"). Required(). Unique(). Immutable(). + Annotations(entsql.Annotation{OnDelete: entsql.Cascade}),– If in your domain subjects truly must never be deleted, add a comment or documentation to record that invariant instead of enabling cascade.
tools/migrate/migrations/20250818093933_entitlement-subject-id.down.sql (1)
1-2: Make the down migration idempotent by adding IF EXISTS
To handle partial rollouts/rollbacks safely, wrap both the constraint and column drops inIF EXISTS. Verified that the FK name in the up migration (tools/migrate/migrations/20250818093933_entitlement-subject-id.up.sql, line 41) is exactlyentitlements_subjects_entitlements.At tools/migrate/migrations/20250818093933_entitlement-subject-id.down.sql (lines 1–2):
-ALTER TABLE "entitlements" DROP CONSTRAINT "entitlements_subjects_entitlements", DROP COLUMN "subject_id"; +ALTER TABLE "entitlements" + DROP CONSTRAINT IF EXISTS "entitlements_subjects_entitlements", + DROP COLUMN IF EXISTS "subject_id";test/subscription/scenario_firstofmonth_test.go (1)
154-160: Subject precreation is good; consider making it idempotent or unique-per-test to avoid flakiness.If this test reuses a DB or is rerun, the unique (namespace,key) constraint can fail. Either use a unique key per test or an upsert/ignore-duplicate pattern.
-_, err = tDeps.SubjectService.Create(ctx, subject.CreateInput{ - Namespace: namespace, - Key: "subject_1", -}) -require.NoError(t, err) +subjKey := "subject_1" // or fmt.Sprintf("subject_%s", t.Name()) +_, err = tDeps.SubjectService.Create(ctx, subject.CreateInput{ + Namespace: namespace, + Key: subjKey, +}) +require.NoError(t, err)openmeter/entitlement/metered/balance_test.go (1)
561-563: Don’t swallow errors creating the Subject; fail fast on real failures.Ignoring the error can mask setup issues and lead to hard-to-debug test failures later.
-ctx := context.Background() -_, _ = deps.dbClient.Subject.Create().SetNamespace(namespace).SetKey("subject1").Save(ctx) +ctx := context.Background() +if _, err := deps.dbClient.Subject.Create(). + SetNamespace(namespace).SetKey("subject1").Save(ctx); err != nil { + t.Fatalf("failed to create subject: %v", err) +}openmeter/entitlement/metered/lateevents_test.go (1)
226-228: Validate Subject creation instead of ignoring the error.Keeps the test deterministic and surfaces setup issues early.
-// ensure subject exists for SubjectKey used in entitlement -_, _ = deps.dbClient.Subject.Create().SetNamespace(namespace).SetKey("subject1").Save(ctx) +// ensure subject exists for SubjectKey used in entitlement +if _, err := deps.dbClient.Subject.Create(). + SetNamespace(namespace).SetKey("subject1").Save(ctx); err != nil { + t.Fatalf("failed to create subject: %v", err) +}api/spec/src/entitlements/v2/main.tsp (2)
21-21: Fix typo in noteChange “should will use” to “should use”, and prefer consistent wording.
Apply:
-// NOTE: Public types, operationIDs and friendlyNames of versioned packages should will use the version suffix. +// NOTE: Public types, operation IDs, and friendly names of versioned packages should use the version suffix.
3-4: Consider dropping legacy OpenAPI import/using if only OpenAPI3 is usedIf you don’t rely on @typespec/openapi, remove it to avoid confusion.
Apply if safe:
-import "@typespec/openapi"; import "@typespec/openapi3"; @@ -using TypeSpec.OpenAPI; +// using TypeSpec.OpenAPI; // Not needed when emitting OpenAPI3 onlyAlso applies to: 16-16
test/subscription/scenario_editcancel_test.go (2)
109-115: Avoid duplicate subject-creation boilerplate; extract a helper.
Refactor to a small helper to DRY creation and improve failure context.- // Third, let's create the subjects first - _, err = tDeps.SubjectService.Create(ctx, subject.CreateInput{ - Namespace: namespace, - Key: "subject_1", - }) - require.NoError(t, err) + // Third, let's create the subjects first + ensureSubject(t, ctx, tDeps.SubjectService, namespace, "subject_1")Add once near top of the file (outside the changed range):
func ensureSubject(t *testing.T, ctx context.Context, svc subject.Service, namespace, key string) { t.Helper() _, err := svc.Create(ctx, subject.CreateInput{Namespace: namespace, Key: key}) require.NoError(t, err, "create subject %q", key) }
137-144: Same DRY helper for looped subject creation.- // Create subject first - subjectKey := fmt.Sprintf("subject_%d", i+2) - _, err := tDeps.SubjectService.Create(ctx, subject.CreateInput{ - Namespace: namespace, - Key: subjectKey, - }) - require.NoError(t, err) + // Create subject first + subjectKey := fmt.Sprintf("subject_%d", i+2) + ensureSubject(t, ctx, tDeps.SubjectService, namespace, subjectKey)e2e/productcatalog_test.go (1)
33-37: Make Upsert status assertion robust and remove repetition.
Some servers return 201 on first upsert; accept 200 or 201 and wrap in a helper.- resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_1"}}) - require.Nil(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode()) + ensureSubject(t, ctx, client, "test_customer_subject_1")Add once near top of the file:
func ensureSubject(t *testing.T, ctx context.Context, client *api.ClientWithResponses, key string) { t.Helper() resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: key}}) require.Nil(t, err, "upsert subject %q", key) require.Contains(t, []int{http.StatusOK, http.StatusCreated}, resp.StatusCode(), "status for subject %q", key) }openmeter/subscription/testutils/service.go (1)
43-61: New SubjectService in dependencies struct is appropriate.
Consider a short doc comment on the field to clarify intended usage in tests.type SubscriptionDependencies struct { @@ - SubjectService subject.Service + // SubjectService exposes subject ops to tests (creation, hooks, etc.). + SubjectService subject.Serviceopenmeter/customer/httpdriver/handler.go (1)
34-34: Nit: prefer name “entitlementConnector”; optionally guard against nil in New.
Improves clarity since the type is entitlement.Connector; a fast-fail helps wiring safety.type handler struct { service customer.Service - entitlementService entitlement.Connector + entitlementConnector entitlement.Connector subscriptionService subscription.Service namespaceDecoder namespacedriver.NamespaceDecoder options []httptransport.HandlerOption } func New( namespaceDecoder namespacedriver.NamespaceDecoder, service customer.Service, subscriptionService subscription.Service, - entitlementService entitlement.Connector, + entitlementConnector entitlement.Connector, options ...httptransport.HandlerOption, ) Handler { - return &handler{ + // Optional: fail fast on miswiring + if entitlementConnector == nil { + panic("entitlement connector must not be nil") + } + return &handler{ service: service, subscriptionService: subscriptionService, namespaceDecoder: namespaceDecoder, - entitlementService: entitlementService, + entitlementConnector: entitlementConnector, options: options, } }Also applies to: 53-55, 60-60
openmeter/ent/schema/entitlement.go (1)
48-50: SubjectID field looks correct; add an index for query paths.Char(26) matches ULID length and Immutable is fine. Add an index on (namespace, subject_id) to avoid regressions as code shifts to subject_id-based lookups.
Apply:
func (Entitlement) Indexes() []ent.Index { return []ent.Index{ index.Fields("namespace", "id"), index.Fields("namespace", "subject_key"), + index.Fields("namespace", "subject_id"), index.Fields("namespace", "id", "subject_key"), + index.Fields("namespace", "id", "subject_id"), index.Fields("namespace", "feature_id", "id"), index.Fields("namespace", "current_usage_period_end"), // Index for collecting entitlements with due resets index.Fields("current_usage_period_end", "deleted_at"), index.Fields("created_at", "id").Unique(), } }openmeter/ent/db/subject_create.go (1)
267-282: Connecting existing Entitlements sets subject_id only; verify subject_key consistency.With both subject_key and subject_id present, connecting here updates only subject_id. Ensure upstream writes keep subject_key aligned or plan to deprecate it to avoid drift.
If you must keep them in sync temporarily, consider a write-path hook that asserts/updates subject_key from the resolved Subject key when subject_id is set (non-generated code).
tools/migrate/migrations/20250818093933_entitlement-subject-id.up.sql (1)
40-41: FK choice is OK; consider DEFERRABLE INITIALLY DEFERRED if large datasets.Not required, but can ease backfills in edge cases. Optional.
openmeter/subscription/testutils/customer.go (1)
82-91: Make subject pre-creation idempotent for repeated test runs.If a subject already exists, Create may fail on unique constraints. Prefer Upsert or ignore “already exists” errors to keep tests resilient.
Example:
- _, err := a.subjectService.Create(context.Background(), subject.CreateInput{ + _, err := a.subjectService.Create(context.Background(), subject.CreateInput{ Namespace: ExampleCreateCustomerInput.Namespace, Key: subjectKey, }) if err != nil { - t.Fatalf("failed to create subject %s: %v", subjectKey, err) + // Optionally ignore unique violation / already-exists here. + t.Fatalf("failed to create subject %s: %v", subjectKey, err) }If an Upsert API exists, switch to it here.
openmeter/entitlement/adapter/entitlement_test.go (3)
31-31: Global mutex around Schema.Create likely unnecessary; consider simplifying.Each test uses an isolated DB; the extra mutex adds serialization and can hide t.Parallel opportunities. If races aren’t observed, drop the mutex or scope it only where truly shared.
Also applies to: 83-89
381-391: Potential ordering flakiness: tie-breakers rely on ID/CreatedAt.The spec sorts by current period end, then created_at, then id. Since many values are identical across the 10 entitlements, ordering may incidentally rely on ULID monotonicity. If CI flakiness appears, seed distinct CurrentUsagePeriodEnd per item or assert by set equality per page.
Also applies to: 392-411, 414-440
525-547: Add a default branch to the type switch to catch new/unsupported types.Ensures future additions fail fast with a clear message.
switch got.EntitlementType { case entitlement.EntitlementTypeMetered: typed, err := meteredentitlement.ParseFromGenericEntitlement(got) require.NoError(t, err) require.Equal(t, subj.Key, typed.GenericProperties.SubjectKey) require.Equal(t, ns, typed.GenericProperties.Subject.Namespace) require.NotNil(t, typed.GenericProperties.Customer) require.Contains(t, typed.GenericProperties.Customer.UsageAttribution.SubjectKeys, subj.Key) case entitlement.EntitlementTypeStatic: typed, err := staticentitlement.ParseFromGenericEntitlement(got) require.NoError(t, err) require.Equal(t, subj.Key, typed.GenericProperties.SubjectKey) require.Equal(t, ns, typed.GenericProperties.Subject.Namespace) require.NotNil(t, typed.GenericProperties.Customer) require.Contains(t, typed.GenericProperties.Customer.UsageAttribution.SubjectKeys, subj.Key) case entitlement.EntitlementTypeBoolean: typed, err := booleanentitlement.ParseFromGenericEntitlement(got) require.NoError(t, err) require.Equal(t, subj.Key, typed.GenericProperties.SubjectKey) require.Equal(t, ns, typed.GenericProperties.Subject.Namespace) require.NotNil(t, typed.GenericProperties.Customer) require.Contains(t, typed.GenericProperties.Customer.UsageAttribution.SubjectKeys, subj.Key) + default: + t.Fatalf("unsupported entitlement type: %s", got.EntitlementType) }openmeter/customer/httpdriver/customer.go (1)
343-345: Fix handler description and operation name.Aligns tracing/metrics and self-documentation.
-// GetCustomerEntitlementValue returns a handler for getting a customer. +// GetCustomerEntitlementValue returns a handler for getting a customer's entitlement value. @@ - httptransport.AppendOptions( + httptransport.AppendOptions( h.options, - httptransport.WithOperationName("getCustomer"), + httptransport.WithOperationName("getCustomerEntitlementValue"), )...,Also applies to: 399-403
openmeter/ent/db/entitlement/entitlement.go (1)
265-268: Ordering by subject_id is fine; ensure data-path queries use the new index.If not already present, add a DB index on entitlements(subject_id) to keep ORDER BY and WHERE filters fast under load.
e2e/e2e_test.go (4)
821-821: Swap testify.Equal args for clearer failure messages (expected, actual).No functional change; improves diagnostics.
Apply this diff:
- require.Equal(t, metered.SubjectKey, subjectKey) + require.Equal(t, subjectKey, metered.SubjectKey)- require.Equal(t, metered.SubjectKey, subject2) + require.Equal(t, subject2, metered.SubjectKey)- require.Equal(t, metered.SubjectKey, subject) + require.Equal(t, subject, metered.SubjectKey)Also applies to: 1172-1172, 1230-1230
27-36: DRY: factor “ensure subject exists” into a helper.Reduces repetition and keeps assertions consistent across tests.
You can add a helper (outside these ranges):
func ensureSubject(t *testing.T, client *api.ClientWithResponses, key string, displayName *string) { t.Helper() resp, err := client.UpsertSubjectWithResponse(context.Background(), api.UpsertSubjectJSONRequestBody{ api.SubjectUpsert{Key: key, DisplayName: displayName}, }) require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode()) }Then replace the repeated blocks with:
ensureSubject(t, client, "customer-1", nil) // or ensureSubject(t, client, randSubjectKey, lo.ToPtr("Credit Test Subject"))Also applies to: 82-91, 160-169, 223-232, 423-432, 852-861, 909-915, 1146-1151, 1199-1205
1039-1045: Typo in comment.“Ingore events” → “Ingest events”.
Apply this diff:
- // Ingore events + // Ingest events
1234-1236: Comment contradicts assertion.You assert 1 item; update comment accordingly.
Apply this diff:
- // should return 2 entitlements for subject for feature + // should return 1 entitlement for subject for featureopenmeter/entitlement/entitlement.go (1)
339-345: Prefer pointer type for Subject to honor omitempty and avoid copying.Use *subject.Subject for consistency with Customer and to ensure zero/absent values aren’t serialized inadvertently.
Apply this diff:
- SubjectKey string `json:"subjectKey,omitempty"` - Subject subject.Subject `json:"subject,omitempty"` - Customer *customer.Customer `json:"customer,omitempty"` + SubjectKey string `json:"subjectKey,omitempty"` + Subject *subject.Subject `json:"subject,omitempty"` + Customer *customer.Customer `json:"customer,omitempty"`openmeter/ent/db/entitlement_query.go (2)
783-811: Skip zero-value subject IDs in batch loaderDefensive filter prevents an unnecessary IN ('') and avoids oddities with partially-migrated rows.
func (_q *EntitlementQuery) loadSubject(ctx context.Context, query *SubjectQuery, nodes []*Entitlement, init func(*Entitlement), assign func(*Entitlement, *Subject)) error { ids := make([]string, 0, len(nodes)) nodeids := make(map[string][]*Entitlement) for i := range nodes { - fk := nodes[i].SubjectID + fk := nodes[i].SubjectID + if fk == "" { + continue + } if _, ok := nodeids[fk]; !ok { ids = append(ids, fk) } nodeids[fk] = append(nodeids[fk], nodes[i]) }
176-184: Minor: consider WithSubject(opts...) overload parityYou added WithSubject(opts ...func(*SubjectQuery)); good. If you plan to support subset selections frequently, consider documenting expected fields to minimize payloads.
openmeter/entitlement/adapter/entitlement.go (4)
119-131: Avoid overshadowing imported package name 'subject'Rename local var to prevent confusion with the imported subject package.
- subject, err := repo.db.Subject.Query(). + subj, err := repo.db.Subject.Query(). Where( db_subject.Key(ent.SubjectKey), db_subject.Namespace(ent.Namespace), ). Only(ctx) if err != nil { return nil, fmt.Errorf("failed to resolve subject key %s to subject ID: %w", ent.SubjectKey, err) } @@ - SetSubjectID(subject.ID). // Set the resolved subject ID + SetSubjectID(subj.ID). // Set the resolved subject ID
456-462: Fallback to persisted SubjectKey when edge not loadedPrevents empty SubjectKey if a future caller forgets WithSubject.
- // Get subject key from the subject edge - subjectKey := "" - if e.Edges.Subject != nil { - subjectKey = e.Edges.Subject.Key - } + // Prefer edge value for normalization; fallback to persisted field + subjectKey := e.SubjectKey + if e.Edges.Subject != nil { + subjectKey = e.Edges.Subject.Key + }
505-526: Don’t swallow real DB errors when resolving CustomerIgnore not-found, but propagate other errors. Keeps backward compatibility without hiding outages.
- if err == nil && custEntity != nil { - // Map to domain customer using existing mapper - if mapped, mapErr := customeradapter.CustomerFromDBEntity(*custEntity); mapErr == nil { - ent.Customer = mapped - } - } else if err != nil { - // If not found, we silently ignore to keep backward compatibility - _ = err - } + if db.IsNotFound(err) { + // ignore + } else if err != nil { + return nil, err + } else if custEntity != nil { + if mapped, mapErr := customeradapter.CustomerFromDBEntity(*custEntity); mapErr == nil { + ent.Customer = mapped + } + }
335-336: Consistent WithSubject across read paths — niceEnsures mapping logic always has the subject edge available. Watch for N+1s from per-entity customer lookups; consider batch-resolving customers by subjectKey in future.
Also applies to: 641-642, 714-716, 854-855, 881-886
openmeter/ent/db/subject_update.go (1)
191-271: Generated code caveatIf these files are regenerated by ent, local guards may be lost. Prefer enforcing via ent schema (Required edges) and/or hooks/mutators to block illegal clears.
Also applies to: 464-561
openmeter/ent/db/mutation.go (4)
33187-33190: Magic capacity; keep in sync.
make([]string, 0, 23)is a brittle magic number. Optional: factor into a const or omit capacity (low impact).
33780-33783: Magic capacity; optional tidy.
edges := make([]string, 0, 6)is non-functional; consider a const for maintainability.
33843-33847: RemovedEdges capacity nit (optional).Same capacity comment as above; functional behavior OK.
33893-33897: ClearedEdges capacity nit (optional).Same capacity comment; behavior OK.
openmeter/server/router/entitlement.go (1)
126-127: Align path placeholders in comments ({customerId} vs {customerIdOrKey})V2 comments mix both forms; pick one per OpenAPI and update for consistency.
If {customerIdOrKey} is intended, apply:
-// (GET /api/v2/customers/{customerId}/access) +// (GET /api/v2/customers/{customerIdOrKey}/access) -// (GET /api/v2/customers/{customerId}/entitlements/{featureKey}/value) +// (GET /api/v2/customers/{customerIdOrKey}/entitlements/{featureKey}/value) -// (GET /api/v2/customers/{customerId}/entitlements/{featureKey}/history) +// (GET /api/v2/customers/{customerIdOrKey}/entitlements/{featureKey}/history) -// (POST /api/v2/customers/{customerId}/entitlements/{featureKey}/reset) +// (POST /api/v2/customers/{customerIdOrKey}/entitlements/{featureKey}/reset)Also applies to: 175-177, 185-187, 191-193
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled
You can enable these sources in your CodeRabbit configuration.
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (62)
api/spec/src/cloud/main.tsp(1 hunks)api/spec/src/entitlements/customer.tsp(0 hunks)api/spec/src/entitlements/entitlements.tsp(2 hunks)api/spec/src/entitlements/v2/customer.tsp(1 hunks)api/spec/src/entitlements/v2/entitlements.tsp(1 hunks)api/spec/src/entitlements/v2/grants.tsp(1 hunks)api/spec/src/entitlements/v2/main.tsp(1 hunks)api/spec/src/main.tsp(1 hunks)app/common/customer.go(1 hunks)e2e/e2e_test.go(25 hunks)e2e/entitlement_test.go(3 hunks)e2e/productcatalog_test.go(4 hunks)openmeter/customer/httpdriver/customer.go(3 hunks)openmeter/customer/httpdriver/handler.go(3 hunks)openmeter/customer/service.go(0 hunks)openmeter/customer/service/customer.go(0 hunks)openmeter/customer/service/hooks/subject_test.go(1 hunks)openmeter/customer/service/service.go(1 hunks)openmeter/ent/db/client.go(2 hunks)openmeter/ent/db/entitlement.go(8 hunks)openmeter/ent/db/entitlement/entitlement.go(7 hunks)openmeter/ent/db/entitlement/where.go(3 hunks)openmeter/ent/db/entitlement_create.go(7 hunks)openmeter/ent/db/entitlement_query.go(9 hunks)openmeter/ent/db/entitlement_update.go(2 hunks)openmeter/ent/db/migrate/schema.go(3 hunks)openmeter/ent/db/mutation.go(20 hunks)openmeter/ent/db/runtime.go(1 hunks)openmeter/ent/db/subject.go(2 hunks)openmeter/ent/db/subject/subject.go(3 hunks)openmeter/ent/db/subject/where.go(2 hunks)openmeter/ent/db/subject_create.go(3 hunks)openmeter/ent/db/subject_query.go(6 hunks)openmeter/ent/db/subject_update.go(5 hunks)openmeter/ent/schema/entitlement.go(2 hunks)openmeter/ent/schema/subject.go(2 hunks)openmeter/entitlement/adapter/entitlement.go(21 hunks)openmeter/entitlement/adapter/entitlement_test.go(7 hunks)openmeter/entitlement/driver/parser.go(1 hunks)openmeter/entitlement/entitlement.go(3 hunks)openmeter/entitlement/metered/balance_test.go(2 hunks)openmeter/entitlement/metered/lateevents_test.go(1 hunks)openmeter/entitlement/repository.go(1 hunks)openmeter/entitlement/service/access_test.go(5 hunks)openmeter/entitlement/service/scheduling_test.go(7 hunks)openmeter/entitlement/service/utils_test.go(3 hunks)openmeter/server/router/credit.go(1 hunks)openmeter/server/router/entitlement.go(1 hunks)openmeter/server/router/router.go(1 hunks)openmeter/subscription/testutils/customer.go(3 hunks)openmeter/subscription/testutils/service.go(5 hunks)test/app/stripe/testenv.go(1 hunks)test/app/testenv.go(1 hunks)test/billing/suite.go(1 hunks)test/customer/testenv.go(1 hunks)test/subscription/scenario_editaligned_test.go(2 hunks)test/subscription/scenario_editcancel_test.go(3 hunks)test/subscription/scenario_entinnextphase_test.go(2 hunks)test/subscription/scenario_firstofmonth_test.go(2 hunks)tools/migrate/entitlement_test.go(1 hunks)tools/migrate/migrations/20250818093933_entitlement-subject-id.down.sql(1 hunks)tools/migrate/migrations/20250818093933_entitlement-subject-id.up.sql(1 hunks)
💤 Files with no reviewable changes (3)
- openmeter/customer/service.go
- openmeter/customer/service/customer.go
- api/spec/src/entitlements/customer.tsp
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-03-07T12:17:43.129Z
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
Applied to files:
openmeter/entitlement/metered/lateevents_test.gotest/subscription/scenario_entinnextphase_test.goopenmeter/entitlement/metered/balance_test.goopenmeter/entitlement/adapter/entitlement_test.go
📚 Learning: 2025-04-20T11:15:07.499Z
Learnt from: chrisgacsal
PR: openmeterio/openmeter#2692
File: openmeter/productcatalog/plan/adapter/mapping.go:64-74
Timestamp: 2025-04-20T11:15:07.499Z
Learning: In the OpenMeter codebase, Ent's edge methods ending in "OrErr" (like AddonsOrErr()) only return NotLoadedError when the edge wasn't loaded, and cannot return DB errors. Simple err != nil checks are sufficient for these methods.
Applied to files:
openmeter/ent/db/entitlement.go
🧬 Code graph analysis (42)
openmeter/entitlement/repository.go (1)
openmeter/ent/db/entitlement/where.go (1)
SubjectKey(110-112)
openmeter/entitlement/metered/lateevents_test.go (3)
openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/schema/subject.go (5)
Subject(15-17)Subject(20-38)Subject(41-46)Subject(49-56)Subject(59-72)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Subject(636-645)
test/subscription/scenario_entinnextphase_test.go (2)
openmeter/subject/service.go (1)
CreateInput(43-49)openmeter/ent/db/subject/where.go (2)
Namespace(69-71)Key(74-76)
e2e/entitlement_test.go (1)
api/api.gen.go (2)
UpsertSubjectJSONRequestBody(8889-8889)SubjectUpsert(6624-6646)
openmeter/server/router/credit.go (2)
openmeter/server/router/router.go (1)
Router(217-242)api/api.gen.go (1)
ListGrantsV2Params(8724-8763)
test/subscription/scenario_editaligned_test.go (1)
openmeter/subject/service.go (1)
CreateInput(43-49)
test/subscription/scenario_editcancel_test.go (3)
openmeter/subject/service.go (1)
CreateInput(43-49)api/api.gen.go (2)
Customer(2188-2238)CustomerUsageAttribution(2373-2376)openmeter/customer/customer.go (2)
CreateCustomerInput(209-212)CustomerMutate(68-78)
test/subscription/scenario_firstofmonth_test.go (1)
openmeter/subject/service.go (1)
CreateInput(43-49)
openmeter/ent/db/subject_create.go (3)
openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)openmeter/ent/db/entitlement/entitlement.go (3)
Table(79-79)Columns(125-150)FieldID(19-19)openmeter/ent/db/subject/subject.go (5)
Table(34-34)EntitlementsTable(36-36)Columns(45-54)EntitlementsColumn(41-41)FieldID(16-16)
openmeter/entitlement/driver/parser.go (3)
api/api.gen.go (2)
EntitlementBooleanType(2666-2666)EntitlementType(3212-3212)openmeter/ent/db/entitlement/entitlement.go (1)
EntitlementType(184-184)openmeter/entitlement/entitlement.go (1)
EntitlementType(296-296)
test/app/stripe/testenv.go (3)
openmeter/customer/adapter.go (1)
Adapter(10-14)openmeter/meter/adapter/adapter.go (1)
Adapter(46-49)openmeter/watermill/eventbus/eventbus.go (1)
Publisher(61-73)
openmeter/ent/db/subject/where.go (4)
openmeter/ent/schema/subject.go (5)
Subject(15-17)Subject(20-38)Subject(41-46)Subject(49-56)Subject(59-72)openmeter/ent/db/predicate/predicate.go (2)
Subject(261-261)Entitlement(159-159)openmeter/ent/db/entitlement/entitlement.go (2)
Table(79-79)FieldID(19-19)openmeter/ent/db/subject/subject.go (4)
Table(34-34)FieldID(16-16)EntitlementsTable(36-36)EntitlementsColumn(41-41)
openmeter/ent/schema/entitlement.go (2)
openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/schema/subject.go (5)
Subject(15-17)Subject(20-38)Subject(41-46)Subject(49-56)Subject(59-72)
test/billing/suite.go (1)
openmeter/watermill/eventbus/eventbus.go (1)
Publisher(61-73)
openmeter/entitlement/service/scheduling_test.go (1)
openmeter/subject/service.go (1)
CreateInput(43-49)
test/customer/testenv.go (1)
openmeter/watermill/eventbus/eventbus.go (2)
Publisher(61-73)NewMock(150-162)
openmeter/entitlement/service/access_test.go (1)
openmeter/subject/service.go (1)
CreateInput(43-49)
openmeter/customer/service/service.go (1)
openmeter/watermill/eventbus/eventbus.go (1)
Publisher(61-73)
openmeter/entitlement/metered/balance_test.go (2)
openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/schema/subject.go (5)
Subject(15-17)Subject(20-38)Subject(41-46)Subject(49-56)Subject(59-72)
openmeter/ent/db/entitlement_query.go (7)
openmeter/ent/db/subject_query.go (1)
SubjectQuery(22-33)openmeter/ent/db/client.go (1)
SubjectClient(6799-6801)openmeter/ent/db/entitlement/entitlement.go (5)
Table(79-79)FieldID(19-19)SubjectTable(116-116)SubjectColumn(121-121)FieldSubjectID(43-43)openmeter/ent/db/subject/subject.go (2)
Table(34-34)FieldID(16-16)openmeter/ent/db/entitlement.go (2)
Entitlement(21-75)Entitlement(155-178)openmeter/ent/db/entitlement/where.go (3)
SubjectID(115-117)IDIn(30-32)ID(15-17)openmeter/ent/db/subject/where.go (2)
IDIn(29-31)ID(14-16)
openmeter/ent/db/migrate/schema.go (3)
openmeter/ent/db/entitlement/entitlement.go (1)
Columns(125-150)openmeter/ent/db/customer/customer.go (2)
Columns(103-123)SubjectsTable(73-73)openmeter/ent/db/subject/subject.go (1)
EntitlementsTable(36-36)
openmeter/ent/db/client.go (4)
openmeter/ent/db/subject_query.go (1)
SubjectQuery(22-33)openmeter/ent/db/entitlement/entitlement.go (4)
Table(79-79)FieldID(19-19)SubjectTable(116-116)SubjectColumn(121-121)openmeter/ent/db/subject/subject.go (4)
Table(34-34)FieldID(16-16)EntitlementsTable(36-36)EntitlementsColumn(41-41)openmeter/ent/db/entitlement_query.go (1)
EntitlementQuery(27-43)
openmeter/ent/schema/subject.go (2)
openmeter/ent/db/entitlement.go (2)
Entitlement(21-75)Entitlement(155-178)openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)
openmeter/customer/httpdriver/handler.go (2)
openmeter/entitlement/connector.go (1)
Connector(52-77)pkg/framework/transport/httptransport/options.go (1)
HandlerOption(19-21)
openmeter/ent/db/entitlement/where.go (4)
openmeter/ent/db/entitlement.go (2)
Entitlement(21-75)Entitlement(155-178)openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)openmeter/ent/db/predicate/predicate.go (2)
Entitlement(159-159)Subject(261-261)openmeter/ent/db/entitlement/entitlement.go (5)
FieldSubjectID(43-43)Table(79-79)FieldID(19-19)SubjectTable(116-116)SubjectColumn(121-121)
openmeter/ent/db/entitlement/entitlement.go (1)
openmeter/ent/db/subject/subject.go (3)
OrderOption(82-82)Table(34-34)FieldID(16-16)
openmeter/customer/httpdriver/customer.go (4)
openmeter/customer/customer.go (2)
GetCustomerInput(248-255)CustomerID(98-98)pkg/models/errors.go (1)
NewGenericConflictError(68-70)pkg/clock/clock.go (1)
Now(14-21)openmeter/ent/db/ent.go (1)
NotFoundError(284-286)
openmeter/subscription/testutils/customer.go (3)
openmeter/subscription/testutils/db.go (1)
DBDeps(15-19)openmeter/customer/service/service.go (3)
Service(12-16)New(35-45)Config(18-21)openmeter/subject/service.go (1)
CreateInput(43-49)
openmeter/ent/db/subject_update.go (5)
openmeter/ent/db/entitlement.go (2)
Entitlement(21-75)Entitlement(155-178)openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)openmeter/ent/db/mutation.go (1)
SubjectMutation(46098-46117)openmeter/ent/db/entitlement/entitlement.go (3)
Table(79-79)Columns(125-150)FieldID(19-19)openmeter/ent/db/subject/subject.go (5)
Table(34-34)EntitlementsTable(36-36)Columns(45-54)EntitlementsColumn(41-41)FieldID(16-16)
app/common/customer.go (2)
openmeter/app/adapter.go (1)
Adapter(10-14)openmeter/watermill/eventbus/eventbus.go (1)
Publisher(61-73)
openmeter/entitlement/adapter/entitlement.go (7)
openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/schema/subject.go (5)
Subject(15-17)Subject(20-38)Subject(41-46)Subject(49-56)Subject(59-72)openmeter/ent/db/subject/where.go (5)
Key(74-76)Namespace(69-71)ID(14-16)DisplayName(79-81)StripeCustomerID(84-86)openmeter/ent/db/entitlement/where.go (4)
SubjectKey(110-112)Namespace(70-72)ID(15-17)SubjectID(115-117)openmeter/ent/db/customer/where.go (1)
HasSubjectsWith(1330-1339)openmeter/ent/db/customersubjects_query.go (1)
CustomerSubjectsQuery(21-32)openmeter/customer/adapter/entitymapping.go (1)
CustomerFromDBEntity(11-71)
openmeter/ent/db/subject.go (5)
openmeter/ent/db/entitlement.go (3)
Entitlements(511-511)Entitlement(21-75)Entitlement(155-178)openmeter/ent/db/ent.go (1)
NotLoadedError(330-332)openmeter/ent/schema/subject.go (5)
Subject(15-17)Subject(20-38)Subject(41-46)Subject(49-56)Subject(59-72)openmeter/ent/db/entitlement_query.go (1)
EntitlementQuery(27-43)openmeter/ent/db/client.go (1)
NewSubjectClient(6804-6806)
openmeter/entitlement/adapter/entitlement_test.go (4)
openmeter/entitlement/repository.go (2)
EntitlementRepo(31-78)CreateEntitlementRepoInputs(80-100)openmeter/customer/customer.go (2)
CreateCustomerInput(209-212)CustomerMutate(68-78)openmeter/subject/service.go (1)
CreateInput(43-49)openmeter/entitlement/entitlement.go (2)
EntitlementType(296-296)GenericProperties(322-348)
openmeter/ent/db/subject_query.go (6)
openmeter/ent/db/entitlement/entitlement.go (4)
OrderOption(208-208)Table(79-79)FieldID(19-19)FieldSubjectID(43-43)openmeter/ent/db/subject/subject.go (5)
OrderOption(82-82)Table(34-34)FieldID(16-16)EntitlementsTable(36-36)EntitlementsColumn(41-41)openmeter/ent/db/entitlement_query.go (1)
EntitlementQuery(27-43)openmeter/ent/db/client.go (1)
EntitlementClient(4803-4805)openmeter/ent/db/entitlement.go (3)
Entitlements(511-511)Entitlement(21-75)Entitlement(155-178)openmeter/ent/db/entitlement/where.go (2)
ID(15-17)SubjectID(115-117)
e2e/productcatalog_test.go (1)
api/api.gen.go (2)
UpsertSubjectJSONRequestBody(8889-8889)SubjectUpsert(6624-6646)
openmeter/ent/db/mutation.go (4)
openmeter/ent/db/entitlement/where.go (1)
SubjectID(115-117)openmeter/ent/db/entitlement/entitlement.go (2)
FieldSubjectID(43-43)EdgeSubject(77-77)openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/db/subject/subject.go (1)
EdgeEntitlements(32-32)
openmeter/ent/db/entitlement.go (4)
openmeter/ent/db/entitlement/where.go (1)
SubjectID(115-117)openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/db/entitlement/entitlement.go (4)
FieldID(19-19)FieldNamespace(21-21)FieldSubjectKey(41-41)FieldSubjectID(43-43)openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)
openmeter/server/router/entitlement.go (4)
openmeter/server/router/router.go (1)
Router(217-242)openmeter/customer/httpdriver/customer.go (1)
GetCustomerEntitlementValueParams(336-339)api/api.gen.go (5)
GetCustomerEntitlementValueParams(7958-7960)ListCustomerEntitlementsV2Params(8604-8632)ListCustomerEntitlementGrantsV2Params(8635-8663)GetCustomerEntitlementValueV2Params(8682-8684)GetCustomerEntitlementHistoryV2Params(8666-8679)openmeter/customer/customer.go (1)
CustomerIDOrKey(131-134)
openmeter/subscription/testutils/service.go (2)
openmeter/subscription/testutils/customer.go (1)
NewSubjectService(42-56)openmeter/streaming/testutils/streaming.go (1)
MockStreamingConnector(32-35)
openmeter/ent/db/entitlement_create.go (4)
openmeter/ent/schema/subject.go (5)
Subject(15-17)Subject(20-38)Subject(41-46)Subject(49-56)Subject(59-72)openmeter/ent/db/entitlement/where.go (2)
ID(15-17)SubjectID(115-117)openmeter/ent/db/entitlement/entitlement.go (6)
Table(79-79)SubjectTable(116-116)Columns(125-150)SubjectColumn(121-121)FieldID(19-19)FieldSubjectID(43-43)openmeter/ent/db/subject/subject.go (3)
Table(34-34)Columns(45-54)FieldID(16-16)
openmeter/entitlement/entitlement.go (3)
openmeter/ent/db/entitlement/where.go (2)
SubjectKey(110-112)ID(15-17)openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)api/api.gen.go (2)
Subject(6596-6621)Customer(2188-2238)
openmeter/ent/db/subject/subject.go (1)
openmeter/ent/db/entitlement/entitlement.go (3)
OrderOption(208-208)Table(79-79)FieldID(19-19)
⏰ 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: E2E
- GitHub Check: Quickstart
- GitHub Check: Build
- GitHub Check: Test
- GitHub Check: Lint
- GitHub Check: Code Generators
- GitHub Check: Analyze (go)
| @friendlyName("EntitlementCustomerFields") | ||
| model EntitlementCustomerFields { | ||
| /** | ||
| * The identifier key unique to the customer | ||
| */ | ||
| @example("customer-1") | ||
| customerKey?: string; | ||
|
|
||
| /** | ||
| * The identifier unique to the customer | ||
| */ | ||
| @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") | ||
| customerId: ULID; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Make customerId optional to avoid blocking transitional states.
Given ongoing subject→customer linking, requiring customerId may be too strict for entities without an associated customer yet. Suggest making it optional.
- customerId: ULID;
+ customerId?: ULID;If you require at least one of customerId or customerKey, consider documenting/enforcing that invariant downstream.
📝 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.
| @friendlyName("EntitlementCustomerFields") | |
| model EntitlementCustomerFields { | |
| /** | |
| * The identifier key unique to the customer | |
| */ | |
| @example("customer-1") | |
| customerKey?: string; | |
| /** | |
| * The identifier unique to the customer | |
| */ | |
| @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") | |
| customerId: ULID; | |
| } | |
| @friendlyName("EntitlementCustomerFields") | |
| model EntitlementCustomerFields { | |
| /** | |
| * The identifier key unique to the customer | |
| */ | |
| @example("customer-1") | |
| customerKey?: string; | |
| /** | |
| * The identifier unique to the customer | |
| */ | |
| @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") | |
| customerId?: ULID; | |
| } |
🤖 Prompt for AI Agents
In api/spec/src/entitlements/v2/entitlements.tsp around lines 27 to 40, the
model currently requires customerId which blocks transitional states where an
entity may only have customerKey; make customerId optional by changing its
declaration to be optional (customerId?: ULID) so records can exist without an
associated ULID during linking; if your domain needs at least one of customerId
or customerKey, add a comment and enforce that invariant downstream (validation
or runtime check).
| // Create subject | ||
| _, err = deps.subjectService.Create(ctx, subject.CreateInput{ | ||
| Namespace: "ns1", | ||
| Key: "subject1", | ||
| }) | ||
| assert.Nil(t, err) | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Pre-create all referenced subjects (subject2, subject3) to prevent flakiness and align with subject_id linking.
Within this suite you only upsert subject1. Tests below use subject2 and subject3 but don’t create them, which may fail once subject existence is strictly enforced.
Apply this diff to extend the setup in the “annotations” test and keep it local to that subtest:
// Create subject
_, err = deps.subjectService.Create(ctx, subject.CreateInput{
Namespace: "ns1",
Key: "subject1",
})
assert.Nil(t, err)
+ // Also create additional subjects used in subtests
+ _, err = deps.subjectService.Create(ctx, subject.CreateInput{
+ Namespace: "ns1",
+ Key: "subject2",
+ })
+ assert.Nil(t, err)
+
+ _, err = deps.subjectService.Create(ctx, subject.CreateInput{
+ Namespace: "ns1",
+ Key: "subject3",
+ })
+ assert.Nil(t, err)Optionally, extract a small helper to DRY subject creation across cases.
Also applies to: 145-151, 192-198, 252-258, 314-320, 369-375
🤖 Prompt for AI Agents
In openmeter/entitlement/service/scheduling_test.go around lines 73 to 79 (and
similarly at 145-151, 192-198, 252-258, 314-320, 369-375), the test setup only
creates subject1 but later assertions reference subject2 and subject3; update
each setup block to pre-create subject2 and subject3 using
deps.subjectService.Create with the same Namespace ("ns1") and appropriate Keys
("subject2", "subject3") so subject_id linking is stable and tests are not
flaky; optionally factor a small helper (e.g., createSubjects(ctx, deps, "ns1",
"subject1", "subject2", "subject3")) and call it in each subtest to keep code
DRY.
| // (POST /api/v2/customers/{customerIdOrKey}/entitlements) | ||
| func (a *Router) CreateCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey string) { | ||
| unimplemented.CreateCustomerEntitlementV2(w, r, customerIdOrKey) | ||
| } |
There was a problem hiding this comment.
Fix compile error: missing import for unimplemented V2 handlers
These routes call unimplemented.*V2 but the package isn’t imported.
Apply this diff to add the import:
import (
"net/http"
"github.com/openmeterio/openmeter/api"
customerdriver "github.com/openmeterio/openmeter/openmeter/customer/httpdriver"
entitlementdriver "github.com/openmeterio/openmeter/openmeter/entitlement/driver"
+ unimplemented "github.com/openmeterio/openmeter/openmeter/server/router/unimplemented"
)Also applies to: 141-143, 146-149, 152-155, 158-161, 164-167, 170-173, 185-188, 191-194
| // (GET /api/v2/customers/{customerId}/entitlements/{featureKey}/value) | ||
| func (a *Router) GetCustomerEntitlementValueV2(w http.ResponseWriter, r *http.Request, customerIdOrKey string, featureKey string, params api.GetCustomerEntitlementValueV2Params) { | ||
| a.customerHandler.GetCustomerEntitlementValue().With(customerdriver.GetCustomerEntitlementValueParams{ | ||
| CustomerIDOrKey: customerIdOrKey, | ||
| FeatureKey: featureKey, | ||
| }).ServeHTTP(w, r) | ||
| } |
There was a problem hiding this comment.
Don’t silently ignore the v2 “time” query param
GetCustomerEntitlementValueV2 accepts params with Time but drops it. Either plumb it through or explicitly reject when provided to avoid surprising behavior.
Suggested guard (uses the unimplemented handler until the driver supports Time):
func (a *Router) GetCustomerEntitlementValueV2(w http.ResponseWriter, r *http.Request, customerIdOrKey string, featureKey string, params api.GetCustomerEntitlementValueV2Params) {
- a.customerHandler.GetCustomerEntitlementValue().With(customerdriver.GetCustomerEntitlementValueParams{
- CustomerIDOrKey: customerIdOrKey,
- FeatureKey: featureKey,
- }).ServeHTTP(w, r)
+ if params.Time != nil {
+ // Avoid silently ignoring the time parameter until supported.
+ unimplemented.GetCustomerEntitlementValueV2(w, r, customerIdOrKey, featureKey, params)
+ return
+ }
+ a.customerHandler.GetCustomerEntitlementValue().With(customerdriver.GetCustomerEntitlementValueParams{
+ CustomerIDOrKey: customerIdOrKey,
+ FeatureKey: featureKey,
+ }).ServeHTTP(w, r)
}📝 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.
| // (GET /api/v2/customers/{customerId}/entitlements/{featureKey}/value) | |
| func (a *Router) GetCustomerEntitlementValueV2(w http.ResponseWriter, r *http.Request, customerIdOrKey string, featureKey string, params api.GetCustomerEntitlementValueV2Params) { | |
| a.customerHandler.GetCustomerEntitlementValue().With(customerdriver.GetCustomerEntitlementValueParams{ | |
| CustomerIDOrKey: customerIdOrKey, | |
| FeatureKey: featureKey, | |
| }).ServeHTTP(w, r) | |
| } | |
| // (GET /api/v2/customers/{customerId}/entitlements/{featureKey}/value) | |
| func (a *Router) GetCustomerEntitlementValueV2(w http.ResponseWriter, r *http.Request, customerIdOrKey string, featureKey string, params api.GetCustomerEntitlementValueV2Params) { | |
| if params.Time != nil { | |
| // Avoid silently ignoring the time parameter until supported. | |
| unimplemented.GetCustomerEntitlementValueV2(w, r, customerIdOrKey, featureKey, params) | |
| return | |
| } | |
| a.customerHandler.GetCustomerEntitlementValue().With(customerdriver.GetCustomerEntitlementValueParams{ | |
| CustomerIDOrKey: customerIdOrKey, | |
| FeatureKey: featureKey, | |
| }).ServeHTTP(w, r) | |
| } |
🤖 Prompt for AI Agents
In openmeter/server/router/entitlement.go around lines 176 to 182, the v2
handler accepts a params.Time but currently drops it; either propagate it into
the driver call or explicitly reject requests that supply Time. Update the
method to check params.Time: if params.Time is non-nil return an appropriate
error response (e.g., 400 with a clear message or use the unimplemented handler)
or include Time in the GetCustomerEntitlementValueParams struct when calling the
driver so the driver receives the requested time; ensure the chosen behavior is
consistent with other v2 endpoints and add a short comment explaining why Time
is rejected or forwarded.
| "github.com/openmeterio/openmeter/openmeter/productcatalog" | ||
| "github.com/openmeterio/openmeter/openmeter/productcatalog/plan" | ||
| pcsubscription "github.com/openmeterio/openmeter/openmeter/productcatalog/subscription" | ||
| "github.com/openmeterio/openmeter/openmeter/subject" |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Pre-creating Subject aligns tests with subject-linked entitlements — good change
Import and creation are correct, namespace/key match the customer UsageAttribution. This removes the flakiness from missing subjects.
Optionally verify other tests using SubjectKeys also pre-create subjects:
Also applies to: 135-142
🏁 Script executed:
#!/bin/bash
# List files that set SubjectKeys but may not create a Subject in the same file
rg -nP --type=go -C3 'SubjectKeys:\s*\[\]string\{.*\}' test | tee /tmp/subjectkeys_usages.txt
awk -F: '{print $1}' /tmp/subjectkeys_usages.txt | sort -u | while read -r f; do
if rg -n 'SubjectService\.Create\(' "$f" >/dev/null; then
echo "OK: $f"
else
echo "MISSING subject creation in: $f"
fi
doneLength of output: 360
I’ll re-run the verification without relying on tee to ensure we correctly identify all test files using SubjectKeys and check for corresponding SubjectService.Create calls:
🏁 Script executed:
#!/bin/bash
# Find test files that initialize SubjectKeys and verify they pre-create a Subject
rg -nP 'SubjectKeys:\s*\[\]string\{' test | cut -d: -f1 | sort -u | while read -r f; do
if rg -q 'SubjectService\.Create\(' "$f"; then
echo "OK: $f"
else
echo "MISSING subject creation in: $f"
fi
doneLength of output: 2348
Add missing SubjectService.Create invocations in tests using SubjectKeys
Several tests define a SubjectKeys array but never call SubjectService.Create, which can lead to flaky failures due to missing subjects. Please add a pre-creation step for each listed file (e.g., at the top of TestMain or in the individual test’s setup) such as:
subject, err := testEnv.SubjectService.Create(ctx, subject.CreateRequest{
Namespace: "customer",
Key: "UsageAttribution",
})
require.NoError(t, err)Files requiring this addition:
- test/app/custominvoicing/invocing_test.go
- test/app/stripe/invoice_test.go
- test/billing/adapter_test.go
- test/billing/invoice_test.go
- test/billing/subscription_test.go
- test/billing/suite.go
- test/customer/customer.go
Once these calls are in place, rerun the suite to confirm removal of flakiness.
🤖 Prompt for AI Agents
In test/subscription/scenario_entinnextphase_test.go around line 15 and in the
other listed test files, several tests declare SubjectKeys but never create
those subjects before use; add a pre-creation step that calls the test
environment SubjectService.Create for each SubjectKey (e.g., create with
Namespace "customer" and the corresponding Key) in TestMain or each test’s
setup, and assert success with require.NoError to ensure subjects exist before
running the tests to prevent flaky failures.
| WITH new_subjects AS ( | ||
| INSERT INTO subjects (id, key, namespace, created_at) | ||
| SELECT DISTINCT ON (e.subject_key, e.namespace) | ||
| om_func_generate_ulid(), | ||
| e.subject_key, | ||
| e.namespace, | ||
| e.created_at | ||
| FROM entitlements e | ||
| WHERE e.subject_id IS NULL | ||
| RETURNING id, key, namespace | ||
| ) |
There was a problem hiding this comment.
Bug: inserting new subjects omits required updated_at (likely NOT NULL).
Subjects.updated_at is required in schema; this INSERT will fail unless DB-level defaults exist. Set updated_at explicitly.
Apply:
-WITH new_subjects AS (
- INSERT INTO subjects (id, key, namespace, created_at)
+WITH new_subjects AS (
+ INSERT INTO subjects (id, key, namespace, created_at, updated_at)
SELECT DISTINCT ON (e.subject_key, e.namespace)
om_func_generate_ulid(),
e.subject_key,
e.namespace,
- e.created_at
+ e.created_at,
+ COALESCE(e.created_at, NOW())
FROM entitlements e
WHERE e.subject_id IS NULL
RETURNING id, key, namespace
)📝 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.
| WITH new_subjects AS ( | |
| INSERT INTO subjects (id, key, namespace, created_at) | |
| SELECT DISTINCT ON (e.subject_key, e.namespace) | |
| om_func_generate_ulid(), | |
| e.subject_key, | |
| e.namespace, | |
| e.created_at | |
| FROM entitlements e | |
| WHERE e.subject_id IS NULL | |
| RETURNING id, key, namespace | |
| ) | |
| WITH new_subjects AS ( | |
| INSERT INTO subjects ( | |
| id, | |
| key, | |
| namespace, | |
| created_at, | |
| updated_at | |
| ) | |
| SELECT DISTINCT ON (e.subject_key, e.namespace) | |
| om_func_generate_ulid(), | |
| e.subject_key, | |
| e.namespace, | |
| e.created_at, | |
| COALESCE(e.created_at, NOW()) | |
| FROM entitlements e | |
| WHERE e.subject_id IS NULL | |
| RETURNING id, key, namespace | |
| ) |
🤖 Prompt for AI Agents
In tools/migrate/migrations/20250818093933_entitlement-subject-id.up.sql around
lines 21-31, the INSERT into subjects omits the required updated_at column
causing the migration to fail; modify the INSERT to include the updated_at
column and set its value explicitly (e.g. use COALESCE(e.updated_at,
e.created_at, now()) or just now() depending on desired semantics) in the SELECT
so the new rows satisfy the NOT NULL constraint.
e9626c4 to
00c563b
Compare
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openmeter/entitlement/adapter/entitlement.go (1)
96-96: Enforce single-active-entitlement invariantThe call to
.First(ctx)in GetActiveEntitlementOfSubjectAt will happily return one of potentially many matching rows, silently violating the invariant that there must be at most one active entitlement per (namespace, subject, feature, overlapping period). We need to enforce this at two levels:• Schema-level (Ent)
– In openmeter/ent/schema/entitlement.go, extendfunc (Entitlement) Indexes()to include a unique index, for example:
go index. Fields("namespace", "subject_id", "feature_key"). // for non-overlapping period enforcement in Postgres: // annotate with an exclusion constraint on tstzrange(current_usage_period_start, current_usage_period_end) Unique(),
– Optionally add a Postgres exclusion constraint to prohibit overlapping active-period ranges.• Runtime-level (adapter)
– In openmeter/entitlement/adapter/entitlement.go’s GetActiveEntitlementOfSubjectAt, replace.First(ctx)with a query that fetches all matches, e.g.:
go results, err := client.Entitlement. Query(). Where( EntitlementNamespaceEQ(namespace), EntitlementSubjectIDEQ(subjectID), EntitlementFeatureIDEQ(featureID), // period overlap predicate... ). All(ctx) if err != nil { return nil, err } switch len(results) { case 0: return nil, ErrNotFound case 1: return results[0], nil default: return nil, fmt.Errorf("multiple active entitlements found for subject %q feature %q", subjectID, featureID) }These changes will guarantee that attempts to create or query more than one active entitlement fail fast, both at the database and in application logic.
♻️ Duplicate comments (7)
openmeter/customer/service/service.go (1)
19-20: Verify repo-wide removal of EntitlementConnector and old Customer service methodsTo prevent build breaks, confirm no lingering references to the removed Config field and methods remain. This mirrors an earlier review note but is still critical.
Run:
#!/bin/bash set -euo pipefail # 1) Stale field references to removed Config field echo ">>> Searching for EntitlementConnector references..." rg -nP --hidden --glob '!**/vendor/**' '\bEntitlementConnector\b' -C3 || true # 2) Stale struct literals passing removed field into customerservice.Config echo ">>> Searching for customerservice.Config literals containing EntitlementConnector..." rg -nP --hidden --glob '!**/vendor/**' 'customerservice\.Config\{[^}]*EntitlementConnector' -C3 || true # 3) Stale usages of removed Customer service methods echo ">>> Searching for removed Customer service methods..." rg -nP --hidden --glob '!**/vendor/**' '\bGetEntitlementValue\b|\bGetCustomerAccess\b' -C3 || trueopenmeter/ent/db/entitlement/where.go (1)
1319-1340: Subject edge generated as M2O unique → enforces one entitlement per subjectThis reflects a Unique() constraint on edge.From("subject") in the schema, making subject_id unique across entitlements. That prevents multiple entitlements per subject (likely unintended). Please remove Unique() on the subject edge and, if needed, enforce business-level uniqueness via a composite index (e.g., namespace+subject_id+feature_id). Regenerate code/migrations after the schema change.
Suggested schema change (outside this file):
*** openmeter/ent/schema/entitlement.go @@ - edge.From("subject", Subject.Type). - Ref("entitlements"). - Field("subject_id"). - Required(). - Unique(). - Immutable(), + edge.From("subject", Subject.Type). + Ref("entitlements"). + Field("subject_id"). + Required(). + Immutable(),Optionally add a composite unique index:
*** openmeter/ent/schema/entitlement.go @@ func (Entitlement) Indexes() []ent.Index { - return nil + return []ent.Index{ + index.Fields("namespace", "subject_id", "feature_id").Unique(), + } }openmeter/ent/db/subject_update.go (4)
124-144: Clearing/removing Entitlements will violate required FK (subject_id) at runtimeEntitlement.subject_id is required/immutable; ClearEntitlements/RemoveEntitlementIDs will attempt to NULL the FK and fail. Block these operations in builder checks to fail fast with a clear error.
Apply checks:
*** In SubjectUpdate.check() func (_u *SubjectUpdate) check() error { if v, ok := _u.mutation.Key(); ok { if err := subject.KeyValidator(v); err != nil { return &ValidationError{Name: "key", err: fmt.Errorf(`db: validator failed for field "Subject.key": %w`, err)} } } + if _u.mutation.EntitlementsCleared() || len(_u.mutation.RemovedEntitlementsIDs()) > 0 { + return fmt.Errorf("cannot clear/remove entitlements: 'subject_id' is required and immutable on Entitlement") + } return nil }*** In SubjectUpdateOne.check() func (_u *SubjectUpdateOne) check() error { if v, ok := _u.mutation.Key(); ok { if err := subject.KeyValidator(v); err != nil { return &ValidationError{Name: "key", err: fmt.Errorf(`db: validator failed for field "Subject.key": %w`, err)} } } + if _u.mutation.EntitlementsCleared() || len(_u.mutation.RemovedEntitlementsIDs()) > 0 { + return fmt.Errorf("cannot clear/remove entitlements: 'subject_id' is required and immutable on Entitlement") + } return nil }
227-271: Runtime FK nulling on Entitlements edge clear/removeThese EdgeSpec clears will try to set entitlements.subject_id = NULL, conflicting with required FK; prevent at check() level as suggested above.
384-404: Clearing/removing Entitlements (single update) has same FK issueSame fix as for SubjectUpdate: disallow at check().
517-561: Single-entity EdgeSpec clears will NULL subject_idWill violate NOT NULL; rely on the added check() guard to avoid this path.
openmeter/ent/db/mutation.go (1)
33126-33130: Fix ClearSubject/ResetSubject symmetry: ensure clearedFields is undone on reset; clear pending set on clear
- Reset should remove
FieldSubjectIDfromclearedFields, otherwise the FK may still be nulled.- Clear should also nil out
m.subjectto override any priorSetSubjectIDin the same mutation.Apply:
func (m *EntitlementMutation) ClearSubject() { m.clearedsubject = true + m.subject = nil m.clearedFields[entitlement.FieldSubjectID] = struct{}{} } @@ func (m *EntitlementMutation) ResetSubject() { m.subject = nil m.clearedsubject = false + delete(m.clearedFields, entitlement.FieldSubjectID) }Run to confirm
clearedFieldsis pre-initialized in the constructor (avoids nil-map writes):#!/bin/bash rg -n -C3 'func newEntitlementMutation\(' openmeter/ent/db/mutation.go rg -n -C2 'newEntitlementMutation' openmeter/ent/db/mutation.go | rg -n 'clearedFields:\s*make\(map\[string\]struct\{\}\)'Also applies to: 33149-33151
🧹 Nitpick comments (23)
openmeter/customer/service/service.go (4)
23-33: Use “nil” instead of “null” in error messages (idiomatic Go)Minor wording fix to match Go terminology.
Apply this diff:
func (c Config) Validate() error { if c.Adapter == nil { - return errors.New("adapter cannot be null") + return errors.New("adapter cannot be nil") } if c.Publisher == nil { - return errors.New("publisher cannot be null") + return errors.New("publisher cannot be nil") } return nil }
12-16: Add doc comment for Service (exported type)Improves discoverability in godoc without changing behavior.
Apply this diff:
+// Service implements customer.Service backed by a customer.Adapter and an eventbus.Publisher. type Service struct { adapter customer.Adapter requestValidatorRegistry customer.RequestValidatorRegistry publisher eventbus.Publisher }
18-21: Add doc comment for Config (exported type)Clarifies required dependencies.
Apply this diff:
+// Config contains the dependencies required to construct a Service. +// Adapter and Publisher must be provided. type Config struct { Adapter customer.Adapter Publisher eventbus.Publisher }
35-45: Document constructor behavior; optional: allow injecting a custom validator registryDoc improves ergonomics; optional enhancement keeps tests/extensibility easy if callers need non-default validators.
Apply this diff to document:
+// New returns a Service configured with a default RequestValidatorRegistry. func New(config Config) (*Service, error) { if err := config.Validate(); err != nil { return nil, err } return &Service{ adapter: config.Adapter, requestValidatorRegistry: customer.NewRequestValidatorRegistry(), publisher: config.Publisher, }, nil }If needed later, consider a functional option to inject a custom registry without expanding Config:
type Option func(*Service) func WithRequestValidatorRegistry(r customer.RequestValidatorRegistry) Option { return func(s *Service) { s.requestValidatorRegistry = r } } // Usage: New(config, WithRequestValidatorRegistry(custom)) func New(config Config, opts ...Option) (*Service, error) { if err := config.Validate(); err != nil { return nil, err } s := &Service{ adapter: config.Adapter, requestValidatorRegistry: customer.NewRequestValidatorRegistry(), publisher: config.Publisher, } for _, opt := range opts { opt(s) } return s, nil }tools/migrate/entitlement_test.go (6)
2024-2102: Consider adding a cross-namespace guard case.Add a subject with the same key in a different namespace before migration to ensure the backfill join keys on (namespace, key) and not just key.
Example snippet to add before entitlement inserts:
_, _ = db.Exec(` INSERT INTO subjects (namespace,id,key,created_at,updated_at) VALUES ('other', $1, 'subject_1', '2024-01-01 00:00:00', NOW()) `, ulid.Make().String())
2103-2106: Optional: check column existence via information_schema for clearer intent.Using information_schema avoids relying on a SELECT error path.
Example:
var x int err := db.QueryRow(` SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'entitlements' AND column_name = 'subject_id'`, ).Scan(&x) require.Error(t, err, "subject_id column should not exist before migration")
2143-2170: Assert SQLSTATE codes instead of error substrings for NOT NULL.Error strings vary; asserting SQLSTATE 23502 is more robust.
Apply this diff within this block:
- require.Error(t, err, "should not allow NULL values in subject_id column") + require.Error(t, err, "should not allow NULL values in subject_id column") + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + require.Equal(t, "23502", pgErr.Code, "expected NOT NULL violation (23502) on subject_id") + }Add imports (outside this hunk):
import ( // ... "errors" "github.com/jackc/pgconn" )
2171-2202: Use SQLSTATE 23503 for foreign key violation.More stable than matching “foreign key” in the message.
Apply this diff:
- require.Error(t, err, "should enforce foreign key constraint") - require.Contains(t, err.Error(), "foreign key", "error should mention foreign key constraint") + require.Error(t, err, "should enforce foreign key constraint") + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + require.Equal(t, "23503", pgErr.Code, "expected FK violation (23503)") + }
2252-2256: Add a down-migration assertion.Mirror earlier tests: migrate down and confirm subject_id is dropped.
Example block to append:
{ version: 20250807075408, direction: directionDown, action: func(t *testing.T, db *sql.DB) { _, err := db.Exec(`SELECT subject_id FROM entitlements LIMIT 1`) require.Error(t, err, "subject_id should be dropped after down migration") }, },
2060-2070: Minor: normalize entitlement_type casing.Elsewhere the code uses "metered" (lowercase) post-202507 schema; keeping consistent casing reduces churn if type becomes an enum.
Also applies to: 2090-2096
test/customer/testenv.go (1)
107-109: Use a single Publisher instance across the test envYou’re creating a second event bus for the customer service; prefer reusing the same Publisher used for the entitlement registry to keep emitted events unified.
Apply within this hunk:
- Adapter: customerAdapter, - Publisher: eventbus.NewMock(t), + Adapter: customerAdapter, + Publisher: publisher,Then, outside this hunk, declare and reuse the Publisher (two small edits):
- After logger initialization (near Line 65):
publisher := eventbus.NewMock(t)
- In EntitlementOptions (near Line 90):
- Publisher: eventbus.NewMock(t), + Publisher: publisher,test/app/testenv.go (1)
95-97: Fragmented Publisher Mocks Spotted – Consider Unifying via InitBillingServiceI noticed three separate
eventbus.NewMock(t)invocations intest/app/testenv.go, which leads to fragmented mock publishers across your tests:
- Line 75:
publisher := eventbus.NewMock(t)- Line 227:
Publisher: eventbus.NewMock(t),- Line 252:
Publisher: eventbus.NewMock(t),To avoid having multiple independent mocks in a single test run, I recommend threading a single
Publisherthrough yourInitBillingServicesetup. For example:type InitBillingServiceInput struct { DBClient *db.Client CustomerService customer.Service AppService app.Service Publisher eventbus.Publisher // optional } func InitBillingService(in InitBillingServiceInput) *BillingService { - // current approach: always creates a new mock - pub := eventbus.NewMock(t) + // reuse provided Publisher or fall back to a new mock + pub := in.Publisher + if pub == nil { + pub = eventbus.NewMock(t) + } bs := &BillingService{ DB: in.DBClient, Customer: in.CustomerService, - Publisher: eventbus.NewMock(t), + Publisher: pub, } // … entitlement registry uses the same pub erInput := EntitlementRegistryInput{ Publisher: pub, // … } bs.entitlementRegistry = NewEntitlementRegistry(erInput) return bs }By passing the same
Publisherinstance, you ensure all components in your test share the same event bus mock, simplifying assertions and avoiding duplicate subscriptions.openmeter/entitlement/adapter/entitlement.go (3)
119-131: Creation: subject resolution needs clearer NotFound semantics.Only(ctx) returns a generic error on missing/duplicate subject. Consider mapping db.IsNotFound(err) to a domain-level error (e.g., subject not found) to return 404/409 deterministically, and keep duplicates as 500. Also consider including namespace in the message for observability.
- subject, err := repo.db.Subject.Query(). + subject, err := repo.db.Subject.Query(). Where( db_subject.Key(ent.SubjectKey), db_subject.Namespace(ent.Namespace), ). Only(ctx) if err != nil { - return nil, fmt.Errorf("failed to resolve subject key %s to subject ID: %w", ent.SubjectKey, err) + if db.IsNotFound(err) { + return nil, fmt.Errorf("subject %q not found in namespace %q: %w", ent.SubjectKey, ent.Namespace, err) + } + return nil, fmt.Errorf("failed to resolve subject %q in namespace %q: %w", ent.SubjectKey, ent.Namespace, err) }
637-645: Upsert path sets SubjectKey/SubjectID even though insert path is logically unreachable.You pre-check existence and error on mismatches, so INSERT shouldn’t happen. Keeping the fields is fine but adds params and column work. Optional: drop SetSubjectKey/SetSubjectID in these Create() stubs to reduce parameter counts and lower conflict payload.
Also applies to: 665-676, 690-699
504-526: Avoid N+1 Customer lookups in entitlement mappingThe
mapEntitlementEntitymethod issues a separate DB query for each entitlement to resolve its Customer via the subjectKey. In list endpoints, this results in one query per item:• At openmeter/entitlement/adapter/entitlement.go:
– Lines 296–298 (loop overres)
– Lines 420–424 (loop overentities)
– Lines 438–442 (loop overpaged.Items)
– Lines 766–768 (loop overres)
– Lines 880–882 (loop overres)Each iteration invokes:
custEntity, err := a.db.Customer.Query()…First(ctx)triggering an N+1 query pattern.
Optional refactor suggestions:
- Before mapping, collect all non-empty
subjectKeyvalues from the page and issue a single query such as:then build acustomers, _ := a.db.Customer.Query(). Where(customerdb.Namespace(namespace)). Where(customerdb.DeletedAtIsNil()). Where(customerdb.HasSubjectsWith(customersubjectsdb.SubjectKeyIn(keys...))). WithSubjects(…). All(ctx)map[string]*customer.Customerand pass it intomapEntitlementEntity.- Or preload the Customer edge with a JOIN/eager-load if supported by your ORM, so that
e.Edges.Customeris populated in the original entitlement query.These changes will dramatically reduce database round-trips on bulk entitlement lookups.
openmeter/customer/httpdriver/customer.go (3)
343-343: Fix comment to reflect handler purpose.-// GetCustomerEntitlementValue returns a handler for getting a customer. +// GetCustomerEntitlementValue returns a handler for getting a customer's entitlement value.
369-392: Subject-key derivation + NotFound→NoAccess mapping — good behavior.Deriving subjectKey from UsageAttribution and translating NotFound to NoAccessValue matches expected semantics.
You fetch the customer twice (arg parsing and handler). To avoid a second read, consider passing subjectKey in the request object or resolving it once in the first phase.
Also applies to: 397-398
401-403: Wrong operation name for tracing/metrics.- httptransport.WithOperationName("getCustomer"), + httptransport.WithOperationName("getCustomerEntitlementValue"),openmeter/ent/db/entitlement_create.go (1)
460-468: Both subject_id field and subject edge are requiredRedundant but safe if SetSubjectID also populates SubjectIDs under the hood. If not, creation could fail later; keep both checks or ensure SetSubjectID updates edge IDs.
openmeter/ent/db/entitlement_query.go (1)
783-811: Guard against empty SubjectID during eager-loadIf legacy rows exist without subject_id (pre-backfill), the loader will query with empty IDs and may raise “unexpected FK” errors. Skip zero-value IDs to harden.
func (_q *EntitlementQuery) loadSubject(ctx context.Context, query *SubjectQuery, nodes []*Entitlement, init func(*Entitlement), assign func(*Entitlement, *Subject)) error { ids := make([]string, 0, len(nodes)) nodeids := make(map[string][]*Entitlement) for i := range nodes { - fk := nodes[i].SubjectID - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) + fk := nodes[i].SubjectID + if fk == "" { + continue + } + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) } if len(ids) == 0 { return nil }openmeter/subscription/testutils/customer.go (1)
82-91: Make subject creation idempotent by deduping and ignoring “already exists” conflictsTo prevent test flakiness when subjects are created in parallel (or retried), de-duplicate the input keys and ignore the unique-constraint violations returned by the subject adapter.
• File: openmeter/subscription/testutils/customer.go
Location: around line 82Suggested changes:
- // Create the subjects first - for _, subjectKey := range ExampleCreateCustomerInput.UsageAttribution.SubjectKeys { - _, err := a.subjectService.Create(context.Background(), subject.CreateInput{ + // Create the subjects first (idempotent) + ctx := context.Background() + for _, subjectKey := range lo.Uniq(ExampleCreateCustomerInput.UsageAttribution.SubjectKeys) { + _, err := a.subjectService.Create(ctx, subject.CreateInput{ Namespace: ExampleCreateCustomerInput.Namespace, Key: subjectKey, }) if err != nil { - t.Fatalf("failed to create subject %s: %v", subjectKey, err) + // Ignore conflicts for keys that already exist + if isAlreadyExistsErr(err) { + continue + } + t.Fatalf("failed to create subject %s: %v", subjectKey, err) } }Add this helper (e.g. at the bottom of the file):
import ( "errors" "openmeter/models" ) // isAlreadyExistsErr returns true if the error represents a unique-constraint violation // from the subject adapter (wrapped as a GenericConflictError). func isAlreadyExistsErr(err error) bool { var gce *models.GenericConflictError if errors.As(err, &gce) { return true } return false }• Deduplicate with
lo.Uniqto avoid repeated Create calls for the same key.
• Detect the conflict by unwrapping into*models.GenericConflictError(the type produced bymodels.NewGenericConflictError) and skip those errors instead of failing.test/app/stripe/testenv.go (2)
57-59: Make Close idempotent; avoid value-receiver copy.Close uses a value receiver and can be called twice; guard with sync.Once and use a pointer receiver.
Apply within this range:
-func (n testEnv) Close() error { - return n.closerFunc() -} +func (n *testEnv) Close() error { + var err error + n.closeOnce.Do(func() { + err = n.closerFunc() + }) + return err +}Also apply outside this range:
// imports import ( "context" "errors" "fmt" "log/slog" "sync" // add "testing" // ... ) // struct field type testEnv struct { // ... stripeAppClient *StripeAppClientMock closeOnce sync.Once // add closerFunc func() error }
206-217: Auto-clean resources with t.Cleanup to prevent leaks in tests.Register Close with t.Cleanup so callers don’t need to remember to defer env.Close().
- return &testEnv{ + env := &testEnv{ app: appService, appstripe: appStripeService, billing: billingService, customer: customerService, fixture: NewFixture(appService, customerService, stripeClientMock, stripeAppClientMock), secret: secretService, closerFunc: closerFunc, stripeClient: stripeClientMock, stripeAppClient: stripeAppClientMock, - }, nil + } + t.Cleanup(func() { _ = env.Close() }) + return env, nil
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled
You can enable these sources in your CodeRabbit configuration.
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (51)
app/common/customer.go(1 hunks)e2e/e2e_test.go(25 hunks)e2e/entitlement_test.go(3 hunks)e2e/productcatalog_test.go(4 hunks)openmeter/customer/httpdriver/customer.go(3 hunks)openmeter/customer/httpdriver/handler.go(3 hunks)openmeter/customer/service.go(0 hunks)openmeter/customer/service/customer.go(0 hunks)openmeter/customer/service/hooks/subject_test.go(1 hunks)openmeter/customer/service/service.go(1 hunks)openmeter/ent/db/client.go(2 hunks)openmeter/ent/db/entitlement.go(8 hunks)openmeter/ent/db/entitlement/entitlement.go(7 hunks)openmeter/ent/db/entitlement/where.go(3 hunks)openmeter/ent/db/entitlement_create.go(7 hunks)openmeter/ent/db/entitlement_query.go(9 hunks)openmeter/ent/db/entitlement_update.go(2 hunks)openmeter/ent/db/migrate/schema.go(3 hunks)openmeter/ent/db/mutation.go(20 hunks)openmeter/ent/db/runtime.go(1 hunks)openmeter/ent/db/subject.go(2 hunks)openmeter/ent/db/subject/subject.go(3 hunks)openmeter/ent/db/subject/where.go(2 hunks)openmeter/ent/db/subject_create.go(3 hunks)openmeter/ent/db/subject_query.go(6 hunks)openmeter/ent/db/subject_update.go(5 hunks)openmeter/ent/schema/entitlement.go(2 hunks)openmeter/ent/schema/subject.go(2 hunks)openmeter/entitlement/adapter/entitlement.go(21 hunks)openmeter/entitlement/adapter/entitlement_test.go(7 hunks)openmeter/entitlement/entitlement.go(3 hunks)openmeter/entitlement/metered/balance_test.go(2 hunks)openmeter/entitlement/metered/lateevents_test.go(1 hunks)openmeter/entitlement/repository.go(1 hunks)openmeter/entitlement/service/access_test.go(5 hunks)openmeter/entitlement/service/scheduling_test.go(7 hunks)openmeter/entitlement/service/utils_test.go(3 hunks)openmeter/server/router/router.go(1 hunks)openmeter/subscription/testutils/customer.go(3 hunks)openmeter/subscription/testutils/service.go(5 hunks)test/app/stripe/testenv.go(1 hunks)test/app/testenv.go(1 hunks)test/billing/suite.go(1 hunks)test/customer/testenv.go(1 hunks)test/subscription/scenario_editaligned_test.go(2 hunks)test/subscription/scenario_editcancel_test.go(3 hunks)test/subscription/scenario_entinnextphase_test.go(2 hunks)test/subscription/scenario_firstofmonth_test.go(2 hunks)tools/migrate/entitlement_test.go(1 hunks)tools/migrate/migrations/20250818093933_entitlement-subject-id.down.sql(1 hunks)tools/migrate/migrations/20250818093933_entitlement-subject-id.up.sql(1 hunks)
💤 Files with no reviewable changes (2)
- openmeter/customer/service.go
- openmeter/customer/service/customer.go
✅ Files skipped from review due to trivial changes (1)
- openmeter/entitlement/repository.go
🚧 Files skipped from review as they are similar to previous changes (33)
- openmeter/ent/db/runtime.go
- e2e/e2e_test.go
- openmeter/entitlement/metered/lateevents_test.go
- e2e/entitlement_test.go
- openmeter/ent/db/entitlement.go
- openmeter/entitlement/service/access_test.go
- openmeter/customer/httpdriver/handler.go
- openmeter/entitlement/service/utils_test.go
- openmeter/ent/db/entitlement/entitlement.go
- tools/migrate/migrations/20250818093933_entitlement-subject-id.down.sql
- openmeter/subscription/testutils/service.go
- openmeter/ent/schema/subject.go
- openmeter/entitlement/metered/balance_test.go
- openmeter/customer/service/hooks/subject_test.go
- openmeter/ent/db/entitlement_update.go
- openmeter/ent/db/subject/where.go
- openmeter/entitlement/service/scheduling_test.go
- test/subscription/scenario_entinnextphase_test.go
- tools/migrate/migrations/20250818093933_entitlement-subject-id.up.sql
- openmeter/ent/db/subject_create.go
- test/subscription/scenario_firstofmonth_test.go
- openmeter/ent/db/subject/subject.go
- openmeter/ent/db/client.go
- openmeter/ent/db/subject_query.go
- test/subscription/scenario_editaligned_test.go
- openmeter/server/router/router.go
- openmeter/ent/schema/entitlement.go
- openmeter/entitlement/entitlement.go
- test/subscription/scenario_editcancel_test.go
- app/common/customer.go
- openmeter/ent/db/migrate/schema.go
- openmeter/ent/db/subject.go
- openmeter/entitlement/adapter/entitlement_test.go
🧰 Additional context used
🧬 Code graph analysis (14)
test/app/stripe/testenv.go (1)
openmeter/meter/adapter/adapter.go (1)
Adapter(46-49)
openmeter/entitlement/adapter/entitlement.go (7)
openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/db/subject/where.go (5)
Key(74-76)Namespace(69-71)ID(14-16)DisplayName(79-81)StripeCustomerID(84-86)openmeter/ent/db/entitlement.go (2)
Entitlement(21-75)Entitlement(155-178)openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)openmeter/ent/db/customer/where.go (1)
HasSubjectsWith(1330-1339)openmeter/ent/db/customersubjects_query.go (1)
CustomerSubjectsQuery(21-32)openmeter/customer/adapter/entitymapping.go (1)
CustomerFromDBEntity(11-71)
test/customer/testenv.go (1)
openmeter/watermill/eventbus/eventbus.go (2)
Publisher(61-73)NewMock(150-162)
openmeter/customer/httpdriver/customer.go (3)
openmeter/customer/customer.go (2)
GetCustomerInput(248-255)CustomerID(98-98)pkg/models/errors.go (1)
NewGenericConflictError(68-70)pkg/clock/clock.go (1)
Now(14-21)
openmeter/ent/db/entitlement/where.go (3)
openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)openmeter/ent/db/predicate/predicate.go (2)
Entitlement(159-159)Subject(261-261)openmeter/ent/db/entitlement/entitlement.go (4)
FieldSubjectID(43-43)Table(79-79)SubjectTable(116-116)SubjectColumn(121-121)
test/billing/suite.go (1)
openmeter/watermill/eventbus/eventbus.go (1)
Publisher(61-73)
openmeter/customer/service/service.go (1)
openmeter/watermill/eventbus/eventbus.go (1)
Publisher(61-73)
test/app/testenv.go (3)
openmeter/customer/adapter.go (1)
Adapter(10-14)openmeter/meter/adapter/adapter.go (1)
Adapter(46-49)openmeter/watermill/eventbus/eventbus.go (1)
Publisher(61-73)
openmeter/ent/db/subject_update.go (6)
openmeter/ent/db/entitlement.go (2)
Entitlement(21-75)Entitlement(155-178)openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)openmeter/ent/db/mutation.go (1)
SubjectMutation(46098-46117)openmeter/ent/db/entitlement/entitlement.go (3)
Table(79-79)Columns(125-150)FieldID(19-19)openmeter/ent/db/subject/subject.go (5)
Table(34-34)EntitlementsTable(36-36)Columns(45-54)EntitlementsColumn(41-41)FieldID(16-16)openmeter/ent/db/migrate/schema.go (1)
EntitlementsTable(1426-1491)
openmeter/ent/db/entitlement_query.go (7)
openmeter/ent/db/subject_query.go (1)
SubjectQuery(22-33)openmeter/ent/db/client.go (1)
SubjectClient(6799-6801)openmeter/ent/db/entitlement/entitlement.go (5)
Table(79-79)FieldID(19-19)SubjectTable(116-116)SubjectColumn(121-121)FieldSubjectID(43-43)openmeter/ent/schema/entitlement.go (5)
Entitlement(20-22)Entitlement(24-31)Entitlement(33-72)Entitlement(74-85)Entitlement(87-120)openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/db/entitlement/where.go (3)
SubjectID(115-117)IDIn(30-32)ID(15-17)openmeter/ent/db/subject/where.go (2)
IDIn(29-31)ID(14-16)
e2e/productcatalog_test.go (1)
api/api.gen.go (2)
UpsertSubjectJSONRequestBody(8889-8889)SubjectUpsert(6624-6646)
openmeter/ent/db/entitlement_create.go (4)
openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/db/entitlement/where.go (2)
ID(15-17)SubjectID(115-117)openmeter/ent/db/entitlement/entitlement.go (6)
Table(79-79)SubjectTable(116-116)Columns(125-150)SubjectColumn(121-121)FieldID(19-19)FieldSubjectID(43-43)openmeter/ent/db/subject/subject.go (3)
Table(34-34)Columns(45-54)FieldID(16-16)
openmeter/subscription/testutils/customer.go (4)
openmeter/subscription/testutils/db.go (1)
DBDeps(15-19)openmeter/customer/service/service.go (3)
Service(12-16)New(35-45)Config(18-21)openmeter/ent/schema/customer.go (5)
Customer(17-19)Customer(21-29)Customer(31-39)Customer(41-54)Customer(56-68)openmeter/subject/service.go (1)
CreateInput(43-49)
openmeter/ent/db/mutation.go (5)
openmeter/ent/db/entitlement/where.go (1)
SubjectID(115-117)openmeter/ent/db/entitlement/entitlement.go (2)
FieldSubjectID(43-43)EdgeSubject(77-77)openmeter/ent/db/subject.go (2)
Subject(17-39)Subject(60-75)openmeter/ent/schema/subject.go (5)
Subject(15-17)Subject(20-38)Subject(41-46)Subject(49-56)Subject(59-72)openmeter/ent/db/subject/subject.go (1)
EdgeEntitlements(32-32)
⏰ 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: Quickstart
- GitHub Check: E2E
- GitHub Check: Code Generators
- GitHub Check: Migration Checks
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Lint
- GitHub Check: Analyze (go)
🔇 Additional comments (40)
openmeter/customer/service/service.go (1)
19-20: LGTM: Config surface simplified and entitlement decoupledAdapter and Publisher-only config is clear and aligns with the PR’s goal of removing the entitlement coupling from the Customer service.
tools/migrate/entitlement_test.go (3)
1919-1934: Good coverage and structure for the new migration test.Clear setup/verify flow, isolates the new subject_id backfill and constraints well.
2113-2141: Backfill assertions look solid.Verifies all three entitlements correctly populated with subject_id after migration.
2203-2251: Valid path checks are good.Positive insert case confirms constraints and backfill coexist with normal writes.
test/billing/suite.go (1)
147-149: No lingering EntitlementConnector wiring for CustomerService – all clearVerified that the
customerservice.Configtype inopenmeter/customer/service/service.goonly definesAdapterandPublisher, and every call site ofcustomerservice.Newacross the repo supplies exactly those two fields. No calls pass anEntitlementConnector, and the Config struct no longer accepts it.• Confirmed
Configstruct shape inopenmeter/customer/service/service.goonly includes:type Config struct { Adapter customer.Adapter Publisher eventbus.Publisher }• Checked all
customerservice.New(...)invocations—none include anEntitlementConnectorkey.
• Any remainingEntitlementConnector:occurrences in tests refer to other services (billing/subscription, entitlement regression), not CustomerService.openmeter/entitlement/adapter/entitlement.go (3)
63-64: Consistent eager-loading of Subject edge — good move.Adding WithSubject() across read paths and routing mapping via repo.mapEntitlementEntity(ctx, …) aligns data shape and prevents downstream nil-edge surprises.
Also applies to: 77-77, 88-88, 109-109, 283-283, 297-297, 335-335, 423-424, 441-441, 714-715, 767-767, 854-854, 881-881
137-139: Set both SubjectKey and SubjectID, then re-query with edge — solid transitional approach.This preserves API compatibility while moving to hard links. Re-querying to populate the edge makes the mapping consistent.
Also applies to: 173-183
309-321: EntitlementQuery method is correctThe Ent codegen uses
Exist(ctx)(notExists(ctx)), as verified across all generated query files underent/db(e.g.EntitlementQuery.Exist(ctx)). No changes are required to avoid compile breaks.openmeter/customer/httpdriver/customer.go (2)
13-13: New imports and service composition — looks correct.entitlement, clock, and models are used appropriately in the new handlers.
Also applies to: 16-16, 20-20
433-445: Customer access via entitlement service — LGTM.Subject-key resolution and delegation to entitlementService.GetAccess are straightforward; conflict errors on missing/ambiguous subject are appropriate.
Also applies to: 449-454
openmeter/ent/db/entitlement/where.go (2)
114-117: Add SubjectID alias predicate — good extensionConvenient equality helper consistent with other fields.
685-749: Full predicate set for subject_id — looks correctCovers the expected operators and mirrors existing patterns.
openmeter/ent/db/entitlement_create.go (4)
140-145: SetSubjectID API — aligns with new FKPublic setter matches other field setters; no issues.
363-367: SetSubject edge helper — OKDelegating to SetSubjectID preserves API symmetry with Feature.
677-693: CreateSpec wires M2O Subject — OKEdge spec and _node.SubjectID assignment follow Feature’s pattern.
940-942: Upsert ignores subject_id — consistent with Immutable()Prevents accidental reassignment of Subject on conflict. Good.
Also applies to: 1381-1383
openmeter/ent/db/entitlement_query.go (6)
21-21: Subject import — neededRequired for query and loader helpers.
38-39: Track withSubject in query state — OKClone() propagation included; consistent with other edges.
186-206: QuerySubject path — correct M2O traversalUses the entitlement table FK and mirrors QueryFeature.
467-476: WithSubject eager-loading — OKOptions pattern consistent; no issues.
556-563: loadedTypes sizing and subject loader invocation — OKIndexing matches added edge; assignment closure correct.
Also applies to: 622-627
844-846: Include subject_id when WithSubject is set — correctEnsures FK is available for assignment.
openmeter/ent/db/subject_update.go (3)
14-17: entitlement import — in useUsed by edge specs; fine.
104-117: AddEntitlements helpers — OKID extraction mirrors other edges; no issues.
364-377: AddEntitlements (single update) — OKParallels bulk update variant; fine.
openmeter/ent/db/mutation.go (8)
31691-31692: New mutation state tracked for Subject — looks goodAdding
subject *stringandclearedsubject boolaligns with how other unique edges are tracked.
33221-33223: Field plumbing for subject_id — correct integrationIncluding
subject_idin Fields(), Field(), and OldField() follows Ent patterns.Also applies to: 33287-33289, 33342-33343
33452-33458: SetField/ResetField paths rely on SetSubjectID/ResetSubjectID fixesGiven SetField delegates to
SetSubjectIDand ResetField toResetSubjectID, the earlier fixes are required to prevent stale clears from nulling the FK.After applying the fixes, please add/adjust tests that exercise: Clear → Set; Set → Clear; Clear → Reset; SetField/ResetField sequences.
Also applies to: 33738-33740
33780-33780: Edge wiring for Subject — LGTMAddedEdges/IDs, ClearedEdges, EdgeCleared, ClearEdge, and ResetEdge correctly expose the Subject edge state.
Also applies to: 33796-33798, 33834-33837, 33910-33912, 33930-33931, 33943-33945, 33969-33971
46098-46117: SubjectMutation edge state for Entitlements — LGTMMaps/flags (
entitlements,removedentitlements,clearedentitlements) mirror Ent’s many-edge mutation pattern.
46514-46522: Entitlements mutation APIs — LGTMAdd/Clear/Remove/Reset implementations look correct.
deleteon a nil map is safe; guard usage is appropriate.Also applies to: 46524-46527, 46529-46532, 46534-46543, 46545-46551, 46553-46559, 46561-46566
46824-46827: Edge introspection for SubjectMutation — LGTMAdd/Removed/Cleared/EdgeCleared/ResetEdge paths correctly reflect the Entitlements edge; omitting it from ClearEdge is consistent with non-unique edges.
Also applies to: 46835-46841, 46847-46850, 46857-46864, 46870-46873, 46880-46883, 46890-46892, 46898-46902
33187-33187: Preallocated capacity is correctThe
make([]string, 0, 23)at openmeter/ent/db/mutation.go:33187 exactly matches the 23fields = append(fields, …)calls in this function, so no reallocation will occur. No changes needed.openmeter/subscription/testutils/customer.go (5)
12-14: LGTM: subject packages correctly imported and scoped.
These imports align with the new subject wiring used below.
34-39: Good DI: subject service wired into test repo.
Keeps customer adapter clean while enabling subject pre-creation in tests.
42-56: Subject service constructor looks solid for tests.
Helper + fatal-on-error is appropriate in test utils.
58-66: Customer service wiring is correct and minimal.
Passing only Adapter and a mock Publisher matches the simplified service config.
76-76: Struct extension is fine.
Embedding customer.Adapter + storing subjectService is a clean approach for test conveniences.test/app/stripe/testenv.go (2)
118-121: Customer service init aligned with entitlement removal.Switching to only Adapter and Publisher matches the PR goal of dropping entitlement wiring from customer service construction here.
118-121: Sanity-check passed: Config shape and stale entitlement wiringAll clear—
customerservice.Confignow exposes onlyAdapterandPublisher, and no call sites pass legacy fields likeEntitlementConnectororGracePeriod.• openmeter/customer/service/service.go (lines 18–21):
type Config struct { Adapter customer.Adapter Publisher eventbus.Publisher }• Calls to
customerservice.New(customerservice.Config{…})across tests and application code only supplyAdapterandPublisher.
• No remaining references toEntitlementConnector,GracePeriod, or related stale entitlement wiring were found.All checks complete—no further action needed.
| // ensure subjects exist for usage attribution | ||
| { | ||
| resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_1"}}) | ||
| require.Nil(t, err) | ||
| require.Equal(t, http.StatusOK, resp.StatusCode()) | ||
| } |
There was a problem hiding this comment.
Accept 201 on upsert and remove duplication via helper
Upsert may legitimately return 201 on create; asserting 200 risks flaky tests. Also, the 4 identical blocks should be DRYed.
Apply within this range:
- {
- resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_1"}})
- require.Nil(t, err)
- require.Equal(t, http.StatusOK, resp.StatusCode())
- }
+ ensureSubject(t, ctx, client, "test_customer_subject_1")Add once (outside this range) near the top of the file:
// helper to ensure subject existence with tolerant status check
func ensureSubject(t testing.TB, ctx context.Context, client *api.ClientWithResponses, key string) {
t.Helper()
resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: key}})
require.NoError(t, err)
require.Contains(t, []int{http.StatusOK, http.StatusCreated}, resp.StatusCode(), "status=%d body=%s", resp.StatusCode(), resp.Body)
}🤖 Prompt for AI Agents
In e2e/productcatalog_test.go around lines 32 to 37, the test currently calls
UpsertSubject and asserts only http.StatusOK and repeats the same block four
times; change this to tolerate both 200 and 201 and remove duplication by adding
a helper near the top of the file (ensureSubject) that calls
UpsertSubjectWithResponse, checks err with require.NoError, and asserts the
response status is one of http.StatusOK or http.StatusCreated (including status
and body on failure), then replace the four identical UpsertSubject blocks with
calls to ensureSubject(t, ctx, client, "<key>") for each subject key.
| // ensure subject exists for second customer | ||
| { | ||
| resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_2"}}) | ||
| require.Nil(t, err) | ||
| require.Equal(t, http.StatusOK, resp.StatusCode()) | ||
| } |
There was a problem hiding this comment.
Same fix: tolerate 201 and call helper
Mirror the change from the first block to avoid brittle status checks and duplication.
- {
- resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_2"}})
- require.Nil(t, err)
- require.Equal(t, http.StatusOK, resp.StatusCode())
- }
+ ensureSubject(t, ctx, client, "test_customer_subject_2")📝 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.
| // ensure subject exists for second customer | |
| { | |
| resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_2"}}) | |
| require.Nil(t, err) | |
| require.Equal(t, http.StatusOK, resp.StatusCode()) | |
| } | |
| // ensure subject exists for second customer | |
| ensureSubject(t, ctx, client, "test_customer_subject_2") |
🤖 Prompt for AI Agents
In e2e/productcatalog_test.go around lines 62 to 67, the test currently upserts
a subject and only asserts StatusOK (200) and duplicates logic; update this
block to mirror the first upsert: use the same helper that checks for either 200
or 201 (tolerate 201 Created as valid) and replace the inline requires with a
call to that helper so the status check is not brittle and duplication is
removed.
| // ensure subject exists for abused customer | ||
| { | ||
| resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_abused"}}) | ||
| require.Nil(t, err) | ||
| require.Equal(t, http.StatusOK, resp.StatusCode()) | ||
| } |
There was a problem hiding this comment.
Same fix for abused subject upsert
Use the helper and accept 200/201.
- {
- resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_abused"}})
- require.Nil(t, err)
- require.Equal(t, http.StatusOK, resp.StatusCode())
- }
+ ensureSubject(t, ctx, client, "test_customer_subject_abused")📝 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.
| // ensure subject exists for abused customer | |
| { | |
| resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_abused"}}) | |
| require.Nil(t, err) | |
| require.Equal(t, http.StatusOK, resp.StatusCode()) | |
| } | |
| // ensure subject exists for abused customer | |
| - { | |
| - resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_abused"}}) | |
| - require.Nil(t, err) | |
| - require.Equal(t, http.StatusOK, resp.StatusCode()) | |
| ensureSubject(t, ctx, client, "test_customer_subject_abused") |
🤖 Prompt for AI Agents
In e2e/productcatalog_test.go around lines 102 to 107, the test upserts an
"abused" subject directly and asserts only HTTP 200; replace this block to use
the existing subject helper function (the one used elsewhere in the test suite)
to create/upsert the subject and update the assertion to accept either 200 or
201 as a successful status code. Ensure the helper is called with the same key
"test_customer_subject_abused" and assert that resp.StatusCode() is either
http.StatusOK or http.StatusCreated.
| // ensure subject exists for third customer | ||
| { | ||
| resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_3"}}) | ||
| require.Nil(t, err) | ||
| require.Equal(t, http.StatusOK, resp.StatusCode()) | ||
| } |
There was a problem hiding this comment.
Same fix for third customer subject upsert
DRY and accept 201 on create.
- {
- resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_3"}})
- require.Nil(t, err)
- require.Equal(t, http.StatusOK, resp.StatusCode())
- }
+ ensureSubject(t, ctx, client, "test_customer_subject_3")📝 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.
| // ensure subject exists for third customer | |
| { | |
| resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: "test_customer_subject_3"}}) | |
| require.Nil(t, err) | |
| require.Equal(t, http.StatusOK, resp.StatusCode()) | |
| } | |
| // ensure subject exists for third customer | |
| ensureSubject(t, ctx, client, "test_customer_subject_3") |
🤖 Prompt for AI Agents
In e2e/productcatalog_test.go around lines 954 to 959, the third customer
subject upsert repeats logic and only checks for 200; refactor to reuse the
existing helper used for the other subject upserts (or extract a small helper
that calls client.UpsertSubjectWithResponse and asserts no error) and update the
assertion to accept both http.StatusOK and http.StatusCreated (201) as valid
outcomes when creating the subject.
| func (m *EntitlementMutation) SetSubjectID(s string) { | ||
| m.subject = &s | ||
| } |
There was a problem hiding this comment.
SetSubjectID/ResetSubjectID must cancel prior ClearSubject to avoid nulling FK
If ClearSubject() ran earlier, clearedsubject and clearedFields[FieldSubjectID] remain set. Calling SetSubjectID or ResetSubjectID should undo both to prevent persisting NULL or a clear+set conflict.
Apply:
func (m *EntitlementMutation) SetSubjectID(s string) {
- m.subject = &s
+ m.subject = &s
+ m.clearedsubject = false
+ delete(m.clearedFields, entitlement.FieldSubjectID)
}
@@
func (m *EntitlementMutation) ResetSubjectID() {
m.subject = nil
+ delete(m.clearedFields, entitlement.FieldSubjectID)
}Also applies to: 32283-32284
🤖 Prompt for AI Agents
In openmeter/ent/db/mutation.go around lines 32251-32253 and 32283-32284,
SetSubjectID and ResetSubjectID currently do not clear the prior clearedsubject
flag or clearedFields[FieldSubjectID], which can leave cleared state and cause a
NULL FK to be persisted; modify both methods so that when setting or resetting
SubjectID they also unset m.clearedsubject (or m.clearedSubject) and delete
m.clearedFields[FieldSubjectID] (or set it to false) — ensure both flags/fields
that ClearSubject() sets are reversed whenever SetSubjectID or ResetSubjectID is
called so no stale cleared state remains.
| func (a *entitlementDBAdapter) mapEntitlementEntity(ctx context.Context, e *db.Entitlement) (*entitlement.Entitlement, error) { | ||
| // Get subject key from the subject edge | ||
| subjectKey := "" | ||
| if e.Edges.Subject != nil { | ||
| subjectKey = e.Edges.Subject.Key | ||
| } | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
SubjectKey mapping drops to empty string if edge isn’t preloaded — add persisted field fallback.
mapEntitlementEntity currently derives SubjectKey only from the edge; when the edge isn’t loaded, SubjectKey becomes empty despite e.SubjectKey being populated. Add a fallback to avoid silent data loss in responses.
-func (a *entitlementDBAdapter) mapEntitlementEntity(ctx context.Context, e *db.Entitlement) (*entitlement.Entitlement, error) {
- // Get subject key from the subject edge
- subjectKey := ""
- if e.Edges.Subject != nil {
- subjectKey = e.Edges.Subject.Key
- }
+func (a *entitlementDBAdapter) mapEntitlementEntity(ctx context.Context, e *db.Entitlement) (*entitlement.Entitlement, error) {
+ // Prefer edge key when loaded; fall back to persisted column
+ subjectKey := e.SubjectKey
+ if e.Edges.Subject != nil && e.Edges.Subject.Key != "" {
+ subjectKey = e.Edges.Subject.Key
+ }Also applies to: 478-478
🤖 Prompt for AI Agents
In openmeter/entitlement/adapter/entitlement.go around lines 456-462 (and
similarly at line ~478), the code only sets subjectKey from e.Edges.Subject
which becomes empty when the edge isn't preloaded; change the logic to first try
e.Edges.Subject.Key if e.Edges.Subject != nil, and if that is absent then fall
back to the persisted e.SubjectKey field (e.SubjectKey), ensuring SubjectKey is
populated when the edge was not loaded; apply the same fallback pattern at the
other occurrence around line 478.
Overview
Don't let the branch name fool you...
During the "Bring subjects to OSS" effort the hard linking of entitlement <---> subject wasn't completed (back then we didn't want to bother with migrating to
subject_idreferences & ent doesn't support edges based on non-PK fields, see deleted comment for details), this PR addresses that.Entitlement <---> Subject linking is needed so that in a later step we can change that reference to the belonging customer (once customers are created for all subjects)
Previously
customerpackage depended on theentitlementpackage (due to thecustomer.Servicemethods). This has been undone via moving those resolutions to the httpdriver layer (temporary solution)Notes
Summary by CodeRabbit
New Features
Breaking Changes
Database Migration
Bug Fixes
Chores