fix: check if already deducted a transaction to avoid 5XX response.
Description
When CreateBillingUsage API is called multiple times with same ID, it doesn't check if already debuted and tries to create transaction entry. This results in DB error ERROR: duplicate key value violates unique constraint, HTTP status code 500 .
Applied a check to see if the ID is present. If no, it's BAU. If yes, it returns an error mentioning credits already applied with HTTP status code 409.
API Testing
- Unique ID
Payload:
"usages": [
{
"id": "cbaef2b4-eb91-44c0-bdc4-eed02666ea70",
"customer_id": "",
"source": "",
"description": "",
"type": "credit",
"amount": "2",
"user_id": "",
"metadata": {},
"created_at": "",
"updated_at": ""
}
Response status: 200 OK
- Duplicate ID
Payload:
"usages": [
{
"id": "cbaef2b4-eb91-44c0-bdc4-eed02666ea70",
"customer_id": "",
"source": "",
"description": "",
"type": "credit",
"amount": "2",
"user_id": "",
"metadata": {},
"created_at": "",
"updated_at": ""
}
Response:
status - 409 Conflict
body -
{
"code": 6,
"message": "failed to deduct usage: credits already applied",
"details": []
}
The latest updates on your projects. Learn more about Vercel for Git ↗︎
| Name | Status | Preview | Comments | Updated (UTC) |
|---|---|---|---|---|
| frontier | ✅ Ready (Inspect) | Visit Preview | 💬 Add feedback | Aug 28, 2024 9:50am |
Pull Request Test Coverage Report for Build 10594331944
Warning: This coverage report may be inaccurate.
This pull request's base commit is no longer the HEAD commit of its target branch. This means it includes changes from outside the original pull request, including, potentially, unrelated coverage changes.
- For more information on this, see Tracking coverage changes with pull request builds.
- To avoid this issue with future PRs, see these Recommended CI Configurations.
- For a quick fix, rebase this PR at GitHub. Your next report should be accurate.
Details
- 7 of 15 (46.67%) changed or added relevant lines in 3 files are covered.
- 344 unchanged lines in 6 files lost coverage.
- Overall coverage increased (+0.03%) to 9.489%
| Changes Missing Coverage | Covered Lines | Changed/Added Lines | % |
|---|---|---|---|
| internal/api/v1beta1/billing_usage.go | 0 | 3 | 0.0% |
| internal/store/postgres/billing_transactions_repository.go | 0 | 5 | 0.0% |
| <!-- | Total: | 7 | 15 |
| Files with Coverage Reduction | New Missed Lines | % |
|---|---|---|
| internal/api/v1beta1/billing_usage.go | 1 | 0.0% |
| internal/store/postgres/billing_invoice_repository.go | 14 | 0.0% |
| billing/customer/service.go | 19 | 0.0% |
| billing/invoice/service.go | 36 | 0.0% |
| billing/checkout/service.go | 123 | 0.0% |
| billing/subscription/service.go | 151 | 0.0% |
| <!-- | Total: | 344 |
| Totals | |
|---|---|
| Change from base Build 10519904318: | 0.03% |
| Covered Lines: | 10459 |
| Relevant Lines: | 110219 |