Unverified Commit 27a39ba1 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[cd] Retry preview tarball uploads with backoff and richer diagnostics (#99060)

The `upload-preview-tarballs` workflow aborted its entire run when a
single tarball upload hit a transient network error, and the logged
error did not identify which package or request had failed. One observed
run failed with `TypeError: fetch failed` (`UND_ERR_SOCKET`) after the
~78MB `next` tarball body had been written but before the response
arrived (e.g.
https://github.com/vercel/next.js/actions/runs/35721116824/job/106724007428#step:4:19).

`scripts/upload-preview-tarballs.js` now wraps each package's upload in
a retry with exponential backoff (5 attempts, 1s/2s/4s/8s). Every
failure is retried, including network-level rejections without an HTTP
status. Error messages now name the package and the failed request
phase, and non-OK responses include a truncated response body alongside
the status and response headers such as `x-vercel-id`, so the next rare
failure is actionable. A package that exhausts its retries no longer
aborts the remaining uploads; all failures are collected and reported at
the end as an `AggregateError`.
Co-authored-by: 's avatarClaude Code (kimi-k3[1m]) <noreply@anthropic.com>
parent 3950aff8
// @ts-check
const fs = require('node:fs/promises')
const path = require('node:path')
const { setTimeout: sleep } = require('node:timers/promises')
const PREVIEW_BUILDS_AUDIENCE = 'https://vercel-packages.vercel.app'
const DEFAULT_PREVIEW_BUILDS_BASE_URL =
'https://vercel-packages.vercel.app/next'
const MAX_ATTEMPTS = 5
const BASE_DELAY_MS = 1000
const MAX_BODY_SNIPPET_LENGTH = 1000
/**
* Mints a GitHub Actions OIDC token for the given audience.
*
......@@ -107,6 +112,134 @@ async function findTarballInDir(dir) {
return tgzFile ? path.join(dir, tgzFile) : null
}
/**
* Formats the diagnostics of a failed response for an error message: all
* response headers (including `x-vercel-id` on the authorize request) plus a
* snippet of the response body.
*
* @param {Response} response
* @returns {Promise<string>}
*/
async function readResponseDetails(response) {
let details = ` Response headers: ${JSON.stringify(Object.fromEntries(response.headers))}`
/** @type {string | null} */
let bodySnippet = null
try {
const bodyText = (await response.text()).trim()
if (bodyText !== '') {
bodySnippet =
bodyText.length > MAX_BODY_SNIPPET_LENGTH
? `${bodyText.slice(0, MAX_BODY_SNIPPET_LENGTH)}...`
: bodyText
}
} catch {
// A body that cannot be read carries no diagnostics.
}
if (bodySnippet !== null) {
details += ` Response body: ${bodySnippet}`
}
return details
}
/**
* Retries `fn` with exponential backoff until it succeeds or all attempts are
* exhausted. Every failure is retried, including network-level rejections
* where no response was received.
*
* @template T
* @param {string} operationName
* @param {() => Promise<T>} fn
* @returns {Promise<T>}
*/
async function withRetry(operationName, fn) {
let attempt = 1
while (true) {
try {
return await fn()
} catch (error) {
if (attempt === MAX_ATTEMPTS) {
throw error
}
const delayMs = Math.pow(2, attempt - 1) * BASE_DELAY_MS
console.info(
`${operationName} failed (attempt ${attempt}/${MAX_ATTEMPTS}), retrying in ${delayMs}ms:`,
error
)
await sleep(delayMs)
attempt++
}
}
}
/**
* Authorizes and performs a single upload attempt for one package tarball.
* vercel-packages authorizes the OIDC token and answers with a presigned
* upload URL scoped to this exact blob path. The bytes flow directly to the
* store, so the tarball size is not limited by a function's request body
* limit.
*
* @param {object} options
* @param {string} options.baseUrl
* @param {string} options.githubHeadSha
* @param {string} options.packageName
* @param {string} options.tarballPath
* @param {() => Promise<string>} options.getOidcToken
* @returns {Promise<string>} the download URL of the uploaded tarball
*/
async function uploadPackageTarball({
baseUrl,
githubHeadSha,
packageName,
tarballPath,
getOidcToken,
}) {
/** @type {Response} */
let response
try {
response = await fetch(
`${baseUrl}/commits/${githubHeadSha}/${packageName}`,
{
method: 'POST',
headers: { authorization: `Bearer ${await getOidcToken()}` },
}
)
} catch (error) {
throw new Error(
`Failed to authorize the upload of ${packageName}: the request failed before a response was received`,
{ cause: error }
)
}
if (!response.ok) {
throw new Error(
`Failed to authorize the upload of ${packageName}: ${response.status}.${await readResponseDetails(response)}`
)
}
/** @type {{ url: string, downloadUrl: string }} */
const body = await response.json()
const fileBuffer = await fs.readFile(tarballPath)
/** @type {Response} */
let putResponse
try {
putResponse = await fetch(body.url, {
method: 'PUT',
body: new Uint8Array(fileBuffer),
headers: { 'content-type': 'application/gzip' },
})
} catch (error) {
throw new Error(
`Failed to upload ${packageName}: the request failed before a response was received`,
{ cause: error }
)
}
if (!putResponse.ok) {
throw new Error(
`Failed to upload ${packageName}: ${putResponse.status}.${await readResponseDetails(putResponse)}`
)
}
return body.downloadUrl
}
async function main() {
const [githubHeadSha, tarballDirectory] = process.argv.slice(2)
if (!githubHeadSha || !tarballDirectory) {
......@@ -119,41 +252,34 @@ async function main() {
process.env.PREVIEW_BUILDS_BASE_URL || DEFAULT_PREVIEW_BUILDS_BASE_URL
const getOidcToken = createGitHubOidcTokenGetter()
/** @type {Error[]} */
const failedUploads = []
for await (const { packageName, tarballPath } of findTarballs(
tarballDirectory
)) {
// vercel-packages authorizes the OIDC token and answers with a presigned
// upload URL scoped to this exact blob path. The bytes flow directly to
// the store, so the tarball size is not limited by a function's request
// body limit.
const response = await fetch(
`${baseUrl}/commits/${githubHeadSha}/${packageName}`,
{
method: 'POST',
headers: { authorization: `Bearer ${await getOidcToken()}` },
}
)
if (!response.ok) {
throw new Error(
`Failed to authorize the upload of ${packageName}: ${response.status}. ` +
`Response headers: ${JSON.stringify(Object.fromEntries(response.headers))}`
try {
const downloadUrl = await withRetry(`Upload of ${packageName}`, () =>
uploadPackageTarball({
baseUrl,
githubHeadSha,
packageName,
tarballPath,
getOidcToken,
})
)
}
const body = await response.json()
const fileBuffer = await fs.readFile(tarballPath)
const putResponse = await fetch(body.url, {
method: 'PUT',
body: new Uint8Array(fileBuffer),
headers: { 'content-type': 'application/gzip' },
})
if (!putResponse.ok) {
throw new Error(
`Failed to upload ${packageName}: ${putResponse.status}. ` +
`Response headers: ${JSON.stringify(Object.fromEntries(putResponse.headers))}`
console.info(`Uploaded ${packageName} -> ${downloadUrl}`)
} catch (error) {
failedUploads.push(
new Error(`Failed to upload ${packageName}`, { cause: error })
)
}
console.info(`Uploaded ${packageName} -> ${body.downloadUrl}`)
}
if (failedUploads.length > 0) {
// eslint-disable-next-line no-undef -- Defined in Node.js
throw new AggregateError(
failedUploads,
`Failed to upload ${failedUploads.length} package(s)`
)
}
console.info('All tarballs uploaded')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment