Skip to content

Commit bb329ac

Browse files
authored
feat(store): billing subscription and checkout reads skip soft-deleted rows (#1963)
1 parent b51bd0a commit bb329ac

5 files changed

Lines changed: 223 additions & 53 deletions

File tree

‎core/deleter/service.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,11 @@ func (d Service) DeleteCustomers(ctx context.Context, id string) error {
403403
// here.
404404
func (d Service) deleteCustomers(ctx context.Context, id string, customers []customer.Customer, amounts map[string]accountTokens) error {
405405
for _, c := range customers {
406+
// TODO(fix): the subscription and checkout reads here skip rows with
407+
// deleted_at. Once these deletes turn soft, a row left behind with
408+
// deleted_at set is invisible to this loop. A subscription then blocks the
409+
// customer delete on its foreign key, and a checkout is removed without
410+
// its audit record below. Make these deletes soft in the same change.
406411
// cancels active subscriptions on the billing provider and removes local records
407412
if err := d.subService.DeleteByCustomer(ctx, c); err != nil {
408413
return fmt.Errorf("failed to delete org while deleting a billing account subscriptions[%s]: %w", c.ID, err)

‎internal/store/postgres/billing_checkout_repository.go‎

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ func (r BillingCheckoutRepository) Create(ctx context.Context, toCreate checkout
212212
}
213213

214214
func (r BillingCheckoutRepository) GetByID(ctx context.Context, id string) (checkout.Checkout, error) {
215-
stmt := dialect.Select().From(TABLE_BILLING_CHECKOUTS).Where(goqu.Ex{
215+
stmt := fromLive(TABLE_BILLING_CHECKOUTS).Where(goqu.Ex{
216216
"id": id,
217217
})
218218
query, params, err := stmt.ToSQL()
@@ -235,30 +235,6 @@ func (r BillingCheckoutRepository) GetByID(ctx context.Context, id string) (chec
235235
return checkoutModel.transform()
236236
}
237237

238-
func (r BillingCheckoutRepository) GetByName(ctx context.Context, name string) (checkout.Checkout, error) {
239-
stmt := dialect.Select().From(TABLE_BILLING_CHECKOUTS).Where(goqu.Ex{
240-
"name": name,
241-
})
242-
query, params, err := stmt.ToSQL()
243-
if err != nil {
244-
return checkout.Checkout{}, fmt.Errorf("%w: %s", errParse, err)
245-
}
246-
247-
var checkoutModel Checkout
248-
if err = r.dbc.WithTimeout(ctx, TABLE_BILLING_CHECKOUTS, "GetByName", func(ctx context.Context) error {
249-
return r.dbc.QueryRowxContext(ctx, query, params...).StructScan(&checkoutModel)
250-
}); err != nil {
251-
err = checkPostgresError(err)
252-
switch {
253-
case errors.Is(err, sql.ErrNoRows):
254-
return checkout.Checkout{}, checkout.ErrNotFound
255-
}
256-
return checkout.Checkout{}, fmt.Errorf("%w: %s", errDB, err)
257-
}
258-
259-
return checkoutModel.transform()
260-
}
261-
262238
func (r BillingCheckoutRepository) UpdateByID(ctx context.Context, toUpdate checkout.Checkout) (checkout.Checkout, error) {
263239
if strings.TrimSpace(toUpdate.ID) == "" {
264240
return checkout.Checkout{}, checkout.ErrInvalidID
@@ -323,7 +299,7 @@ func (r BillingCheckoutRepository) DeleteByCustomerID(ctx context.Context, custo
323299
}
324300

325301
func (r BillingCheckoutRepository) List(ctx context.Context, flt checkout.Filter) ([]checkout.Checkout, error) {
326-
stmt := dialect.Select().From(TABLE_BILLING_CHECKOUTS).Order(goqu.I("created_at").Desc())
302+
stmt := fromLive(TABLE_BILLING_CHECKOUTS).Order(goqu.I("created_at").Desc())
327303
if flt.CustomerID != "" {
328304
stmt = stmt.Where(goqu.Ex{
329305
"customer_id": flt.CustomerID,
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package postgres_test
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"testing"
7+
8+
"github.com/raystack/frontier/billing/checkout"
9+
"github.com/raystack/frontier/internal/store/postgres"
10+
"github.com/raystack/frontier/pkg/db"
11+
"github.com/stretchr/testify/suite"
12+
)
13+
14+
// Runs the billing checkout reads against a real postgres to check that a
15+
// soft-deleted checkout stays out of every read.
16+
type BillingCheckoutRepositoryPGTestSuite struct {
17+
suite.Suite
18+
ctx context.Context
19+
client *db.Client
20+
repository *postgres.BillingCheckoutRepository
21+
}
22+
23+
func (s *BillingCheckoutRepositoryPGTestSuite) SetupSuite() {
24+
var err error
25+
s.client, err = newTestClient()
26+
if err != nil {
27+
s.T().Fatal(err)
28+
}
29+
s.ctx = context.TODO()
30+
s.repository = postgres.NewBillingCheckoutRepository(s.client)
31+
}
32+
33+
func (s *BillingCheckoutRepositoryPGTestSuite) TearDownSuite() {
34+
if err := closeTestClient(s.client); err != nil {
35+
s.T().Fatal(err)
36+
}
37+
}
38+
39+
func (s *BillingCheckoutRepositoryPGTestSuite) SetupTest() {
40+
s.exec(`INSERT INTO organizations (name, title) VALUES ('bch-live', 'Live Org')`)
41+
s.exec(`INSERT INTO billing_customers (org_id, provider_id, name, email)
42+
VALUES ((SELECT id FROM organizations WHERE name = 'bch-live'), 'bch-cust', 'bch-cust', 'bch-cust')`)
43+
44+
s.checkout("bch-live-session")
45+
s.checkout("bch-gone-session")
46+
47+
s.exec(`UPDATE billing_checkouts SET deleted_at = now() WHERE provider_id = 'bch-gone-session'`)
48+
}
49+
50+
func (s *BillingCheckoutRepositoryPGTestSuite) TearDownTest() {
51+
queries := []string{}
52+
for _, table := range []string{postgres.TABLE_BILLING_CHECKOUTS, postgres.TABLE_BILLING_CUSTOMERS,
53+
postgres.TABLE_ORGANIZATIONS} {
54+
queries = append(queries, fmt.Sprintf("TRUNCATE TABLE %s RESTART IDENTITY CASCADE", table))
55+
}
56+
if err := execQueries(s.ctx, s.client, queries); err != nil {
57+
s.T().Fatal(err)
58+
}
59+
}
60+
61+
func (s *BillingCheckoutRepositoryPGTestSuite) exec(query string, args ...any) {
62+
s.T().Helper()
63+
execSQL(s.T(), s.ctx, s.client, query, args...)
64+
}
65+
66+
func (s *BillingCheckoutRepositoryPGTestSuite) customerID() string {
67+
s.T().Helper()
68+
return scalarSQL(s.T(), s.ctx, s.client, `SELECT id FROM billing_customers WHERE name = 'bch-cust'`)
69+
}
70+
71+
func (s *BillingCheckoutRepositoryPGTestSuite) checkoutID(providerID string) string {
72+
s.T().Helper()
73+
return scalarSQL(s.T(), s.ctx, s.client,
74+
`SELECT id FROM billing_checkouts WHERE provider_id = $1`, providerID)
75+
}
76+
77+
func (s *BillingCheckoutRepositoryPGTestSuite) checkout(providerID string) {
78+
s.T().Helper()
79+
s.exec(`INSERT INTO billing_checkouts (customer_id, provider_id, checkout_url, state)
80+
VALUES ((SELECT id FROM billing_customers WHERE name = 'bch-cust'), $1, $1, 'pending')`, providerID)
81+
}
82+
83+
func (s *BillingCheckoutRepositoryPGTestSuite) TestGetByIDSkipsDeleted() {
84+
got, err := s.repository.GetByID(s.ctx, s.checkoutID("bch-live-session"))
85+
s.Require().NoError(err)
86+
s.Equal("bch-live-session", got.ProviderID)
87+
88+
_, err = s.repository.GetByID(s.ctx, s.checkoutID("bch-gone-session"))
89+
s.ErrorIs(err, checkout.ErrNotFound)
90+
}
91+
92+
func (s *BillingCheckoutRepositoryPGTestSuite) TestListSkipsDeleted() {
93+
got, err := s.repository.List(s.ctx, checkout.Filter{CustomerID: s.customerID()})
94+
s.Require().NoError(err)
95+
s.Require().Len(got, 1)
96+
s.Equal("bch-live-session", got[0].ProviderID)
97+
}
98+
99+
func TestBillingCheckoutRepositoryPG(t *testing.T) {
100+
suite.Run(t, new(BillingCheckoutRepositoryPGTestSuite))
101+
}

‎internal/store/postgres/billing_subscription_repository.go‎

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ func (r BillingSubscriptionRepository) Create(ctx context.Context, toCreate subs
241241
}
242242

243243
func (r BillingSubscriptionRepository) GetByID(ctx context.Context, id string) (subscription.Subscription, error) {
244-
stmt := dialect.Select().From(TABLE_BILLING_SUBSCRIPTIONS).Where(goqu.Ex{
244+
stmt := fromLive(TABLE_BILLING_SUBSCRIPTIONS).Where(goqu.Ex{
245245
"id": id,
246246
})
247247
query, params, err := stmt.ToSQL()
@@ -264,32 +264,8 @@ func (r BillingSubscriptionRepository) GetByID(ctx context.Context, id string) (
264264
return subscriptionModel.transform()
265265
}
266266

267-
func (r BillingSubscriptionRepository) GetByName(ctx context.Context, name string) (subscription.Subscription, error) {
268-
stmt := dialect.Select().From(TABLE_BILLING_SUBSCRIPTIONS).Where(goqu.Ex{
269-
"name": name,
270-
})
271-
query, params, err := stmt.ToSQL()
272-
if err != nil {
273-
return subscription.Subscription{}, fmt.Errorf("%w: %s", errParse, err)
274-
}
275-
276-
var subscriptionModel Subscription
277-
if err = r.dbc.WithTimeout(ctx, TABLE_BILLING_SUBSCRIPTIONS, "GetByName", func(ctx context.Context) error {
278-
return r.dbc.QueryRowxContext(ctx, query, params...).StructScan(&subscriptionModel)
279-
}); err != nil {
280-
err = checkPostgresError(err)
281-
switch {
282-
case errors.Is(err, sql.ErrNoRows):
283-
return subscription.Subscription{}, subscription.ErrNotFound
284-
}
285-
return subscription.Subscription{}, fmt.Errorf("%w: %s", errDB, err)
286-
}
287-
288-
return subscriptionModel.transform()
289-
}
290-
291267
func (r BillingSubscriptionRepository) GetByProviderID(ctx context.Context, id string) (subscription.Subscription, error) {
292-
stmt := dialect.Select().From(TABLE_BILLING_SUBSCRIPTIONS).Where(goqu.Ex{
268+
stmt := fromLive(TABLE_BILLING_SUBSCRIPTIONS).Where(goqu.Ex{
293269
"provider_id": id,
294270
})
295271
query, params, err := stmt.ToSQL()
@@ -429,7 +405,7 @@ func (r BillingSubscriptionRepository) toSubscriptionChanges(toUpdate subscripti
429405
}
430406

431407
func (r BillingSubscriptionRepository) List(ctx context.Context, filter subscription.Filter) ([]subscription.Subscription, error) {
432-
stmt := dialect.Select().From(TABLE_BILLING_SUBSCRIPTIONS).Order(goqu.I("created_at").Desc())
408+
stmt := fromLive(TABLE_BILLING_SUBSCRIPTIONS).Order(goqu.I("created_at").Desc())
433409
if filter.CustomerID != "" {
434410
stmt = stmt.Where(goqu.Ex{
435411
"customer_id": filter.CustomerID,
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
package postgres_test
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"testing"
7+
8+
"github.com/raystack/frontier/billing/subscription"
9+
"github.com/raystack/frontier/internal/store/postgres"
10+
"github.com/raystack/frontier/pkg/db"
11+
"github.com/stretchr/testify/suite"
12+
)
13+
14+
// Runs the billing subscription reads against a real postgres to check that a
15+
// soft-deleted subscription stays out of every read.
16+
type BillingSubscriptionRepositoryPGTestSuite struct {
17+
suite.Suite
18+
ctx context.Context
19+
client *db.Client
20+
repository *postgres.BillingSubscriptionRepository
21+
}
22+
23+
func (s *BillingSubscriptionRepositoryPGTestSuite) SetupSuite() {
24+
var err error
25+
s.client, err = newTestClient()
26+
if err != nil {
27+
s.T().Fatal(err)
28+
}
29+
s.ctx = context.TODO()
30+
s.repository = postgres.NewBillingSubscriptionRepository(s.client)
31+
}
32+
33+
func (s *BillingSubscriptionRepositoryPGTestSuite) TearDownSuite() {
34+
if err := closeTestClient(s.client); err != nil {
35+
s.T().Fatal(err)
36+
}
37+
}
38+
39+
func (s *BillingSubscriptionRepositoryPGTestSuite) SetupTest() {
40+
s.exec(`INSERT INTO organizations (name, title) VALUES ('bs-live', 'Live Org')`)
41+
s.exec(`INSERT INTO billing_customers (org_id, provider_id, name, email)
42+
VALUES ((SELECT id FROM organizations WHERE name = 'bs-live'), 'bs-cust', 'bs-cust', 'bs-cust')`)
43+
s.exec(`INSERT INTO billing_plans (name, description) VALUES ('bs-plan', 'plan under test')`)
44+
45+
s.subscription("bs-sub-live")
46+
s.subscription("bs-sub-gone")
47+
48+
s.exec(`UPDATE billing_subscriptions SET deleted_at = now() WHERE provider_id = 'bs-sub-gone'`)
49+
}
50+
51+
func (s *BillingSubscriptionRepositoryPGTestSuite) TearDownTest() {
52+
queries := []string{}
53+
for _, table := range []string{postgres.TABLE_BILLING_SUBSCRIPTIONS, postgres.TABLE_BILLING_CUSTOMERS,
54+
postgres.TABLE_BILLING_PLANS, postgres.TABLE_ORGANIZATIONS} {
55+
queries = append(queries, fmt.Sprintf("TRUNCATE TABLE %s RESTART IDENTITY CASCADE", table))
56+
}
57+
if err := execQueries(s.ctx, s.client, queries); err != nil {
58+
s.T().Fatal(err)
59+
}
60+
}
61+
62+
func (s *BillingSubscriptionRepositoryPGTestSuite) exec(query string, args ...any) {
63+
s.T().Helper()
64+
execSQL(s.T(), s.ctx, s.client, query, args...)
65+
}
66+
67+
func (s *BillingSubscriptionRepositoryPGTestSuite) customerID() string {
68+
s.T().Helper()
69+
return scalarSQL(s.T(), s.ctx, s.client, `SELECT id FROM billing_customers WHERE name = 'bs-cust'`)
70+
}
71+
72+
func (s *BillingSubscriptionRepositoryPGTestSuite) subscriptionID(providerID string) string {
73+
s.T().Helper()
74+
return scalarSQL(s.T(), s.ctx, s.client,
75+
`SELECT id FROM billing_subscriptions WHERE provider_id = $1`, providerID)
76+
}
77+
78+
func (s *BillingSubscriptionRepositoryPGTestSuite) subscription(providerID string) {
79+
s.T().Helper()
80+
s.exec(`INSERT INTO billing_subscriptions (customer_id, provider_id, plan_id, state)
81+
VALUES ((SELECT id FROM billing_customers WHERE name = 'bs-cust'), $1,
82+
(SELECT id FROM billing_plans WHERE name = 'bs-plan'), 'active')`, providerID)
83+
}
84+
85+
func (s *BillingSubscriptionRepositoryPGTestSuite) TestGetByIDSkipsDeleted() {
86+
got, err := s.repository.GetByID(s.ctx, s.subscriptionID("bs-sub-live"))
87+
s.Require().NoError(err)
88+
s.Equal("bs-sub-live", got.ProviderID)
89+
90+
_, err = s.repository.GetByID(s.ctx, s.subscriptionID("bs-sub-gone"))
91+
s.ErrorIs(err, subscription.ErrNotFound)
92+
}
93+
94+
func (s *BillingSubscriptionRepositoryPGTestSuite) TestGetByProviderIDSkipsDeleted() {
95+
got, err := s.repository.GetByProviderID(s.ctx, "bs-sub-live")
96+
s.Require().NoError(err)
97+
s.Equal("bs-sub-live", got.ProviderID)
98+
99+
_, err = s.repository.GetByProviderID(s.ctx, "bs-sub-gone")
100+
s.ErrorIs(err, subscription.ErrNotFound)
101+
}
102+
103+
func (s *BillingSubscriptionRepositoryPGTestSuite) TestListSkipsDeleted() {
104+
got, err := s.repository.List(s.ctx, subscription.Filter{CustomerID: s.customerID()})
105+
s.Require().NoError(err)
106+
s.Require().Len(got, 1)
107+
s.Equal("bs-sub-live", got[0].ProviderID)
108+
}
109+
110+
func TestBillingSubscriptionRepositoryPG(t *testing.T) {
111+
suite.Run(t, new(BillingSubscriptionRepositoryPGTestSuite))
112+
}

0 commit comments

Comments
 (0)