-
Notifications
You must be signed in to change notification settings - Fork 1.3k
feat(plans): growth add-on management cron #7530
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
Open
ErickRDev
wants to merge
6
commits into
master
Choose a base branch
from
erickr/NAN-6975/add-cron-based-growth-add-on-management
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ab540f3
feat(plans): growth add-on management cron
ErickRDev 5e0bb4b
refactor: error handling
ErickRDev 06709c1
fix: flipping actual feature flags gated by the add-on flag
ErickRDev 971fd38
fix: compile time validation of scheduling column
ErickRDev cbecd39
chore: address PR concerns
ErickRDev b98a31b
chore: address PR concerns
ErickRDev 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
11 changes: 11 additions & 0 deletions
11
packages/database/lib/migrations/20260911120000_plans_add_growth_addon_start.cjs
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,11 @@ | ||
| /** | ||
| * @param {import('knex').Knex} knex | ||
| */ | ||
| exports.up = async function (knex) { | ||
| await knex.raw(`ALTER TABLE plans ADD COLUMN IF NOT EXISTS growth_features_starts_at timestamptz`); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: The hourly growth-addon update filters on Prompt for AI agents |
||
| }; | ||
|
|
||
| /** | ||
| * @param {import('knex').Knex} knex | ||
| */ | ||
| exports.down = async function () {}; | ||
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,131 @@ | ||
| import * as cron from 'node-cron'; | ||
|
|
||
| import db from '@nangohq/database'; | ||
| import { getLocking } from '@nangohq/kvstore'; | ||
| import { getGrowthAddonFlags, getPlanDefinition, PLANS_WITH_GROWTH_ADD_ON } from '@nangohq/shared'; | ||
| import { flagHasPlan, getLogger, metrics } from '@nangohq/utils'; | ||
|
|
||
| import type { Lock } from '@nangohq/kvstore'; | ||
| import type { DBPlan, PlanDefinition } from '@nangohq/types'; | ||
|
|
||
| const logger = getLogger('cron.growthFeatures'); | ||
|
|
||
| const cronMinutes = 60; | ||
| const cronExpression = `*/${cronMinutes} * * * *`; | ||
| const lockTtlMs = cronMinutes * 60 * 1000; | ||
|
|
||
| type GrowthAddonSchedulingColumn = keyof Pick<DBPlan, 'growth_features_starts_at' | 'growth_features_ends_at'>; | ||
| type GrowthAddonOperation = 'enable' | 'disable'; | ||
|
|
||
| const growthAddonOperations = { | ||
| enable: { hasGrowthFeatures: true, schedulingColumn: 'growth_features_starts_at' }, | ||
| disable: { hasGrowthFeatures: false, schedulingColumn: 'growth_features_ends_at' } | ||
| } as const satisfies Record<GrowthAddonOperation, { hasGrowthFeatures: boolean; schedulingColumn: GrowthAddonSchedulingColumn }>; | ||
|
|
||
| export function manageGrowthAddonsCron(): void { | ||
| if (!flagHasPlan) { | ||
| return; | ||
| } | ||
|
|
||
| cron.schedule(cronExpression, async () => { | ||
| const start = Date.now(); | ||
| let success = true; | ||
| try { | ||
| await exec(); | ||
| } catch (err) { | ||
| success = false; | ||
| logger.error('Failed to execute growth add-on management cron', { err }); | ||
| } finally { | ||
| metrics.duration(metrics.Types.CRON_MANAGE_GROWTH_ADDON, Date.now() - start, { success: String(success) }); | ||
| logger.info('✅ done'); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| export async function exec(date = new Date()): Promise<void> { | ||
| const locking = await getLocking(); | ||
| let lock: Lock | undefined; | ||
| try { | ||
| lock = await locking.acquire('lock:growthFeatures:cron', lockTtlMs); | ||
| } catch (err) { | ||
| logger.info('Could not acquire lock, skipping', err); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| await reportCorruptedPlans(); | ||
| await enableGrowthAddon(date); | ||
| await disableGrowthAddon(date); | ||
| } finally { | ||
| await locking.release(lock); | ||
|
ErickRDev marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
|
||
| async function reportCorruptedPlans() { | ||
| const corrupted = await db.knex | ||
| .from<Pick<DBPlan, 'id' | 'account_id' | 'name'>>('plans') | ||
| .select('id', 'account_id', 'name') | ||
| .where('has_growth_features', true) | ||
| .whereNotIn('name', PLANS_WITH_GROWTH_ADD_ON); | ||
|
|
||
| if (corrupted.length > 0) { | ||
| for (const plan of corrupted) { | ||
| logger.error('Growth features enabled for a plan that does not support the add-on', { | ||
| planId: plan.id, | ||
| accountId: plan.account_id, | ||
| planName: plan.name | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| metrics.gauge(metrics.Types.GROWTH_ADDON_CORRUPTED_STATE_COUNT, corrupted.length); | ||
| } | ||
|
|
||
| async function enableGrowthAddon(date: Date) { | ||
| const accountIds = await updateGrowthAddonState(date, 'enable'); | ||
| if (accountIds.length > 0) { | ||
| logger.info('Enabled growth add-on for accounts.', { accountIds: accountIds }); | ||
| } | ||
| } | ||
|
|
||
| async function disableGrowthAddon(date: Date) { | ||
| const accountIds = await updateGrowthAddonState(date, 'disable'); | ||
| if (accountIds.length > 0) { | ||
| logger.info('Disabled growth add-on for accounts.', { accountIds: accountIds }); | ||
| } | ||
| } | ||
|
|
||
| async function updateGrowthAddonState(date: Date, operation: GrowthAddonOperation): Promise<number[]> { | ||
| const { hasGrowthFeatures, schedulingColumn } = growthAddonOperations[operation]; | ||
| const accountIds = await Promise.all( | ||
| getPlansWithAddonSupport().map(async (plan) => { | ||
| const addonFlags = getGrowthAddonFlags(plan, hasGrowthFeatures); | ||
|
|
||
| const updated = await db.knex | ||
| .from<DBPlan>('plans') | ||
| .where('name', plan.code) | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| .whereNotNull(schedulingColumn) | ||
| .where(schedulingColumn, '<=', date) | ||
| .update({ | ||
| has_growth_features: hasGrowthFeatures, | ||
| [schedulingColumn]: null, | ||
| ...addonFlags, | ||
| updated_at: db.knex.fn.now() | ||
| }) | ||
| .returning('account_id'); | ||
|
|
||
| return updated.map((plan) => plan.account_id); | ||
| }) | ||
| ); | ||
| return accountIds.flat(); | ||
| } | ||
|
|
||
| function getPlansWithAddonSupport(): PlanDefinition[] { | ||
| return PLANS_WITH_GROWTH_ADD_ON.map((planCode) => { | ||
| const definition = getPlanDefinition(planCode); | ||
| if (!definition) { | ||
| throw new Error(`Missing plan definition for ${planCode}`); | ||
| } | ||
| return definition; | ||
| }); | ||
| } | ||
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
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
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.