Changeset 63449
- Timestamp:
- 09/03/2026 06:55:31 PM (2 months ago)
- Location:
- branches/7.0/tools/gutenberg
- Files:
-
- 2 edited
-
download.js (modified) (10 diffs)
-
utils.js (modified) (6 diffs)
Legend:
- Unmodified
- Added
- Removed
-
branches/7.0/tools/gutenberg/download.js
r62599 r63449 1 1 #!/usr/bin/env node 2 /* global AbortSignal */ 2 3 3 4 /** … … 5 6 * 6 7 * This script downloads a pre-built Gutenberg tar.gz artifact from the GitHub 7 * Container Registry and extracts it into the ./gutenberg directory. Any 8 * existing gutenberg directory is removed before extraction. 8 * Container Registry and extracts it into the ./gutenberg directory. The 9 * archive is downloaded and verified (SHA-256 and manifest size) before 10 * extraction; the existing gutenberg directory is then removed and replaced 11 * with the extracted contents. 9 12 * 10 13 * The artifact is identified by the "gutenberg.sha" value in the root … … 21 24 22 25 const { spawn } = require( 'child_process' ); 26 const crypto = require( 'crypto' ); 23 27 const fs = require( 'fs' ); 28 const os = require( 'os' ); 29 const path = require( 'path' ); 24 30 const { Readable } = require( 'stream' ); 25 31 const { pipeline } = require( 'stream/promises' ); 26 const zlib = require( 'zlib' );32 const { Transform } = require( 'stream' ); 27 33 const { 28 34 gutenbergDir, … … 32 38 } = require( './utils' ); 33 39 40 const MAX_DOWNLOAD_ATTEMPTS = 3; 41 const RETRY_DELAY_MS = 2000; 42 const DOWNLOAD_TIMEOUT_MS = 120000; 43 44 /** 45 * Convert bytes into a readable string for download diagnostics. 46 * 47 * @param {number} bytes Number of bytes. 48 * @return {string} Formatted byte count. 49 */ 50 function formatBytes( bytes ) { 51 return `${ ( bytes / 1024 / 1024 ).toFixed( 2 ) } MiB (${ bytes } bytes)`; 52 } 53 54 /** 55 * Wait before retrying a failed download. 56 * 57 * @param {number} milliseconds Time to wait in milliseconds. 58 * @return {Promise<void>} Resolves after the requested delay. 59 */ 60 function delay( milliseconds ) { 61 return new Promise( ( resolve ) => setTimeout( resolve, milliseconds ) ); 62 } 63 64 /** 65 * Create an error that retains the HTTP status code for retry decisions. 66 * 67 * @param {string} message Error message. 68 * @param {number} status HTTP status code. 69 * @return {Error & { status: number }} Error with status code. 70 */ 71 function createHttpError( message, status ) { 72 const error = /** @type {Error & { status: number }} */ ( new Error( message ) ); 73 error.status = status; 74 return error; 75 } 76 77 /** 78 * Determine whether a failed download might succeed on a later attempt. 79 * 80 * @param {Error & { status?: number }} error Download error. 81 * @return {boolean} Whether the error is retryable. 82 */ 83 function isRetryableDownloadError( error ) { 84 return ! error.status || error.status === 408 || error.status === 429 || error.status >= 500; 85 } 86 87 /** 88 * Extract a SHA-256 hash from an OCI layer digest. 89 * 90 * @param {string} digest OCI layer digest. 91 * @return {string} Expected SHA-256 hash. 92 * @throws {Error} If the digest is not a SHA-256 digest. 93 */ 94 function getExpectedSha256( digest ) { 95 const match = /^sha256:([a-f0-9]{64})$/i.exec( digest ); 96 if ( ! match ) { 97 throw new Error( `Unsupported OCI layer digest: ${ digest }` ); 98 } 99 100 return match[ 1 ].toLowerCase(); 101 } 102 103 /** 104 * Download a blob to disk and verify its SHA-256 digest and byte count. 105 * 106 * @param {string} url Blob URL. 107 * @param {string} token Bearer token for GHCR. 108 * @param {string} digest OCI layer digest. 109 * @param {number|undefined} expectedSize Expected layer size from the manifest. 110 * @param {string} destination Path where the compressed blob is written. 111 * @return {Promise<void>} Resolves after the download is verified. 112 */ 113 async function downloadAndVerifyBlob( url, token, digest, expectedSize, destination ) { 114 const expectedSha256 = getExpectedSha256( digest ); 115 const response = await fetch( url, { 116 headers: { 117 Authorization: `Bearer ${ token }`, 118 }, 119 signal: AbortSignal.timeout( DOWNLOAD_TIMEOUT_MS ), 120 } ); 121 122 console.log( 123 ` Response: ${ response.status } ${ response.statusText } from ${ new URL( response.url ).hostname }` 124 ); 125 126 if ( ! response.ok ) { 127 throw createHttpError( 128 `Failed to download blob: ${ response.status } ${ response.statusText }`, 129 response.status 130 ); 131 } 132 133 if ( ! response.body ) { 134 throw new Error( 'Blob response has no body' ); 135 } 136 137 const contentLength = Number( response.headers.get( 'content-length' ) ); 138 if ( Number.isFinite( contentLength ) && contentLength > 0 ) { 139 console.log( ` Content-Length: ${ formatBytes( contentLength ) }` ); 140 } 141 if ( expectedSize ) { 142 console.log( ` Manifest size: ${ formatBytes( expectedSize ) }` ); 143 } 144 145 let downloadedBytes = 0; 146 const hash = crypto.createHash( 'sha256' ); 147 const meter = new Transform( { 148 transform( chunk, _encoding, callback ) { 149 downloadedBytes += chunk.length; 150 hash.update( chunk ); 151 callback( null, chunk ); 152 }, 153 } ); 154 155 try { 156 await pipeline( 157 Readable.fromWeb( 158 /** @type {import('stream/web').ReadableStream} */ ( response.body ) 159 ), 160 meter, 161 fs.createWriteStream( destination ) 162 ); 163 } catch ( error ) { 164 throw new Error( 165 `Download interrupted after ${ formatBytes( downloadedBytes ) }: ${ /** @type {Error} */ ( error ).message }` 166 ); 167 } 168 169 if ( expectedSize && downloadedBytes !== expectedSize ) { 170 throw new Error( 171 `Downloaded ${ formatBytes( downloadedBytes ) }, but manifest size was ${ formatBytes( expectedSize ) }` 172 ); 173 } 174 175 const actualSha256 = hash.digest( 'hex' ); 176 if ( actualSha256 !== expectedSha256 ) { 177 throw new Error( 178 `SHA-256 mismatch: expected ${ expectedSha256 } but received ${ actualSha256 }` 179 ); 180 } 181 182 console.log( `✅ Downloaded ${ formatBytes( downloadedBytes ) } and verified SHA-256` ); 183 } 184 185 /** 186 * Download a blob with bounded retries and remove incomplete files between attempts. 187 * 188 * The GHCR bearer token can age out during a long retry window. If a 401 is 189 * encountered, a fresh token is fetched once (via `fetchGhcrToken`) and the 190 * download is retried with it. 191 * 192 * @param {string} url Blob URL. 193 * @param {string} token Bearer token for GHCR. 194 * @param {string} digest OCI layer digest. 195 * @param {number|undefined} expectedSize Expected layer size from the manifest. 196 * @param {string} ghcrRepo The "owner/repo/package" path on ghcr.io, used to refresh an expired token. 197 * @return {Promise<string>} Path to the verified compressed blob. 198 */ 199 async function downloadBlobWithRetries( url, token, digest, expectedSize, ghcrRepo ) { 200 const destination = path.join( 201 os.tmpdir(), 202 `wordpress-gutenberg-${ process.pid }.tar.gz` 203 ); 204 205 let currentToken = token; 206 let hasRefetchedToken = false; 207 208 for ( let attempt = 1; attempt <= MAX_DOWNLOAD_ATTEMPTS; attempt++ ) { 209 console.log( `\n📥 Download attempt ${ attempt }/${ MAX_DOWNLOAD_ATTEMPTS }...` ); 210 fs.rmSync( destination, { force: true } ); 211 212 try { 213 await downloadAndVerifyBlob( 214 url, 215 currentToken, 216 digest, 217 expectedSize, 218 destination 219 ); 220 return destination; 221 } catch ( error ) { 222 const downloadError = /** @type {Error & { status?: number }} */ ( error ); 223 fs.rmSync( destination, { force: true } ); 224 console.error( `❌ Download attempt ${ attempt } failed: ${ downloadError.message }` ); 225 226 if ( 227 downloadError.status === 401 && 228 ! hasRefetchedToken && 229 attempt < MAX_DOWNLOAD_ATTEMPTS 230 ) { 231 hasRefetchedToken = true; 232 console.log( ' Bearer token may have expired mid-retry; fetching a fresh token...' ); 233 currentToken = await fetchGhcrToken( ghcrRepo ); 234 235 console.log( ` Retrying in ${ RETRY_DELAY_MS / 1000 } seconds...` ); 236 await delay( RETRY_DELAY_MS ); 237 continue; 238 } 239 240 if ( 241 attempt === MAX_DOWNLOAD_ATTEMPTS || 242 ! isRetryableDownloadError( downloadError ) 243 ) { 244 throw downloadError; 245 } 246 247 console.log( ` Retrying in ${ RETRY_DELAY_MS / 1000 } seconds...` ); 248 await delay( RETRY_DELAY_MS ); 249 } 250 } 251 252 throw new Error( 'Download failed without an error' ); 253 } 254 255 /** 256 * Extract a verified archive directly into the Gutenberg directory, removing 257 * any existing directory first. 258 * 259 * @param {string} archivePath Path to the verified compressed blob. 260 * @param {string} expectedSha Expected immutable Gutenberg source SHA. 261 * @return {Promise<void>} Resolves after extraction completes. 262 */ 263 async function extractVerifiedArchive( archivePath, expectedSha ) { 264 fs.rmSync( gutenbergDir, { recursive: true, force: true } ); 265 fs.mkdirSync( gutenbergDir, { recursive: true } ); 266 267 const tar = spawn( 'tar', [ '-xzf', archivePath, '-C', gutenbergDir ], { 268 stdio: [ 'ignore', 'inherit', 'inherit' ], 269 } ); 270 271 await new Promise( ( resolve, reject ) => { 272 tar.on( 'close', ( code ) => { 273 if ( code !== 0 ) { 274 reject( new Error( `tar exited with code ${ code }` ) ); 275 return; 276 } 277 resolve( undefined ); 278 } ); 279 tar.on( 'error', reject ); 280 } ); 281 282 const extractedHashPath = path.join( gutenbergDir, '.gutenberg-hash' ); 283 const extractedSha = fs.readFileSync( extractedHashPath, 'utf8' ).trim(); 284 if ( extractedSha !== expectedSha ) { 285 throw new Error( 286 `Extracted Gutenberg SHA mismatch: expected ${ expectedSha } but found ${ extractedSha }` 287 ); 288 } 289 } 290 34 291 /** 35 292 * Resolve the manifest to use for downloading. … … 44 301 * @param {{ ref: string, ghcrRepo: string, isMutable: boolean }} config 45 302 * @param {string} token 46 * @return {Promise<{ manifest: Record<string, any>, resolvedRef: string }>}303 * @return {Promise<{ manifest: Record<string, any>, resolvedRef: string, expectedSha: string }>} 47 304 */ 48 305 async function resolveDownloadManifest( config, token ) { … … 52 309 53 310 if ( ! isMutable ) { 54 return { manifest: initialManifest, resolvedRef: ref };311 return { manifest: initialManifest, resolvedRef: ref, expectedSha: ref }; 55 312 } 56 313 57 314 const revision = 58 315 initialManifest?.annotations?.[ 'org.opencontainers.image.revision' ]; 59 if ( ! revision ) { 60 console.log( 61 `ℹ️ No image.revision annotation on "${ ref }"; using mutable tag for download.` 62 ); 63 return { manifest: initialManifest, resolvedRef: ref }; 316 if ( ! revision || ! /^[a-f0-9]{40}$/i.test( revision ) ) { 317 throw new Error( 318 `Manifest for mutable ref "${ ref }" has no valid org.opencontainers.image.revision SHA` 319 ); 64 320 } 65 321 66 322 try { 67 323 const immutableManifest = await fetchManifest( revision, ghcrRepo, token ); 68 return { manifest: immutableManifest, resolvedRef: revision };324 return { manifest: immutableManifest, resolvedRef: revision, expectedSha: revision }; 69 325 } catch ( error ) { 70 326 if ( /** @type {{ status?: number }} */ ( error ).status === 404 ) { … … 72 328 `ℹ️ Immutable SHA tag ${ revision } unavailable; falling back to mutable tag "${ ref }".` 73 329 ); 74 return { manifest: initialManifest, resolvedRef: ref };330 return { manifest: initialManifest, resolvedRef: ref, expectedSha: revision }; 75 331 } 76 332 throw error; … … 117 373 // Step 2: Resolve the manifest to use for download. 118 374 console.log( `\n📋 Fetching manifest for ${ config.ref }...` ); 119 let manifest, resolvedRef ;120 try { 121 ( { manifest, resolvedRef } = await resolveDownloadManifest(375 let manifest, resolvedRef, expectedSha; 376 try { 377 ( { manifest, resolvedRef, expectedSha } = await resolveDownloadManifest( 122 378 config, 123 379 token … … 131 387 } 132 388 133 const digest = manifest?.layers?.[ 0 ]?.digest; 389 const layer = manifest?.layers?.[ 0 ]; 390 const digest = layer?.digest; 134 391 if ( ! digest ) { 135 392 console.error( '❌ No layer digest found in manifest' ); … … 138 395 console.log( `✅ Blob digest: ${ digest }` ); 139 396 140 // Remove existing gutenberg directory so the extraction is clean.141 if ( fs.existsSync( gutenbergDir ) ) {142 console.log( '\n🗑️ Removing existing gutenberg directory...' );143 fs.rmSync( gutenbergDir, { recursive: true, force: true } );144 }145 146 fs.mkdirSync( gutenbergDir, { recursive: true } );147 148 /*149 * Step 3: Stream the blob directly through gunzip into tar, writing150 * into ./gutenberg with no temporary file on disk. 151 */152 console.log( `\n📥 Downloading and extracting artifact...`);153 try {154 const response = await fetch( `https://ghcr.io/v2/${ config.ghcrRepo }/blobs/${ digest }`,{155 headers: {156 Authorization: `Bearer ${ token }`,157 },158 } );159 if ( ! response.ok) {160 throw new Error( `Failed to download blob: ${ response.status } ${ response.statusText }`);397 // Step 3: Download and verify the compressed blob before extraction. 398 let archivePath; 399 try { 400 archivePath = await downloadBlobWithRetries( 401 `https://ghcr.io/v2/${ config.ghcrRepo }/blobs/${ digest }`, 402 token, 403 digest, 404 layer.size, 405 config.ghcrRepo 406 ); 407 408 console.log( '\n📦 Extracting verified artifact...' ); 409 await extractVerifiedArchive( archivePath, expectedSha ); 410 console.log( '✅ Extraction complete' ); 411 } catch ( error ) { 412 console.error( '❌ Download/extraction failed:', /** @type {Error} */ ( error ).message ); 413 process.exitCode = 1; 414 return; 415 } finally { 416 if ( archivePath ) { 417 fs.rmSync( archivePath, { force: true } ); 161 418 } 162 if ( ! response.body ) {163 throw new Error( 'Blob response has no body' );164 }165 166 /*167 * Spawn tar to read from stdin and extract into gutenbergDir.168 * `tar` is available on macOS, Linux, and Windows 10+.169 */170 const tar = spawn( 'tar', [ '-x', '-C', gutenbergDir ], {171 stdio: [ 'pipe', 'inherit', 'inherit' ],172 } );173 174 /** @type {Promise<void>} */175 const tarDone = new Promise( ( resolve, reject ) => {176 tar.on( 'close', ( code ) => {177 if ( code !== 0 ) {178 reject( new Error( `tar exited with code ${ code }` ) );179 } else {180 resolve();181 }182 } );183 tar.on( 'error', reject );184 } );185 186 /*187 * Pipe: fetch body → gunzip → tar stdin.188 * Decompressing in Node keeps the pipeline error handling189 * consistent and means tar only sees plain tar data on stdin.190 */191 await pipeline(192 Readable.fromWeb(193 /** @type {import('stream/web').ReadableStream} */ ( response.body )194 ),195 zlib.createGunzip(),196 tar.stdin,197 );198 199 await tarDone;200 201 console.log( '✅ Download and extraction complete' );202 } catch ( error ) {203 console.error( '❌ Download/extraction failed:', /** @type {Error} */ ( error ).message );204 process.exit( 1 );205 419 } 206 420 -
branches/7.0/tools/gutenberg/utils.js
r62600 r63449 1 1 #!/usr/bin/env node 2 /* global AbortSignal */ 2 3 3 4 /** … … 27 28 const MANIFEST_ACCEPT = 'application/vnd.oci.image.manifest.v1+json'; 28 29 30 // Retry/timeout settings for the token and manifest requests. These run 31 // before the blob download and are now a single point of failure for the 32 // whole build, so they share the blob download's attempt count and backoff 33 // (see MAX_DOWNLOAD_ATTEMPTS and RETRY_DELAY_MS in download.js). 34 const MAX_METADATA_ATTEMPTS = 3; 35 const RETRY_DELAY_MS = 2000; 36 const METADATA_TIMEOUT_MS = 30000; 37 38 /** 39 * Wait before retrying a failed metadata request. 40 * 41 * @param {number} milliseconds Time to wait in milliseconds. 42 * @return {Promise<void>} Resolves after the requested delay. 43 */ 44 function delay( milliseconds ) { 45 return new Promise( ( resolve ) => setTimeout( resolve, milliseconds ) ); 46 } 47 48 /** 49 * Create an error that retains the HTTP status code for retry decisions. 50 * 51 * @param {string} message Error message. 52 * @param {number} status HTTP status code. 53 * @return {Error & { status: number }} Error with status code. 54 */ 55 function createHttpError( message, status ) { 56 const error = /** @type {Error & { status: number }} */ ( new Error( message ) ); 57 error.status = status; 58 return error; 59 } 60 61 /** 62 * Determine whether a failed metadata request might succeed on a later attempt. 63 * 64 * @param {Error & { status?: number }} error Request error. 65 * @return {boolean} Whether the error is retryable. 66 */ 67 function isRetryableMetadataError( error ) { 68 return ! error.status || error.status === 408 || error.status === 429 || error.status >= 500; 69 } 70 71 /** 72 * Run a metadata request with bounded retries, matching the blob download's 73 * retry semantics. Non-retryable errors (e.g. a 404) are thrown immediately. 74 * 75 * @param {string} description Human-readable label for retry log messages. 76 * @param {() => Promise<any>} request Function that performs one request attempt. 77 * @return {Promise<any>} Resolves with the request's result. 78 */ 79 async function withMetadataRetries( description, request ) { 80 for ( let attempt = 1; attempt <= MAX_METADATA_ATTEMPTS; attempt++ ) { 81 try { 82 return await request(); 83 } catch ( error ) { 84 const requestError = /** @type {Error & { status?: number }} */ ( error ); 85 if ( attempt === MAX_METADATA_ATTEMPTS || ! isRetryableMetadataError( requestError ) ) { 86 throw requestError; 87 } 88 console.error( `❌ ${ description } attempt ${ attempt } failed: ${ requestError.message }` ); 89 console.log( ` Retrying in ${ RETRY_DELAY_MS / 1000 } seconds...` ); 90 await delay( RETRY_DELAY_MS ); 91 } 92 } 93 94 throw new Error( `${ description } failed without an error` ); 95 } 96 29 97 /** 30 98 * Read Gutenberg configuration from package.json. … … 65 133 */ 66 134 async function fetchGhcrToken( ghcrRepo ) { 67 const response = await fetch( 68 `https://ghcr.io/token?scope=repository:${ ghcrRepo }:pull&service=ghcr.io` 69 ); 70 if ( ! response.ok ) { 71 throw new Error( 72 `Failed to fetch GHCR token: ${ response.status } ${ response.statusText }` 135 return withMetadataRetries( 'Fetch GHCR token', async () => { 136 const response = await fetch( 137 `https://ghcr.io/token?scope=repository:${ ghcrRepo }:pull&service=ghcr.io`, 138 { signal: AbortSignal.timeout( METADATA_TIMEOUT_MS ) } 73 139 ); 74 } 75 const data = await response.json(); 76 if ( ! data.token ) { 77 throw new Error( 'No token in GHCR response' ); 78 } 79 return data.token; 140 if ( ! response.ok ) { 141 throw createHttpError( 142 `Failed to fetch GHCR token: ${ response.status } ${ response.statusText }`, 143 response.status 144 ); 145 } 146 const data = await response.json(); 147 if ( ! data.token ) { 148 throw new Error( 'No token in GHCR response' ); 149 } 150 return data.token; 151 } ); 80 152 } 81 153 … … 89 161 */ 90 162 async function fetchManifest( ref, ghcrRepo, token ) { 91 const response = await fetch( 92 `https://ghcr.io/v2/${ ghcrRepo }/manifests/${ ref }`, 93 { 94 headers: { 95 Authorization: `Bearer ${ token }`, 96 Accept: MANIFEST_ACCEPT, 97 }, 98 } 99 ); 100 if ( ! response.ok ) { 101 const error = /** @type {Error & { status?: number }} */ ( 102 new Error( 103 `Failed to fetch manifest for "${ ref }": ${ response.status } ${ response.statusText }` 104 ) 163 return withMetadataRetries( `Fetch manifest for "${ ref }"`, async () => { 164 const response = await fetch( 165 `https://ghcr.io/v2/${ ghcrRepo }/manifests/${ ref }`, 166 { 167 headers: { 168 Authorization: `Bearer ${ token }`, 169 Accept: MANIFEST_ACCEPT, 170 }, 171 signal: AbortSignal.timeout( METADATA_TIMEOUT_MS ), 172 } 105 173 ); 106 error.status = response.status; 107 throw error; 108 } 109 return response.json(); 174 if ( ! response.ok ) { 175 throw createHttpError( 176 `Failed to fetch manifest for "${ ref }": ${ response.status } ${ response.statusText }`, 177 response.status 178 ); 179 } 180 return response.json(); 181 } ); 110 182 } 111 183 … … 122 194 */ 123 195 async function resolveExpectedSha( { ref, ghcrRepo, isMutable } ) { 196 const workflowSha = process.env.GUTENBERG_EXPECTED_SHA; 197 if ( workflowSha ) { 198 if ( ! SHA_PATTERN.test( workflowSha ) ) { 199 throw new Error( 200 `GUTENBERG_EXPECTED_SHA must be a 40-character Git SHA, received "${ workflowSha }"` 201 ); 202 } 203 204 return workflowSha; 205 } 206 124 207 if ( ! isMutable ) { 125 208 return ref; … … 158 241 * Verify that the installed Gutenberg version matches the expected SHA. 159 242 * 160 * For SHA refs, the expected SHA is the configured value. For mutable refs,161 * the expected SHA is whatever the mutable tag currently points to in GHCR162 * (read from the manifest's image.revision annotation). The installed163 * `.gutenberg-hash` is compared against the expected SHA; on mismatch, a164 * fresh download is triggered.243 * A calling workflow may supply GUTENBERG_EXPECTED_SHA after resolving a build 244 * once. This avoids re-resolving a mutable tag in every matrix job. Otherwise, 245 * SHA refs use the configured value and mutable refs resolve their current 246 * image.revision annotation. The installed `.gutenberg-hash` is compared 247 * against the expected SHA; on mismatch, a fresh download is triggered. 165 248 */ 166 249 async function verifyGutenbergVersion() {
Note:
See TracChangeset
for help on using the changeset viewer.
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)