-
-
Notifications
You must be signed in to change notification settings - Fork 10
feat(billing): config-gated referral grant — listener + reconcile cron (closes #3842) #3843
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
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
7b55d37
feat(billing): config-gated referral grant on invitation.accepted (#3…
PierreBrisorgueil 5feb6ba
refactor(billing): referral grant review fixes — expectedGrantKeys si…
PierreBrisorgueil 4db326b
fix(billing): fold CodeRabbit/Copilot review comments (pass 1)
PierreBrisorgueil 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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| /** | ||
| * Cron script — referral grant reconcile sweep (#3842). | ||
| * | ||
| * The `invitation.accepted` listener in billing.init.js is in-process fire-and-forget: | ||
| * a crash between accept and grant loses the event, and a mailer-configured signup can | ||
| * fire it before the referee's organization exists. This sweep is the truth: it scans | ||
| * ALL `invitations { status:'accepted' }`, diffs the expected grant keys | ||
| * (`referral:<invitationId>:referrer|referee`) against the BillingExtraBalance ledger, | ||
| * and back-fills misses idempotently via BillingReferralService.grantForInvitation | ||
| * (the atomic `ledger.refId` guard makes overlap with the listener harmless). | ||
| * | ||
| * No-op when config.billing.referral.enabled === false (default). | ||
| * Intended to run as a Kubernetes CronJob — see modules/billing/crons/README.md. | ||
| * | ||
| * Usage: | ||
| * NODE_ENV=production node modules/billing/crons/billing.referralReconcile.js | ||
| */ | ||
|
|
||
| import { randomUUID } from 'node:crypto'; | ||
|
|
||
| process.env.NODE_ENV = process.env.NODE_ENV || 'development'; | ||
|
|
||
| const [ | ||
| { default: config }, | ||
| { default: mongooseService }, | ||
| { default: logger }, | ||
| { applyJitter }, | ||
| { getCronJitterMaxMs }, | ||
| { acquireLock, releaseLock }, | ||
| ] = await Promise.all([ | ||
| import('../../../config/index.js'), | ||
| import('../../../lib/services/mongoose.js'), | ||
| import('../../../lib/services/logger.js'), | ||
| import('../lib/billing.cron-utils.js'), | ||
| import('../lib/billing.constants.js'), | ||
| import('../../../lib/services/distributedLock.js'), | ||
| ]); | ||
|
|
||
| if (!config?.billing?.referral?.enabled) { | ||
| logger.info('[cron.referralReconcile] referral disabled — skipping.'); | ||
| process.exit(0); | ||
| } | ||
|
|
||
| const LOCK_NAME = 'billing.referralReconcile'; | ||
| const LOCK_TTL_MS = 10 * 60 * 1000; // 10 min | ||
|
|
||
| const startMs = Date.now(); | ||
| logger.info('[cron.referralReconcile] start'); | ||
|
|
||
| let lockHolder = null; | ||
| try { | ||
| await applyJitter(getCronJitterMaxMs()); | ||
| await mongooseService.loadModels(); | ||
| await mongooseService.connect(); | ||
|
|
||
| lockHolder = `${process.env.HOSTNAME ?? 'unknown'}:${randomUUID()}`; | ||
| const acquired = await acquireLock({ name: LOCK_NAME, ttlMs: LOCK_TTL_MS, holder: lockHolder }); | ||
| if (!acquired) { | ||
| logger.info('[cron.referralReconcile] lock held by another pod, skipping'); | ||
| process.exitCode = 0; | ||
| } else { | ||
| try { | ||
| const [ | ||
| { default: BillingReferralService }, | ||
| { default: BillingExtraBalanceRepository }, | ||
| { default: InvitationRepository }, | ||
| ] = await Promise.all([ | ||
| import('../services/billing.referral.service.js'), | ||
| import('../repositories/billing.extraBalance.repository.js'), | ||
| import('../../invitations/repositories/invitations.repository.js'), | ||
| ]); | ||
|
|
||
| const cfg = config.billing.referral; | ||
| const accepted = await InvitationRepository.findAccepted(); | ||
|
|
||
| // Expected keys per invitation — derived from the service's expectedGrantKeys | ||
| // (the SINGLE rule source shared with grantForInvitation): the cron never | ||
| // re-encodes the side rules, so a new guard (e.g. #3833) can never drift. | ||
| const candidates = []; | ||
| for (const invite of accepted) { | ||
| const expected = BillingReferralService.expectedGrantKeys(invite, cfg).map(({ key }) => key); | ||
| if (expected.length > 0) candidates.push({ invite, expected }); | ||
| } | ||
|
|
||
| const allKeys = candidates.flatMap((c) => c.expected); | ||
| const existing = new Set(await BillingExtraBalanceRepository.findExistingRefIds(allKeys)); | ||
|
|
||
|
PierreBrisorgueil marked this conversation as resolved.
|
||
| let backfilled = 0; | ||
| let pending = 0; | ||
| let errors = 0; | ||
|
|
||
| for (const { invite, expected } of candidates) { | ||
| if (expected.every((key) => existing.has(key))) continue; // fully granted | ||
| try { | ||
| const result = await BillingReferralService.grantForInvitation({ | ||
| invitationId: String(invite._id), | ||
| invitedBy: invite.invitedBy ? String(invite.invitedBy) : null, | ||
| acceptedUserId: invite.acceptedUserId ? String(invite.acceptedUserId) : null, | ||
| }); | ||
| const sides = [result.referrer, result.referee].filter(Boolean); | ||
| const applied = sides.filter((s) => s.applied).length; | ||
| // `no_organization` = the actor has no workspace yet (e.g. email verification | ||
| // pending) — stays pending, retried on the next run once the org exists. | ||
| const waiting = sides.filter((s) => s.reason === 'no_organization').length; | ||
| if (applied > 0) { | ||
| backfilled += applied; | ||
| logger.info('[cron.referralReconcile] back-filled', { invitationId: String(invite._id), applied }); | ||
| } | ||
| if (waiting > 0) pending += waiting; | ||
| } catch (err) { | ||
| errors += 1; | ||
| logger.error('[cron.referralReconcile] grantForInvitation failed', { | ||
| invitationId: String(invite._id), | ||
| err: err?.message, | ||
| stack: err?.stack, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| logger.info('[cron.referralReconcile] complete', { | ||
| accepted: accepted.length, | ||
| backfilled, | ||
| pending, | ||
| errors, | ||
| durationMs: Date.now() - startMs, | ||
| }); | ||
| process.exitCode = errors > 0 ? 1 : 0; | ||
| } finally { | ||
| // releaseLock failure is non-fatal: lock auto-expires on TTL. | ||
| // Log separately to preserve any original work error. | ||
| try { | ||
| await releaseLock({ name: LOCK_NAME, holder: lockHolder }); | ||
| } catch (releaseErr) { | ||
| logger.error('[cron.referralReconcile] failed to release lock — will auto-expire on TTL', { | ||
| err: releaseErr, | ||
| cron: LOCK_NAME, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| } catch (err) { | ||
| logger.error('[cron.referralReconcile] failed', { err: err?.message, stack: err?.stack }); | ||
| process.exitCode = 1; | ||
| } finally { | ||
| await mongooseService.disconnect?.(); | ||
| } | ||
| process.exit(process.exitCode ?? 0); | ||
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
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.