Reuse published photo variants and deploy the validated build
This commit is contained in:
parent
0afd149382
commit
8dbea46ddb
3 changed files with 226 additions and 29 deletions
|
|
@ -3,6 +3,7 @@ import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
|
|||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import sharp from 'sharp';
|
||||
import { createPhotoAssetCache } from './photo-asset-cache.mjs';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = path.resolve(__dirname, '..');
|
||||
|
|
@ -176,6 +177,11 @@ const generate = async () => {
|
|||
}));
|
||||
|
||||
await assertCatalogMatchesFiles(catalog);
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log(`Validated ${catalog.length} photo catalog entries.`);
|
||||
return;
|
||||
}
|
||||
|
||||
await mkdir(publicPhotoDir, { recursive: true });
|
||||
await mkdir(generatedDir, { recursive: true });
|
||||
|
||||
|
|
@ -186,10 +192,14 @@ const generate = async () => {
|
|||
// startup timeout.
|
||||
const existingFiles = new Set(await readdir(publicPhotoDir));
|
||||
const expectedFiles = new Set();
|
||||
const restoreAsset = createPhotoAssetCache(process.env.PHOTO_ASSET_CACHE_URL);
|
||||
let downloaded = 0;
|
||||
let encoded = 0;
|
||||
|
||||
const photos = [];
|
||||
|
||||
for (const entry of catalog) {
|
||||
console.log(`[${entry.order}/${catalog.length}] Preparing ${entry.file}`);
|
||||
const inputPath = path.join(sourceDir, entry.file);
|
||||
const input = await readFile(inputPath);
|
||||
const hash = createHash('sha256')
|
||||
|
|
@ -224,7 +234,15 @@ const generate = async () => {
|
|||
await Promise.all(
|
||||
variants
|
||||
.filter(({ filename }) => !existingFiles.has(filename))
|
||||
.map(async ({ outputPath, width }) => {
|
||||
.map(async (variant) => {
|
||||
if (
|
||||
await restoreAsset({ ...variant, extension: format.extension })
|
||||
) {
|
||||
downloaded += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const { outputPath, width } = variant;
|
||||
const pipeline = sharp(input).rotate().resize({
|
||||
width,
|
||||
withoutEnlargement: true,
|
||||
|
|
@ -237,6 +255,7 @@ const generate = async () => {
|
|||
} else {
|
||||
await pipeline.jpeg(format.options).toFile(outputPath);
|
||||
}
|
||||
encoded += 1;
|
||||
})
|
||||
);
|
||||
|
||||
|
|
@ -310,7 +329,7 @@ ${landscapes}
|
|||
0
|
||||
),
|
||||
0
|
||||
)} responsive assets.`
|
||||
)} responsive assets (${downloaded} downloaded, ${encoded} encoded).`
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
53
scripts/photo-asset-cache.mjs
Normal file
53
scripts/photo-asset-cache.mjs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { rename, rm, writeFile } from 'node:fs/promises';
|
||||
import sharp from 'sharp';
|
||||
|
||||
// Published variants are immutable: their names include the source image and
|
||||
// encoding settings hash. This cache is optional; misses are encoded locally.
|
||||
export const createPhotoAssetCache = (baseUrl) => {
|
||||
let available = Boolean(baseUrl);
|
||||
const base = baseUrl ? new URL(baseUrl.replace(/\/?$/, '/')) : null;
|
||||
|
||||
return async ({ filename, outputPath, width, height, extension }) => {
|
||||
if (!available) return false;
|
||||
|
||||
const temporaryPath = `${outputPath}.tmp`;
|
||||
try {
|
||||
const response = await fetch(
|
||||
new URL(encodeURIComponent(filename), base),
|
||||
{
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
redirect: 'error',
|
||||
}
|
||||
);
|
||||
if (response.status === 404) return false;
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
|
||||
const buffer = Buffer.from(await response.arrayBuffer());
|
||||
const metadata = await sharp(buffer).metadata();
|
||||
const expectedFormat = { avif: 'heif', webp: 'webp', jpg: 'jpeg' }[
|
||||
extension
|
||||
];
|
||||
if (
|
||||
metadata.width !== width ||
|
||||
metadata.height !== height ||
|
||||
metadata.format !== expectedFormat ||
|
||||
(extension === 'avif' && metadata.compression !== 'av1')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await writeFile(temporaryPath, buffer);
|
||||
await rename(temporaryPath, outputPath);
|
||||
return true;
|
||||
} catch (error) {
|
||||
// A network outage should cost one timeout, not one for every variant.
|
||||
if (available) {
|
||||
console.warn(`Published photo cache unavailable: ${error.message}`);
|
||||
}
|
||||
available = false;
|
||||
return false;
|
||||
} finally {
|
||||
await rm(temporaryPath, { force: true });
|
||||
}
|
||||
};
|
||||
};
|
||||
123
scripts/photo-asset-cache.test.mjs
Normal file
123
scripts/photo-asset-cache.test.mjs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
// @vitest-environment node
|
||||
import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import sharp from 'sharp';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createPhotoAssetCache } from './photo-asset-cache.mjs';
|
||||
|
||||
describe('published photo cache', () => {
|
||||
let directory;
|
||||
let variant;
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(path.join(tmpdir(), 'photo-cache-test-'));
|
||||
variant = {
|
||||
filename: 'photo-sourcehash-4.webp',
|
||||
outputPath: path.join(directory, 'photo-sourcehash-4.webp'),
|
||||
width: 4,
|
||||
height: 3,
|
||||
extension: 'webp',
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const image = (format, width = 4) =>
|
||||
sharp({
|
||||
create: { width, height: 3, channels: 3, background: '#a63446' },
|
||||
})
|
||||
.toFormat(format)
|
||||
.toBuffer();
|
||||
|
||||
it.each([
|
||||
['avif', 'avif'],
|
||||
['webp', 'webp'],
|
||||
['jpg', 'jpeg'],
|
||||
])('restores a complete %s variant', async (extension, format) => {
|
||||
const bytes = await image(format);
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(bytes));
|
||||
const restore = createPhotoAssetCache('https://photos.example/static/');
|
||||
|
||||
expect(await restore({ ...variant, extension })).toBe(true);
|
||||
expect(await readFile(variant.outputPath)).toEqual(bytes);
|
||||
expect(await readdir(directory)).toEqual([variant.filename]);
|
||||
});
|
||||
|
||||
it('leaves offline builds independent of the published site', async () => {
|
||||
const request = vi.spyOn(globalThis, 'fetch');
|
||||
expect(await createPhotoAssetCache()(variant)).toBe(false);
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('allows a new photo to miss without disabling other cache hits', async () => {
|
||||
const bytes = await image('webp');
|
||||
const request = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(new Response(null, { status: 404 }))
|
||||
.mockResolvedValueOnce(new Response(bytes));
|
||||
const restore = createPhotoAssetCache('https://photos.example/static/');
|
||||
|
||||
expect(await restore(variant)).toBe(false);
|
||||
expect(await readdir(directory)).toEqual([]);
|
||||
expect(await restore(variant)).toBe(true);
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('rejects cached images with the wrong dimensions or format', async () => {
|
||||
vi.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(new Response(await image('webp', 8)))
|
||||
.mockResolvedValueOnce(new Response(await image('jpeg')));
|
||||
const restore = createPhotoAssetCache('https://photos.example/static/');
|
||||
|
||||
expect(await restore(variant)).toBe(false);
|
||||
expect(await restore(variant)).toBe(false);
|
||||
expect(await readdir(directory)).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects an HTML response instead of saving it as a photo', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response('<html>not an image</html>')
|
||||
);
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
expect(
|
||||
await createPhotoAssetCache('https://photos.example/static/')(variant)
|
||||
).toBe(false);
|
||||
expect(await readdir(directory)).toEqual([]);
|
||||
});
|
||||
|
||||
it('avoids repeated network timeouts during an outage', async () => {
|
||||
const request = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockRejectedValue(new Error('timeout'));
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const restore = createPhotoAssetCache('https://photos.example/static/');
|
||||
|
||||
expect(await restore(variant)).toBe(false);
|
||||
expect(await restore(variant)).toBe(false);
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
expect(await readdir(directory)).toEqual([]);
|
||||
});
|
||||
|
||||
it('never saves a partially downloaded variant', async () => {
|
||||
const response = new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
controller.error(new Error('connection closed'));
|
||||
},
|
||||
})
|
||||
);
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(response);
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
expect(
|
||||
await createPhotoAssetCache('https://photos.example/static/')(variant)
|
||||
).toBe(false);
|
||||
expect(await readdir(directory)).toEqual([]);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue