|
| 1 | +import { randomBytes } from 'node:crypto'; |
| 2 | +import { deleteWorker, deployWorker, keepsWorker, waitForWorker } from './deployed-worker.mjs'; |
| 3 | + |
| 4 | +const WORKER_PREFIX = 'e2e-send-to-sentry'; |
| 5 | + |
| 6 | +/** |
| 7 | + * In CI the name follows the ref, so `develop`, `master` and every PR get a stable Worker that the |
| 8 | + * next run of the same ref overwrites. Pull request refs look like `123/merge` and merge queue refs |
| 9 | + * like `gh-readonly-queue/<base>/pr-123-<sha>`; both map to the PR's Worker. |
| 10 | + */ |
| 11 | +export function getWorkerName() { |
| 12 | + if (!process.env.GITHUB_ACTIONS) { |
| 13 | + return `${WORKER_PREFIX}-local-${randomBytes(3).toString('hex')}`; |
| 14 | + } |
| 15 | + |
| 16 | + const { GITHUB_EVENT_NAME, GITHUB_REF_NAME = '' } = process.env; |
| 17 | + const prNumber = |
| 18 | + GITHUB_EVENT_NAME === 'pull_request' ? GITHUB_REF_NAME.split('/')[0] : /\/pr-(\d+)-/.exec(GITHUB_REF_NAME)?.[1]; |
| 19 | + const ref = prNumber ? `pr-${prNumber}` : GITHUB_REF_NAME; |
| 20 | + // Worker names allow lowercase alphanumerics and dashes only, up to 63 characters. |
| 21 | + const slug = ref.toLowerCase().replace(/[^a-z0-9]+/g, '-'); |
| 22 | + |
| 23 | + return `${WORKER_PREFIX}-${slug}`.slice(0, 63).replace(/-+$/, ''); |
| 24 | +} |
| 25 | + |
| 26 | +export default async function globalSetup() { |
| 27 | + const { CLOUDFLARE_ACCOUNT_ID, E2E_TEST_DSN } = process.env; |
| 28 | + |
| 29 | + // Wrangler authenticates with `CLOUDFLARE_API_TOKEN` (CI) or a `wrangler login` session (local), |
| 30 | + // but it cannot pick an account on its own outside of a terminal. |
| 31 | + if (!CLOUDFLARE_ACCOUNT_ID) { |
| 32 | + throw new Error('CLOUDFLARE_ACCOUNT_ID must be set to deploy the test worker.'); |
| 33 | + } |
| 34 | + |
| 35 | + const workerName = getWorkerName(); |
| 36 | + const workerUrl = deployWorker(workerName, E2E_TEST_DSN); |
| 37 | + process.env.E2E_TEST_WORKER_NAME = workerName; |
| 38 | + |
| 39 | + try { |
| 40 | + await waitForWorker(workerUrl); |
| 41 | + } catch (error) { |
| 42 | + if (!keepsWorker()) { |
| 43 | + try { |
| 44 | + deleteWorker(workerName); |
| 45 | + } catch (deleteError) { |
| 46 | + // The unreachable worker is the failure to report, not the cleanup. |
| 47 | + console.error(`Failed to delete worker ${workerName}:`, deleteError); |
| 48 | + } |
| 49 | + } |
| 50 | + throw error; |
| 51 | + } |
| 52 | + |
| 53 | + process.env.E2E_TEST_WORKER_URL = workerUrl; |
| 54 | +} |
0 commit comments