Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
219 changes: 219 additions & 0 deletions e2e/v1readsurface_unitconfig_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
package e2e

import (
"net/http"
"testing"

"github.com/samber/lo"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

api "github.com/openmeterio/openmeter/api/client/go"
v3sdk "github.com/openmeterio/openmeter/api/v3/client"
)

const unitConfigNotRepresentableCode = "unit_config_not_representable"

// Flow:
// - v1 plan GET on a unit_config plan → 400 with the typed code (not a stripped 200)
// - v1 plan GET on a plain plan → 200 (exclusion is content-derived, not blanket)
// - v1 plan LIST omits the unit_config plan, keeps the plain one, and reports an exact TotalCount
// - v1 subscribe-by-plan-key from the unit_config plan still succeeds (read ≠ subscribe; OM-399)
// - v1 subscription GET on that subscription → 400 with the same typed code
func TestV1ReadSurfaceExcludesUnitConfig(t *testing.T) {
c := newV3Client(t)
v1 := initClient(t)

uniq := uniqueKey("ucread")
meterKey := "ucread_meter_" + uniq
eventType := "ucread_event_" + uniq
featureKey := "ucread_feature_" + uniq
customerKey := "ucread_customer_" + uniq
subjectKey := "ucread_subject_" + uniq
ucPlanKey := "ucread_uc_plan_" + uniq
plainPlanKey := "ucread_plain_plan_" + uniq

var ucPlan *v3sdk.Plan
var plainPlan *v3sdk.Plan

// given:
// - a unit_config plan (usage-based rate card, divide-by-1000 ceiling) and a plain plan, both
// authored and published via v3 (v1 cannot author unit_config).
runRequired(t, "creates a unit_config plan and a plain plan", func(t *testing.T) {
meter, err := c.Meters.Create(t.Context(), v3sdk.CreateMeterRequest{
Key: meterKey,
Name: "UC Read Meter " + uniq,
Aggregation: v3sdk.MeterAggregationSum,
EventType: eventType,
ValueProperty: lo.ToPtr("$.value"),
})
c.requireStatus(http.StatusCreated, err)
require.NotNil(t, meter)

feature, err := c.Features.Create(t.Context(), v3sdk.CreateFeatureRequest{
Key: featureKey,
Name: "UC Read Feature " + uniq,
Meter: &v3sdk.FeatureMeterReferenceInput{ID: meter.ID},
})
c.requireStatus(http.StatusCreated, err)
require.NotNil(t, feature)

cadence := "P1M"
term := v3sdk.PricePaymentTermInArrears
price := lo.Must(v3sdk.PriceFromPriceUnit(v3sdk.PriceUnit{
Amount: "0.10",
}))
ucRateCard := v3sdk.RateCardInput{
Key: feature.Key,
Name: "UC Read Rate Card " + uniq,
Price: price,
BillingCadence: &cadence,
PaymentTerm: &term,
Feature: &v3sdk.FeatureReference{ID: feature.ID},
UnitConfig: &v3sdk.UnitConfig{
Operation: v3sdk.UnitConfigOperationDivide,
ConversionFactor: "1000",
Rounding: lo.ToPtr(v3sdk.UnitConfigRoundingModeCeiling),
Precision: lo.ToPtr(int64(0)),
},
}

createdUC, err := c.Plans.Create(t.Context(), v3sdk.CreatePlanRequest{
Key: ucPlanKey,
Name: "UC Read Plan " + uniq,
Currency: "USD",
BillingCadence: "P1M",
Phases: []v3sdk.PlanPhaseInput{{
Key: "phase_1",
Name: "UC Phase",
RateCards: []v3sdk.RateCardInput{ucRateCard},
}},
})
c.requireStatus(http.StatusCreated, err)
require.NotNil(t, createdUC)
ucPlan, err = c.Plans.Publish(t.Context(), createdUC.ID)
c.requireStatus(http.StatusOK, err)
require.NotNil(t, ucPlan)

createdPlain, err := c.Plans.Create(t.Context(), v3sdk.CreatePlanRequest{
Key: plainPlanKey,
Name: "Plain Read Plan " + uniq,
Currency: "USD",
BillingCadence: "P1M",
Phases: []v3sdk.PlanPhaseInput{validPlanPhase("plain_phase", true /* isLast */)},
})
c.requireStatus(http.StatusCreated, err)
require.NotNil(t, createdPlain)
plainPlan, err = c.Plans.Publish(t.Context(), createdPlain.ID)
c.requireStatus(http.StatusOK, err)
require.NotNil(t, plainPlan)
})

// then:
// - v1 GET on the unit_config plan is rejected with the typed code (not a silently-stripped 200).
runRequired(t, "v1 plan GET rejects the unit_config plan", func(t *testing.T) {
resp, err := v1.GetPlanWithResponse(t.Context(), ucPlan.ID, nil)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode(), "body: %s", string(resp.Body))
require.NotNil(t, resp.ApplicationproblemJSON400)
assert.Contains(t, string(resp.Body), unitConfigNotRepresentableCode, "the 400 must carry the typed unit_config code")
})

// and:
// - the plain plan is still gettable via v1 (the exclusion is content-derived, not a blanket block).
runRequired(t, "v1 plan GET returns the plain plan", func(t *testing.T) {
resp, err := v1.GetPlanWithResponse(t.Context(), plainPlan.ID, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode(), "body: %s", string(resp.Body))
require.NotNil(t, resp.JSON200)
assert.Equal(t, plainPlanKey, resp.JSON200.Key)
})

// and:
// - v1 LIST omits the unit_config plan, keeps the plain one, and TotalCount reflects the filtered set
// (the exclusion runs at the query layer, before the COUNT — so the count stays exact).
runRequired(t, "v1 plan LIST excludes the unit_config plan with an exact TotalCount", func(t *testing.T) {
resp, err := v1.ListPlansWithResponse(t.Context(), &api.ListPlansParams{
Key: &[]string{ucPlanKey, plainPlanKey},
PageSize: lo.ToPtr(api.PaginationPageSize(1000)),
})
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode(), "body: %s", string(resp.Body))
require.NotNil(t, resp.JSON200)

keys := lo.Map(resp.JSON200.Items, func(p api.Plan, _ int) string { return p.Key })
assert.NotContains(t, keys, ucPlanKey, "unit_config plan must be excluded from the v1 list")
assert.Contains(t, keys, plainPlanKey, "plain plan must remain in the v1 list")
assert.Equal(t, 1, resp.JSON200.TotalCount, "TotalCount must reflect the filtered set, not the raw count")
})

// and:
// - v1 mutations on the unit_config plan are rejected BEFORE any side effect. The guard runs
// pre-commit in the service (not in the response mapper), so a 400 means nothing committed —
// the plan is left exactly as it was. This is the core OM-409 follow-up: no commit-then-400.
runRequired(t, "v1 plan mutations reject the unit_config plan with no side effect", func(t *testing.T) {
// archive: the guard runs before the active-status check, so an active plan is still rejected.
archiveResp, err := v1.ArchivePlanWithResponse(t.Context(), ucPlan.ID)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, archiveResp.StatusCode(), "body: %s", string(archiveResp.Body))
assert.Contains(t, string(archiveResp.Body), unitConfigNotRepresentableCode, "archive 400 must carry the typed unit_config code")

// publish: the guard runs before the publishable-status check.
publishResp, err := v1.PublishPlanWithResponse(t.Context(), ucPlan.ID)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, publishResp.StatusCode(), "body: %s", string(publishResp.Body))
assert.Contains(t, string(publishResp.Body), unitConfigNotRepresentableCode, "publish 400 must carry the typed unit_config code")

// next: the guard runs before the next draft version is created.
nextResp, err := v1.NextPlanWithResponse(t.Context(), ucPlan.ID)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, nextResp.StatusCode(), "body: %s", string(nextResp.Body))
assert.Contains(t, string(nextResp.Body), unitConfigNotRepresentableCode, "next 400 must carry the typed unit_config code")

// no side effect: after three rejected mutations the plan is unchanged — still the single
// active version it was published as (a commit-then-400 mapper would have left it archived).
after, err := c.Plans.Get(t.Context(), ucPlan.ID)
c.requireStatus(http.StatusOK, err)
require.NotNil(t, after)
assert.Equal(t, v3sdk.PlanStatusActive, after.Status, "the plan must remain active — no mutation may have committed")
})

// and:
// - a v1 subscription created from the unit_config plan BY KEY still succeeds (read ≠ subscribe; the
// server rates it correctly per OM-399, only the read surfaces are restricted).
var subscriptionID string
runRequired(t, "v1 subscribe-by-plan-key from the unit_config plan succeeds", func(t *testing.T) {
customer := CreateCustomerWithSubject(t, v1, customerKey, subjectKey)
require.NotNil(t, customer)

timing := &api.SubscriptionTiming{}
require.NoError(t, timing.FromSubscriptionTimingEnum(api.SubscriptionTimingEnumImmediate))

body := api.SubscriptionCreate{}
require.NoError(t, body.FromPlanSubscriptionCreate(api.PlanSubscriptionCreate{
Timing: timing,
CustomerId: lo.ToPtr(customer.Id),
Plan: api.PlanReferenceInput{
Key: ucPlanKey,
Version: lo.ToPtr(1),
},
}))

resp, err := v1.CreateSubscriptionWithResponse(t.Context(), body)
require.NoError(t, err)
require.Equal(t, http.StatusCreated, resp.StatusCode(), "body: %s", string(resp.Body))
require.NotNil(t, resp.JSON201)
subscriptionID = resp.JSON201.Id
})

// then:
// - v1 GET on that subscription is rejected with the same typed code (its items carry the unit_config).
runRequired(t, "v1 subscription GET rejects the unit_config subscription", func(t *testing.T) {
require.NotEmpty(t, subscriptionID)
resp, err := v1.GetSubscriptionWithResponse(t.Context(), subscriptionID, nil)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode(), "body: %s", string(resp.Body))
require.NotNil(t, resp.ApplicationproblemJSON400)
assert.Contains(t, string(resp.Body), unitConfigNotRepresentableCode, "the 400 must carry the typed unit_config code")
})
}
4 changes: 4 additions & 0 deletions openmeter/productcatalog/addon.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,10 @@ func (a Addon) ValidateWith(validators ...models.ValidatorFunc[Addon]) error {
return models.Validate(a, validators...)
}

func (a Addon) HasUnitConfig() bool {
return a.RateCards.HasUnitConfig()
}

// ValidationErrors returns a list of possible validation errors for the add-on.
// It returns nil if the add-on has no validation issues.
func (a Addon) ValidationErrors() (models.ValidationIssues, error) {
Expand Down
72 changes: 72 additions & 0 deletions openmeter/productcatalog/addon/adapter/adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,78 @@ func TestPostgresAdapter(t *testing.T) {
})
}

func TestListAddonsExcludeUnitConfig(t *testing.T) {
ctx := context.Background()
Comment on lines +453 to +454

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the test file around the cited lines and nearby context.
FILE="openmeter/productcatalog/addon/adapter/adapter_test.go"
wc -l "$FILE"
sed -n '430,480p' "$FILE"

# Check for t.Context() usage in the same file and surrounding tests.
rg -n 't\.Context\(\)|context\.Background\(\)|context\.TODO\(\)' "$FILE" openmeter/productcatalog/addon/adapter -g '*_test.go'

Repository: openmeterio/openmeter

Length of output: 2117


Use t.Context() here
It matches the test lifecycle better than context.Background().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/productcatalog/addon/adapter/adapter_test.go` around lines 453 -
454, In TestListAddonsExcludeUnitConfig, replace context.Background() with
t.Context() so the test context follows the test lifecycle.

Source: Coding guidelines


env := pctestutils.NewTestEnv(t)
t.Cleanup(func() { env.Close(t) })
env.DBSchemaMigrate(t)

namespace := pctestutils.NewTestNamespace(t)

require.NoError(t, env.Meter.ReplaceMeters(ctx, pctestutils.NewTestMeters(t, namespace)),
"replacing meters must not fail")
meters, err := env.Meter.ListMeters(ctx, meter.ListMetersParams{
Page: pagination.Page{PageSize: 1000, PageNumber: 1},
Namespace: namespace,
})
require.NoError(t, err, "listing meters must not fail")
require.NotEmpty(t, meters.Items, "list of meters must not be empty")

feat, err := env.Feature.CreateFeature(ctx, pctestutils.NewTestFeatureFromMeter(t, &meters.Items[0]))
require.NoError(t, err, "creating feature must not fail")

// Plain add-on: flat rate card, no unit_config → v1-representable.
plainInput := pctestutils.NewTestAddon(t, namespace, &productcatalog.FlatFeeRateCard{
RateCardMeta: productcatalog.RateCardMeta{Key: "flat", Name: "Flat"},
})
plainInput.Addon.Key = "plain"
_, err = env.AddonRepository.CreateAddon(ctx, plainInput)
require.NoError(t, err, "creating plain add-on must not fail")

// unit_config add-on: usage-based rate card carrying a unit_config → not v1-representable.
ucInput := pctestutils.NewTestAddon(t, namespace, &productcatalog.UsageBasedRateCard{
RateCardMeta: productcatalog.RateCardMeta{
Key: feat.Key,
Name: "UC RateCard",
FeatureKey: lo.ToPtr(feat.Key),
FeatureID: lo.ToPtr(feat.ID),
Price: productcatalog.NewPriceFrom(productcatalog.UnitPrice{Amount: decimal.NewFromInt(1)}),
UnitConfig: &productcatalog.UnitConfig{
Operation: productcatalog.UnitConfigOperationDivide,
ConversionFactor: decimal.NewFromInt(1000),
},
},
BillingCadence: MonthPeriod,
})
ucInput.Addon.Key = "with-uc"
_, err = env.AddonRepository.CreateAddon(ctx, ucInput)
require.NoError(t, err, "creating unit_config add-on must not fail")

t.Run("included when ExcludeUnitConfig is false", func(t *testing.T) {
list, err := env.AddonRepository.ListAddons(ctx, addon.ListAddonsInput{
Namespaces: []string{namespace},
})
require.NoError(t, err, "listing add-ons must not fail")

keys := lo.Map(list.Items, func(a addon.Addon, _ int) string { return a.Key })
require.ElementsMatch(t, []string{"plain", "with-uc"}, keys)
require.Equal(t, 2, list.TotalCount, "TotalCount must count both add-ons")
})

t.Run("excluded when ExcludeUnitConfig is true, TotalCount stays consistent", func(t *testing.T) {
list, err := env.AddonRepository.ListAddons(ctx, addon.ListAddonsInput{
Namespaces: []string{namespace},
ExcludeUnitConfig: true,
})
require.NoError(t, err, "listing add-ons must not fail")

keys := lo.Map(list.Items, func(a addon.Addon, _ int) string { return a.Key })
require.ElementsMatch(t, []string{"plain"}, keys)
require.Equal(t, 1, list.TotalCount, "TotalCount must exclude the unit_config add-on, not just the page slice")
})
}

// TestFromPlanRateCardRowMapsUnitConfig guards the cross-package mapper used when an
// add-on is loaded with expanded linked plans
// (FromAddonRow → FromPlanAddonRow → FromPlanRow → FromPlanPhaseRow → FromPlanRateCardRow).
Expand Down
7 changes: 7 additions & 0 deletions openmeter/productcatalog/addon/adapter/addon.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ func (a *adapter) ListAddons(ctx context.Context, params addon.ListAddonsInput)
query = filter.ApplyToQuery(query, params.Name, addondb.FieldName)
query = filter.ApplyToQuery(query, params.Currency, addondb.FieldCurrency)

if params.ExcludeUnitConfig {
query = query.Where(addondb.Not(addondb.HasRatecardsWith(
addonratecarddb.UnitConfigNotNil(),
addonratecarddb.DeletedAtIsNil(),
)))
}

if !params.IncludeDeleted {
query = query.Where(addondb.DeletedAtIsNil())
}
Expand Down
11 changes: 11 additions & 0 deletions openmeter/productcatalog/addon/httpdriver/addon.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ func (h *handler) ListAddons() ListAddonsHandler {
KeyVersions: lo.FromPtr(params.KeyVersion),
IncludeDeleted: lo.FromPtr(params.IncludeDeleted),
Status: statusFilter,
// The v1 API cannot represent unit_config; exclude such add-ons from the v1 list at the query layer.
ExcludeUnitConfig: true,
}

if params.Id != nil {
Expand Down Expand Up @@ -185,6 +187,8 @@ func (h *handler) UpdateAddon() UpdateAddonHandler {

req.IgnoreNonCriticalIssues = true

req.RejectUnitConfig = true

return req, nil
},
func(ctx context.Context, request UpdateAddonRequest) (UpdateAddonResponse, error) {
Expand Down Expand Up @@ -287,6 +291,10 @@ func (h *handler) GetAddon() GetAddonHandler {
return GetAddonResponse{}, fmt.Errorf("failed to get add-on [namespace=%s key=%s id=%s]: %w", request.Namespace, request.Key, request.ID, err)
}

if a.AsProductCatalogAddon().HasUnitConfig() {
return GetAddonResponse{}, productcatalog.ErrUnitConfigNotRepresentable
}

return FromAddon(*a)
},
commonhttp.JSONResponseEncoderWithStatus[GetAddonResponse](http.StatusOK),
Expand Down Expand Up @@ -322,6 +330,7 @@ func (h *handler) PublishAddon() PublishAddonHandler {
EffectivePeriod: productcatalog.EffectivePeriod{
EffectiveFrom: lo.ToPtr(clock.Now()),
},
RejectUnitConfig: true,
}

return req, nil
Expand Down Expand Up @@ -365,6 +374,8 @@ func (h *handler) ArchiveAddon() ArchiveAddonHandler {
ID: addonID,
},
EffectiveTo: clock.Now(),
// The v1 API cannot represent unit_config; reject archiving such an add-on.
RejectUnitConfig: true,
}

return req, nil
Expand Down
Loading
Loading