-
Notifications
You must be signed in to change notification settings - Fork 191
feat: auto top ups #821
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat: auto top ups #821
Changes from 3 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6504a91
feat: add intial cutsomer billing control schema
charlietlamb 1a15b4a
chore: flatten billing controls in customer table in db
charlietlamb 0e65dc2
feat: auto top ups
charlietlamb 0b24e43
refactor: auto topups
charlietlamb 250c4ec
feat: auto top ups frontend & refactor
charlietlamb 2081152
merged from dev
johnyeocx 7de7a0e
fix: correct granted_balance computation in BalanceEditSheet for prep…
charlietlamb daee561
fix: auto top up tests and added trigger to check
johnyeocx b06724d
Merge branch 'charlie/eng-1060-enable-auto-top-ups' of https://github…
johnyeocx 8a8f881
Merge branch 'dev' into auto-topups
johnyeocx File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| -- ============================================================================ | ||
| -- INCREMENT CUSTOMER ENTITLEMENT BALANCE | ||
| -- Atomically increments a cusEnt's balance in the cached FullCustomer JSON | ||
| -- using JSON.NUMINCRBY (relative delta, safe with concurrent deductions). | ||
| -- ============================================================================ | ||
| -- KEYS[1] = fullCustomer cache key | ||
| -- ARGV[1] = JSON: { cus_ent_id: string, delta: number } | ||
| -- Returns: JSON: { ok: true, new_balance: number } | { ok: false, error: string } | ||
| -- ============================================================================ | ||
|
|
||
| local cache_key = KEYS[1] | ||
| local params = cjson.decode(ARGV[1]) | ||
|
|
||
| local cus_ent_id = params.cus_ent_id | ||
| local delta = tonumber(params.delta) | ||
|
|
||
| if not cus_ent_id or not delta then | ||
| return cjson.encode({ ok = false, error = "missing cus_ent_id or delta" }) | ||
| end | ||
|
|
||
| -- Read the full customer to find the entitlement indices | ||
| local raw = redis.call('JSON.GET', cache_key, '.') | ||
| if not raw then | ||
| return cjson.encode({ ok = false, error = "cache_miss" }) | ||
| end | ||
|
|
||
| local full_customer = cjson.decode(raw) | ||
| local cus_ent, cus_product, ce_idx, cp_idx = find_entitlement(full_customer, cus_ent_id) | ||
|
|
||
| if not cus_ent then | ||
| return cjson.encode({ ok = false, error = "cus_ent_not_found" }) | ||
| end | ||
|
|
||
| -- Build the JSON path to the balance field | ||
| local base_path | ||
| if cp_idx then | ||
| -- Lua arrays are 1-indexed, RedisJSON is 0-indexed | ||
| base_path = '$.customer_products[' .. (cp_idx - 1) .. '].customer_entitlements[' .. (ce_idx - 1) .. ']' | ||
| else | ||
| base_path = '$.extra_customer_entitlements[' .. (ce_idx - 1) .. ']' | ||
| end | ||
|
|
||
| local balance_path = base_path .. '.balance' | ||
|
|
||
| -- Atomic relative increment | ||
| local new_balance = redis.call('JSON.NUMINCRBY', cache_key, balance_path, delta) | ||
|
|
||
| return cjson.encode({ ok = true, new_balance = tonumber(new_balance) }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
74 changes: 74 additions & 0 deletions
74
server/src/internal/balances/autoTopUp/autoTopUpRateLimit.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| import { | ||
| type AutoTopupMaxPurchases, | ||
| billingIntervalToSeconds, | ||
| } from "@autumn/shared"; | ||
| import { redis } from "@/external/redis/initRedis.js"; | ||
| import { tryRedisWrite } from "@/utils/cacheUtils/cacheUtils.js"; | ||
|
|
||
| const buildRateLimitKey = ({ | ||
| orgId, | ||
| env, | ||
| customerId, | ||
| featureId, | ||
| }: { | ||
| orgId: string; | ||
| env: string; | ||
| customerId: string; | ||
| featureId: string; | ||
| }) => { | ||
| return `auto_topup_count:${orgId}:${env}:${customerId}:${featureId}`; | ||
| }; | ||
|
|
||
| /** Check if auto top-up is within the max_purchases rate limit */ | ||
| export const checkAutoTopUpRateLimit = async ({ | ||
| orgId, | ||
| env, | ||
| customerId, | ||
| featureId, | ||
| maxPurchases, | ||
| }: { | ||
| orgId: string; | ||
| env: string; | ||
| customerId: string; | ||
| featureId: string; | ||
| maxPurchases: AutoTopupMaxPurchases; | ||
| }): Promise<boolean> => { | ||
| if (redis.status !== "ready") { | ||
| return true; | ||
| } | ||
|
|
||
| const key = buildRateLimitKey({ orgId, env, customerId, featureId }); | ||
| const current = await redis.get(key); | ||
|
|
||
| if (current === null) { | ||
| return true; | ||
| } | ||
|
|
||
| return Number.parseInt(current, 10) < maxPurchases.limit; | ||
| }; | ||
|
|
||
| /** Increment the auto top-up purchase counter. Sets TTL on first increment. */ | ||
| export const incrementAutoTopUpCounter = async ({ | ||
| orgId, | ||
| env, | ||
| customerId, | ||
| featureId, | ||
| maxPurchases, | ||
| }: { | ||
| orgId: string; | ||
| env: string; | ||
| customerId: string; | ||
| featureId: string; | ||
| maxPurchases: AutoTopupMaxPurchases; | ||
| }): Promise<void> => { | ||
| const key = buildRateLimitKey({ orgId, env, customerId, featureId }); | ||
| const ttl = billingIntervalToSeconds({ interval: maxPurchases.interval }); | ||
|
|
||
| await tryRedisWrite(async () => { | ||
| const count = await redis.incr(key); | ||
|
|
||
| if (count === 1) { | ||
| await redis.expire(key, ttl); | ||
| } | ||
| }); | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.