|
| 1 | +import { TEST_USER_ID } from '@codebuff/common/old-constants' |
| 2 | +import { withRetry, withTimeout } from '@codebuff/common/util/promise' |
| 3 | +import db from '@codebuff/internal/db' |
| 4 | +import * as schema from '@codebuff/internal/db/schema' |
| 5 | +import { stripeServer } from '@codebuff/internal/util/stripe' |
| 6 | +import { eq } from 'drizzle-orm' |
| 7 | + |
| 8 | +import type { Logger } from '@codebuff/common/types/contracts/logger' |
| 9 | + |
| 10 | +const STRIPE_METER_EVENT_NAME = 'credits' |
| 11 | +const STRIPE_METER_REQUEST_TIMEOUT_MS = 10_000 |
| 12 | + |
| 13 | +function shouldAttemptStripeMetering(): boolean { |
| 14 | + // Avoid sending Stripe metering events in CI/tests, and when Stripe isn't configured. |
| 15 | + if (process.env.CI === 'true' || process.env.CI === '1') return false |
| 16 | + if (process.env.NODE_ENV === 'test') return false |
| 17 | + return Boolean(process.env.STRIPE_SECRET_KEY) |
| 18 | +} |
| 19 | + |
| 20 | +export async function reportPurchasedCreditsToStripe(params: { |
| 21 | + userId: string |
| 22 | + stripeCustomerId?: string | null |
| 23 | + purchasedCredits: number |
| 24 | + logger: Logger |
| 25 | + /** |
| 26 | + * Optional unique identifier used for Stripe idempotency + debugging. |
| 27 | + * For message-based usage, pass the message ID. |
| 28 | + */ |
| 29 | + eventId?: string |
| 30 | + /** |
| 31 | + * Optional timestamp for the usage event. |
| 32 | + * Defaults to "now". |
| 33 | + */ |
| 34 | + timestamp?: Date |
| 35 | + /** |
| 36 | + * Optional additional payload fields (must be strings). |
| 37 | + */ |
| 38 | + extraPayload?: Record<string, string> |
| 39 | +}): Promise<void> { |
| 40 | + const { |
| 41 | + userId, |
| 42 | + stripeCustomerId: providedStripeCustomerId, |
| 43 | + purchasedCredits, |
| 44 | + logger, |
| 45 | + eventId, |
| 46 | + timestamp = new Date(), |
| 47 | + extraPayload, |
| 48 | + } = params |
| 49 | + |
| 50 | + if (purchasedCredits <= 0) return |
| 51 | + if (userId === TEST_USER_ID) return |
| 52 | + if (!shouldAttemptStripeMetering()) return |
| 53 | + |
| 54 | + const logContext = { userId, purchasedCredits, eventId } |
| 55 | + |
| 56 | + let stripeCustomerId = providedStripeCustomerId |
| 57 | + if (stripeCustomerId === undefined) { |
| 58 | + let user: { stripe_customer_id: string | null } | undefined |
| 59 | + try { |
| 60 | + user = await db.query.user.findFirst({ |
| 61 | + where: eq(schema.user.id, userId), |
| 62 | + columns: { stripe_customer_id: true }, |
| 63 | + }) |
| 64 | + } catch (error) { |
| 65 | + logger.error( |
| 66 | + { ...logContext, error }, |
| 67 | + 'Failed to fetch user for Stripe metering', |
| 68 | + ) |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + stripeCustomerId = user?.stripe_customer_id ?? null |
| 73 | + } |
| 74 | + if (!stripeCustomerId) { |
| 75 | + logger.warn(logContext, 'Skipping Stripe metering (missing stripe_customer_id)') |
| 76 | + return |
| 77 | + } |
| 78 | + |
| 79 | + const stripeTimestamp = Math.floor(timestamp.getTime() / 1000) |
| 80 | + const idempotencyKey = eventId ? `meter-${eventId}` : undefined |
| 81 | + |
| 82 | + try { |
| 83 | + await withTimeout( |
| 84 | + withRetry( |
| 85 | + () => |
| 86 | + stripeServer.billing.meterEvents.create( |
| 87 | + { |
| 88 | + event_name: STRIPE_METER_EVENT_NAME, |
| 89 | + timestamp: stripeTimestamp, |
| 90 | + payload: { |
| 91 | + stripe_customer_id: stripeCustomerId, |
| 92 | + value: purchasedCredits.toString(), |
| 93 | + ...(eventId ? { event_id: eventId } : {}), |
| 94 | + ...(extraPayload ?? {}), |
| 95 | + }, |
| 96 | + }, |
| 97 | + idempotencyKey ? { idempotencyKey } : undefined, |
| 98 | + ), |
| 99 | + { |
| 100 | + maxRetries: 3, |
| 101 | + retryIf: (error: any) => |
| 102 | + error?.type === 'StripeConnectionError' || |
| 103 | + error?.type === 'StripeAPIError' || |
| 104 | + error?.type === 'StripeRateLimitError', |
| 105 | + onRetry: (error: any, attempt: number) => { |
| 106 | + logger.warn( |
| 107 | + { ...logContext, attempt, error }, |
| 108 | + 'Retrying Stripe metering call', |
| 109 | + ) |
| 110 | + }, |
| 111 | + retryDelayMs: 500, |
| 112 | + }, |
| 113 | + ), |
| 114 | + STRIPE_METER_REQUEST_TIMEOUT_MS, |
| 115 | + `Stripe metering timed out after ${STRIPE_METER_REQUEST_TIMEOUT_MS}ms`, |
| 116 | + ) |
| 117 | + } catch (error) { |
| 118 | + logger.error({ ...logContext, error }, 'Failed to report purchased credits to Stripe') |
| 119 | + } |
| 120 | +} |
0 commit comments