|
| 1 | +/** |
| 2 | + * Cron script — referral grant reconcile sweep (#3842). |
| 3 | + * |
| 4 | + * The `invitation.accepted` listener in billing.init.js is in-process fire-and-forget: |
| 5 | + * a crash between accept and grant loses the event, and a mailer-configured signup can |
| 6 | + * fire it before the referee's organization exists. This sweep is the truth: it scans |
| 7 | + * ALL `invitations { status:'accepted' }`, diffs the expected grant keys |
| 8 | + * (`referral:<invitationId>:referrer|referee`) against the BillingExtraBalance ledger, |
| 9 | + * and back-fills misses idempotently via BillingReferralService.grantForInvitation |
| 10 | + * (the atomic `ledger.refId` guard makes overlap with the listener harmless). |
| 11 | + * |
| 12 | + * No-op when config.billing.referral.enabled === false (default). |
| 13 | + * Intended to run as a Kubernetes CronJob — see modules/billing/crons/README.md. |
| 14 | + * |
| 15 | + * Usage: |
| 16 | + * NODE_ENV=production node modules/billing/crons/billing.referralReconcile.js |
| 17 | + */ |
| 18 | + |
| 19 | +import { randomUUID } from 'node:crypto'; |
| 20 | + |
| 21 | +process.env.NODE_ENV = process.env.NODE_ENV || 'development'; |
| 22 | + |
| 23 | +const [ |
| 24 | + { default: config }, |
| 25 | + { default: mongooseService }, |
| 26 | + { default: logger }, |
| 27 | + { applyJitter }, |
| 28 | + { getCronJitterMaxMs }, |
| 29 | + { acquireLock, releaseLock }, |
| 30 | +] = await Promise.all([ |
| 31 | + import('../../../config/index.js'), |
| 32 | + import('../../../lib/services/mongoose.js'), |
| 33 | + import('../../../lib/services/logger.js'), |
| 34 | + import('../lib/billing.cron-utils.js'), |
| 35 | + import('../lib/billing.constants.js'), |
| 36 | + import('../../../lib/services/distributedLock.js'), |
| 37 | +]); |
| 38 | + |
| 39 | +if (!config?.billing?.referral?.enabled) { |
| 40 | + logger.info('[cron.referralReconcile] referral disabled — skipping.'); |
| 41 | + process.exit(0); |
| 42 | +} |
| 43 | + |
| 44 | +const LOCK_NAME = 'billing.referralReconcile'; |
| 45 | +const LOCK_TTL_MS = 10 * 60 * 1000; // 10 min |
| 46 | + |
| 47 | +const startMs = Date.now(); |
| 48 | +logger.info('[cron.referralReconcile] start'); |
| 49 | + |
| 50 | +let lockHolder = null; |
| 51 | +try { |
| 52 | + await applyJitter(getCronJitterMaxMs()); |
| 53 | + await mongooseService.loadModels(); |
| 54 | + await mongooseService.connect(); |
| 55 | + |
| 56 | + lockHolder = `${process.env.HOSTNAME ?? 'unknown'}:${randomUUID()}`; |
| 57 | + const acquired = await acquireLock({ name: LOCK_NAME, ttlMs: LOCK_TTL_MS, holder: lockHolder }); |
| 58 | + if (!acquired) { |
| 59 | + logger.info('[cron.referralReconcile] lock held by another pod, skipping'); |
| 60 | + process.exitCode = 0; |
| 61 | + } else { |
| 62 | + try { |
| 63 | + const [ |
| 64 | + { default: BillingReferralService }, |
| 65 | + { default: BillingExtraBalanceRepository }, |
| 66 | + { default: InvitationRepository }, |
| 67 | + ] = await Promise.all([ |
| 68 | + import('../services/billing.referral.service.js'), |
| 69 | + import('../repositories/billing.extraBalance.repository.js'), |
| 70 | + import('../../invitations/repositories/invitations.repository.js'), |
| 71 | + ]); |
| 72 | + |
| 73 | + const cfg = config.billing.referral; |
| 74 | + const accepted = await InvitationRepository.findAccepted(); |
| 75 | + |
| 76 | + // Expected keys per invitation — derived from the service's expectedGrantKeys |
| 77 | + // (the SINGLE rule source shared with grantForInvitation): the cron never |
| 78 | + // re-encodes the side rules, so a new guard (e.g. #3833) can never drift. |
| 79 | + const candidates = []; |
| 80 | + for (const invite of accepted) { |
| 81 | + const expected = BillingReferralService.expectedGrantKeys(invite, cfg).map(({ key }) => key); |
| 82 | + if (expected.length > 0) candidates.push({ invite, expected }); |
| 83 | + } |
| 84 | + |
| 85 | + const allKeys = candidates.flatMap((c) => c.expected); |
| 86 | + const existing = new Set(await BillingExtraBalanceRepository.findExistingRefIds(allKeys)); |
| 87 | + |
| 88 | + let backfilled = 0; |
| 89 | + let pending = 0; |
| 90 | + let errors = 0; |
| 91 | + |
| 92 | + for (const { invite, expected } of candidates) { |
| 93 | + if (expected.every((key) => existing.has(key))) continue; // fully granted |
| 94 | + try { |
| 95 | + const result = await BillingReferralService.grantForInvitation({ |
| 96 | + invitationId: String(invite._id), |
| 97 | + invitedBy: invite.invitedBy ? String(invite.invitedBy) : null, |
| 98 | + acceptedUserId: invite.acceptedUserId ? String(invite.acceptedUserId) : null, |
| 99 | + }); |
| 100 | + const sides = [result.referrer, result.referee].filter(Boolean); |
| 101 | + const applied = sides.filter((s) => s.applied).length; |
| 102 | + // `no_organization` = the actor has no workspace yet (e.g. email verification |
| 103 | + // pending) — stays pending, retried on the next run once the org exists. |
| 104 | + const waiting = sides.filter((s) => s.reason === 'no_organization').length; |
| 105 | + if (applied > 0) { |
| 106 | + backfilled += applied; |
| 107 | + logger.info('[cron.referralReconcile] back-filled', { invitationId: String(invite._id), applied }); |
| 108 | + } |
| 109 | + if (waiting > 0) pending += waiting; |
| 110 | + } catch (err) { |
| 111 | + errors += 1; |
| 112 | + logger.error('[cron.referralReconcile] grantForInvitation failed', { |
| 113 | + invitationId: String(invite._id), |
| 114 | + err: err?.message, |
| 115 | + stack: err?.stack, |
| 116 | + }); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + logger.info('[cron.referralReconcile] complete', { |
| 121 | + accepted: accepted.length, |
| 122 | + backfilled, |
| 123 | + pending, |
| 124 | + errors, |
| 125 | + durationMs: Date.now() - startMs, |
| 126 | + }); |
| 127 | + process.exitCode = errors > 0 ? 1 : 0; |
| 128 | + } finally { |
| 129 | + // releaseLock failure is non-fatal: lock auto-expires on TTL. |
| 130 | + // Log separately to preserve any original work error. |
| 131 | + try { |
| 132 | + await releaseLock({ name: LOCK_NAME, holder: lockHolder }); |
| 133 | + } catch (releaseErr) { |
| 134 | + logger.error('[cron.referralReconcile] failed to release lock — will auto-expire on TTL', { |
| 135 | + err: releaseErr, |
| 136 | + cron: LOCK_NAME, |
| 137 | + }); |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | +} catch (err) { |
| 142 | + logger.error('[cron.referralReconcile] failed', { err: err?.message, stack: err?.stack }); |
| 143 | + process.exitCode = 1; |
| 144 | +} finally { |
| 145 | + await mongooseService.disconnect?.(); |
| 146 | +} |
| 147 | +process.exit(process.exitCode ?? 0); |
0 commit comments