bulk-cancel-subscriptions.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #!/usr/bin/env node
  2. /**
  3. * This script bulk cancels active Stripe subscriptions immediately without proration.
  4. *
  5. * NOTE: this will email customers to inform them of the cancellation unless you turn off
  6. * the cancellation automation in Stripe beforehand: https://dashboard.stripe.com/<account>/revenue-recovery/automations
  7. *
  8. * Usage:
  9. * node scripts/stripe/bulk-cancel-subscriptions.mjs [OPTS] [INPUT-FILE]
  10. *
  11. * Options:
  12. * --output PATH Output file path (default: /tmp/bulk_cancel_output_<timestamp>.csv)
  13. * Use '-' to write to stdout
  14. * --commit Apply changes (without this flag, runs in dry-run mode)
  15. * --concurrency N Number of customers to process concurrently (default: 10)
  16. * --stripe-rate-limit N Requests per second for Stripe (default: 50)
  17. * --stripe-api-retries N Number of retries on Stripe 429s (default: 5)
  18. * --stripe-retry-delay-ms N Delay between Stripe retries in ms (default: 1000)
  19. * --help Show a help message
  20. *
  21. * CSV Input Format:
  22. * The CSV must have the following columns:
  23. * - stripe_customer_id: Stripe customer id
  24. * - target_stripe_account: Either 'stripe-uk' or 'stripe-us'
  25. *
  26. * Output:
  27. * Writes a CSV with columns:
  28. * - stripe_customer_id: The customer id processed
  29. * - target_stripe_account: The Stripe account
  30. * - subscription_id: The subscription id that was cancelled (if found)
  31. * - status: Result status (cancelled, validated, no-subscription, already-cancelled, or error)
  32. * - note: Additional information about the status
  33. */
  34. import fs from 'node:fs'
  35. import path from 'node:path'
  36. import * as csv from 'csv'
  37. import minimist from 'minimist'
  38. import PQueue from 'p-queue'
  39. import { z } from '../../app/src/infrastructure/Validation.mjs'
  40. import { scriptRunner } from '../lib/ScriptRunner.mjs'
  41. import { getRegionClient } from '../../modules/subscriptions/app/src/StripeClient.mjs'
  42. import { ReportError } from './helpers.mjs'
  43. import {
  44. createRateLimitedApiWrappers,
  45. DEFAULT_STRIPE_RATE_LIMIT,
  46. DEFAULT_STRIPE_API_RETRIES,
  47. DEFAULT_STRIPE_RETRY_DELAY_MS,
  48. } from './RateLimiter.mjs'
  49. const DEFAULT_CONCURRENCY = 10
  50. // rate limiters - initialized in main()
  51. let rateLimiters
  52. function usage() {
  53. console.error(`Usage: node scripts/stripe/bulk-cancel-subscriptions.mjs [OPTS] [INPUT-FILE]
  54. Options:
  55. --output PATH Output file path (default: /tmp/bulk_cancel_output_<timestamp>.csv)
  56. Use '-' to write to stdout
  57. --commit Apply changes (without this, runs in dry-run mode)
  58. --concurrency N Number of customers to process concurrently (default: ${DEFAULT_CONCURRENCY})
  59. --stripe-rate-limit N Requests per second for Stripe (default: ${DEFAULT_STRIPE_RATE_LIMIT})
  60. --stripe-api-retries N Number of retries on Stripe 429s (default: ${DEFAULT_STRIPE_API_RETRIES})
  61. --stripe-retry-delay-ms N Delay between Stripe retries in ms (default: ${DEFAULT_STRIPE_RETRY_DELAY_MS})
  62. --help Show this help message
  63. `)
  64. }
  65. async function main(trackProgress) {
  66. const opts = parseArgs()
  67. const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  68. const outputFile = opts.output ?? `/tmp/bulk_cancel_output_${timestamp}.csv`
  69. // initialize rate limiters
  70. rateLimiters = createRateLimitedApiWrappers({
  71. stripeRateLimit: opts.stripeRateLimit,
  72. stripeApiRetries: opts.stripeApiRetries,
  73. stripeRetryDelayMs: opts.stripeRetryDelayMs,
  74. })
  75. await trackProgress('Starting bulk subscription cancellation for Stripe')
  76. await trackProgress(`Run mode: ${opts.commit ? 'COMMIT' : 'DRY RUN'}`)
  77. await trackProgress(`Rate limit: Stripe ${opts.stripeRateLimit}/s`)
  78. await trackProgress(`Concurrency: ${opts.concurrency}`)
  79. const inputStream = opts.inputFile
  80. ? fs.createReadStream(opts.inputFile)
  81. : process.stdin
  82. const csvReader = getCsvReader(inputStream)
  83. const csvWriter = getCsvWriter(outputFile)
  84. await trackProgress(`Output: ${outputFile === '-' ? 'stdout' : outputFile}`)
  85. let processedCount = 0
  86. let successCount = 0
  87. let errorCount = 0
  88. const queue = new PQueue({ concurrency: opts.concurrency })
  89. const maxQueueSize = opts.concurrency
  90. try {
  91. for await (const input of csvReader) {
  92. if (queue.size >= maxQueueSize) {
  93. await queue.onSizeLessThan(maxQueueSize)
  94. }
  95. queue.add(async () => {
  96. processedCount++
  97. try {
  98. const result = await processCancellation(input, opts.commit)
  99. csvWriter.write({
  100. stripe_customer_id: input.stripe_customer_id,
  101. target_stripe_account: input.target_stripe_account,
  102. subscription_id: result.subscriptionId || '',
  103. status: result.status,
  104. note:
  105. result.note ||
  106. (opts.commit ? '' : 'dry run - no changes applied'),
  107. })
  108. if (result.status === 'cancelled' || result.status === 'validated') {
  109. successCount++
  110. } else {
  111. errorCount++
  112. }
  113. if (processedCount % 10 === 0) {
  114. await trackProgress(
  115. `Processed ${processedCount} customers (${successCount} ${opts.commit ? 'cancelled' : 'validated'}, ${errorCount} errors)`
  116. )
  117. }
  118. } catch (err) {
  119. errorCount++
  120. if (err instanceof ReportError) {
  121. csvWriter.write({
  122. stripe_customer_id: input.stripe_customer_id,
  123. target_stripe_account: input.target_stripe_account,
  124. subscription_id: '',
  125. status: err.status,
  126. note: err.message,
  127. })
  128. } else {
  129. csvWriter.write({
  130. stripe_customer_id: input.stripe_customer_id,
  131. target_stripe_account: input.target_stripe_account,
  132. subscription_id: '',
  133. status: 'error',
  134. note: err.message,
  135. })
  136. await trackProgress(
  137. `Error processing ${input.stripe_customer_id}: ${err.message}`
  138. )
  139. }
  140. }
  141. })
  142. }
  143. } finally {
  144. await queue.onIdle()
  145. }
  146. await trackProgress(`✅ Total processed: ${processedCount}`)
  147. if (opts.commit) {
  148. await trackProgress(`✅ Successfully cancelled: ${successCount}`)
  149. } else {
  150. await trackProgress(`✅ Successfully validated: ${successCount}`)
  151. await trackProgress('ℹ️ DRY RUN: No changes were applied')
  152. }
  153. await trackProgress(`❌ Errors: ${errorCount}`)
  154. await trackProgress('🎉 Script completed!')
  155. csvWriter.end()
  156. }
  157. function parseArgs() {
  158. const args = minimist(process.argv.slice(2), {
  159. string: [
  160. 'output',
  161. 'concurrency',
  162. 'stripe-rate-limit',
  163. 'stripe-api-retries',
  164. 'stripe-retry-delay-ms',
  165. ],
  166. boolean: ['commit', 'help'],
  167. default: {
  168. commit: false,
  169. concurrency: DEFAULT_CONCURRENCY,
  170. 'stripe-rate-limit': DEFAULT_STRIPE_RATE_LIMIT,
  171. 'stripe-api-retries': DEFAULT_STRIPE_API_RETRIES,
  172. 'stripe-retry-delay-ms': DEFAULT_STRIPE_RETRY_DELAY_MS,
  173. },
  174. unknown: arg => {
  175. if (arg.startsWith('-')) {
  176. console.error(`Unknown option: ${arg}`)
  177. usage()
  178. process.exit(1)
  179. }
  180. return true
  181. },
  182. })
  183. if (args.help) {
  184. usage()
  185. process.exit(0)
  186. }
  187. const inputFile = args._[0]
  188. const paramsSchema = z.object({
  189. output: z.string().optional(),
  190. commit: z.boolean(),
  191. concurrency: z.number().int().positive(),
  192. stripeRateLimit: z.number().positive(),
  193. stripeApiRetries: z.number().int().nonnegative(),
  194. stripeRetryDelayMs: z.number().int().nonnegative(),
  195. inputFile: z.string().optional(),
  196. })
  197. try {
  198. return paramsSchema.parse({
  199. output: args.output,
  200. commit: args.commit,
  201. concurrency: Number(args.concurrency),
  202. stripeRateLimit: Number(args['stripe-rate-limit']),
  203. stripeApiRetries: Number(args['stripe-api-retries']),
  204. stripeRetryDelayMs: Number(args['stripe-retry-delay-ms']),
  205. inputFile,
  206. })
  207. } catch (err) {
  208. console.error('Invalid arguments:', err.message)
  209. usage()
  210. process.exit(1)
  211. }
  212. }
  213. function getCsvReader(inputStream) {
  214. const parser = csv.parse({ columns: true })
  215. inputStream.pipe(parser)
  216. return parser
  217. }
  218. function getCsvWriter(outputFile) {
  219. if (outputFile === '-') {
  220. const writer = csv.stringify({
  221. columns: [
  222. 'stripe_customer_id',
  223. 'target_stripe_account',
  224. 'subscription_id',
  225. 'status',
  226. 'note',
  227. ],
  228. header: true,
  229. })
  230. writer.on('error', err => {
  231. console.error(err)
  232. process.exit(1)
  233. })
  234. writer.pipe(process.stdout)
  235. return writer
  236. }
  237. fs.mkdirSync(path.dirname(outputFile), { recursive: true })
  238. const outputStream = fs.createWriteStream(outputFile)
  239. const writer = csv.stringify({
  240. columns: [
  241. 'stripe_customer_id',
  242. 'target_stripe_account',
  243. 'subscription_id',
  244. 'status',
  245. 'note',
  246. ],
  247. header: true,
  248. })
  249. writer.on('error', err => {
  250. console.error(err)
  251. process.exit(1)
  252. })
  253. writer.pipe(outputStream)
  254. return writer
  255. }
  256. async function processCancellation(input, commit) {
  257. const {
  258. stripe_customer_id: customerId,
  259. target_stripe_account: targetStripeAccount,
  260. } = input
  261. // get Stripe client for the target account (strip 'stripe-' prefix if present)
  262. const region = targetStripeAccount.replace(/^stripe-/, '')
  263. const stripeClient = getRegionClient(region)
  264. // fetch customer with subscriptions
  265. let customer
  266. try {
  267. customer = await rateLimiters.requestWithRetries(
  268. stripeClient.serviceName,
  269. () => stripeClient.getCustomerById(customerId, ['subscriptions']),
  270. {
  271. operation: 'getCustomerById',
  272. customerId,
  273. region: stripeClient.serviceName,
  274. }
  275. )
  276. } catch (err) {
  277. throw new ReportError(
  278. 'customer-not-found',
  279. `Customer not found: ${err.message}`
  280. )
  281. }
  282. // check for active subscriptions
  283. if (!customer.subscriptions || customer.subscriptions.data.length === 0) {
  284. throw new ReportError('no-subscriptions', 'Customer has no subscriptions')
  285. }
  286. // find the subscription with migration metadata
  287. const migrationSubscription = customer.subscriptions.data.find(
  288. sub => sub.metadata?.recurly_to_stripe_migration_status === 'in_progress'
  289. )
  290. if (!migrationSubscription) {
  291. throw new ReportError(
  292. 'no-migration-subscription',
  293. 'Could not find a subscription with migration metadata to cancel'
  294. )
  295. }
  296. // in dry-run mode, just validate
  297. if (!commit) {
  298. return {
  299. status: 'validated',
  300. note: 'Subscription can be cancelled',
  301. subscriptionId: migrationSubscription.id,
  302. }
  303. }
  304. // cancel the subscription immediately
  305. try {
  306. await rateLimiters.requestWithRetries(
  307. stripeClient.serviceName,
  308. () => stripeClient.terminateSubscription(migrationSubscription.id),
  309. {
  310. operation: 'terminateSubscription',
  311. subscriptionId: migrationSubscription.id,
  312. region: stripeClient.serviceName,
  313. }
  314. )
  315. return {
  316. status: 'cancelled',
  317. note: `Cancelled subscription ${migrationSubscription.id}`,
  318. subscriptionId: migrationSubscription.id,
  319. }
  320. } catch (err) {
  321. throw new ReportError(
  322. 'cancellation-failed',
  323. `Failed to cancel subscription: ${err.message}`
  324. )
  325. }
  326. }
  327. try {
  328. await scriptRunner(main)
  329. process.exit(0)
  330. } catch (error) {
  331. console.error(error)
  332. process.exit(1)
  333. }