diff --git a/packages/static-site-deploy/__tests__/cli.test.cjs b/packages/static-site-deploy/__tests__/cli.test.cjs index 6102b4f..4b4a070 100644 --- a/packages/static-site-deploy/__tests__/cli.test.cjs +++ b/packages/static-site-deploy/__tests__/cli.test.cjs @@ -82,6 +82,7 @@ function fakeDeploy() { const log = "const args = process.argv.slice(2); require('node:fs').appendFileSync(process.env.CALLS, JSON.stringify(["; mock('aws', log + `'aws', ...args]) + '\\n'); const [service, command] = args; +if (process.env.FAIL_ALIAS && args.at(-1) === process.env.FAIL_ALIAS) process.exit(7); if (command === 'create-invalidation') console.log('{"Invalidation":{"Id":"EXAMPLE"}}'); if (command === 'wait' && process.env.WAIT_FAILURE) process.exit(9); if (command === 'list-objects-v2') { @@ -139,6 +140,69 @@ test('prefers the directory index when both forms produce the same extensionless ]); }); +test('copies aliases with bounded concurrency and waits for every copy before invalidating', () => { + const { cwd, cliRun, calls } = fakeDeploy(); + for (let index = 0; index < 20; index++) writeFileSync(join(cwd, 'out', `page-${index}.html`), ''); + const preload = join(cwd, 'track-spawn.cjs'); + writeFileSync(preload, ` +const childProcess = require('node:child_process'); +const { appendFileSync } = require('node:fs'); +const spawn = childProcess.spawn; +childProcess.spawn = (command, args, options) => { + const child = spawn(command, args, options); + if (command === 'aws') { + const record = event => appendFileSync(process.env.CALLS, JSON.stringify([event, args.at(-1)]) + '\\n'); + record('copy-start'); + child.once('close', () => record('copy-close')); + } + return child; +}; +`); + const result = cliRun(['deploy', '--site', site, '--trailing-slash-aliases'], { + ...targets, NODE_OPTIONS: `--require="${preload}"`, + }); + assert.equal(result.status, 0, result.stderr); + const events = calls(); + assert.ok(events.slice(0, 2).every(args => args.includes('--recursive'))); + const invalidation = events.findIndex(args => args[2] === 'create-invalidation'); + const active = new Set(); + let peak = 0; + let completed = 0; + for (const [event, destination] of events.slice(2, invalidation)) { + if (event === 'copy-start') { + active.add(destination); + peak = Math.max(peak, active.size); + } else if (event === 'copy-close') { + assert.ok(active.delete(destination)); + completed++; + } + } + assert.ok(peak > 1 && peak <= 16, `peak concurrent copies: ${peak}`); + assert.equal(completed, 22); + assert.equal(active.size, 0); +}); + +test('does not invalidate, health-check, or prune after an alias copy fails', () => { + const { cliRun, calls } = fakeDeploy(); + const result = cliRun(['deploy', '--site', site, '--trailing-slash-aliases'], { + ...targets, FAIL_ALIAS: '--key=new-page/', + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /AWS s3api copy-object failed for alias "new-page\/" \(7\)/); + assert.ok(calls().some(args => args.at(-1) === 's3://example-site-bucket/new-page')); + assert.ok(!calls().some(args => args[0] === 'curl' || args[1] === 'cloudfront' || args[2] === 'list-objects-v2')); +}); + +test('continues to invalidate when there are no aliases', () => { + const { cwd, cliRun, calls } = fakeDeploy(); + rmSync(join(cwd, 'out', 'new-page'), { recursive: true }); + const result = cliRun(['deploy', '--site', site], targets); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(calls().slice(0, 3).map(args => args.slice(1, 3)), [ + ['s3', 'cp'], ['s3', 'cp'], ['cloudfront', 'create-invalidation'], + ]); +}); + test('dry run lists planned changes and only sends read-only S3 listing requests', () => { const { cliRun, calls } = fakeDeploy(); const result = cliRun(['deploy', '--site', site, '--dry-run', '--trailing-slash-aliases', '--preserve', 'manual/*'], { diff --git a/packages/static-site-deploy/src/deploy.ts b/packages/static-site-deploy/src/deploy.ts index 1b5ecad..5862497 100644 --- a/packages/static-site-deploy/src/deploy.ts +++ b/packages/static-site-deploy/src/deploy.ts @@ -1,10 +1,11 @@ -import { execFileSync, spawnSync } from 'node:child_process'; +import { execFileSync, spawn, spawnSync } from 'node:child_process'; import { readFileSync, readdirSync } from 'node:fs'; import { resolve, sep } from 'node:path'; import { awsEnvironment, SiteConfig } from './config'; const markdown = ['*.md', 'llms.txt']; +const aliasConcurrency = 16; const globRegex = (pattern: string) => new RegExp(`^${pattern.split('*').map( part => part.replace(/[|\\{}()[\]^$+?.]/g, '\\$&'), ).join('.*')}$`); @@ -28,7 +29,7 @@ type Options = { type ObjectKey = { Key: string }; type ObjectPage = { Contents?: ObjectKey[]; IsTruncated?: boolean; NextContinuationToken?: string }; -export function deploy(config: SiteConfig, { +export async function deploy(config: SiteConfig, { directory, preserve = markdown, dryRun, trailingSlashAliases, verifyHomepage, }: Options) { const root = resolve(directory); @@ -94,13 +95,32 @@ export function deploy(config: SiteConfig, { aws('s3', 'cp', source, s3, '--recursive', ...markdown.flatMap(pattern => ['--exclude', pattern])); aws('s3', 'cp', source, s3, '--recursive', '--exclude', '*', ...markdown.flatMap(pattern => ['--include', pattern]), '--content-type', 'text/plain; charset=utf-8'); - for (const [alias, key] of aliases) { - if (alias.endsWith('/')) { - aws('s3api', 'copy-object', '--bucket', bucket, `--copy-source=${bucket}/${key}`, `--key=${alias}`); - } else { - aws('s3', 'cp', `${s3}/${key}`, `${s3}/${alias}`); + const copyAlias = (alias: string, key: string) => new Promise((resolveCopy, reject) => { + const args = alias.endsWith('/') + ? ['s3api', 'copy-object', '--bucket', bucket, `--copy-source=${bucket}/${key}`, `--key=${alias}`] + : ['s3', 'cp', `${s3}/${key}`, `${s3}/${alias}`]; + const child = spawn('aws', args, { env: environment, stdio: 'inherit' }); + child.once('error', reject); + child.once('close', (status, signal) => { + if (status === 0) resolveCopy(); + else reject(new Error(`AWS ${args.slice(0, 2).join(' ')} failed for alias ${JSON.stringify(alias)} (${status ?? signal})`)); + }); + }); + const copies = aliases.entries(); + let failure: { error: unknown } | undefined; + const copyWorker = async () => { + while (!failure) { + const next = copies.next(); + if (next.done) return; + try { + await copyAlias(...next.value); + } catch (error) { + failure ??= { error }; + } } - } + }; + await Promise.all(Array.from({ length: Math.min(aliasConcurrency, aliases.size) }, copyWorker)); + if (failure) throw failure.error; invalidate(); const response = exec('curl', ['--silent', '--show-error', '--max-time', '30', '--write-out', '\n%{http_code} %{content_type}', '--', url]);