Reuse published photo variants and deploy the validated build
All checks were successful
Check & deploy / validate (push) Successful in 1m45s
Check & deploy / deploy (push) Has been skipped

This commit is contained in:
Andras Schmelczer 2026-11-10 20:55:14 +00:00
commit 8dbea46ddb
8 changed files with 226 additions and 29 deletions

View file

@ -9,6 +9,8 @@ on:
jobs:
validate:
env:
PHOTO_ASSET_CACHE_URL: https://photos.schmelczer.dev/static/photos/
runs-on:
${{ (github.actor == 'renovate-bot' || github.event.pull_request.user.login == 'renovate-bot' || startsWith(github.ref, 'refs/heads/renovate/') || startsWith(github.head_ref,
'renovate/')) && 'renovate' || 'docker' }}
@ -26,7 +28,6 @@ jobs:
uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Install dependencies
run: npm ci
@ -41,11 +42,22 @@ jobs:
run: npm run build
- name: Install Playwright browser
run: npx playwright install --with-deps chromium
run: npx playwright install --with-deps --only-shell chromium
- name: End-to-end smoke test
env:
PLAYWRIGHT_USE_EXISTING_BUILD: '1'
run: npm run test:e2e
- name: Save validated build
if: ${{ github.event_name == 'push' && github.event.ref == 'refs/heads/main' && contains(fromJSON('["andras","ruby336688"]'), github.actor) }}
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5
with:
name: photos-validated-dist
path: dist
if-no-files-found: error
retention-days: 1
if:
${{ contains(fromJSON('["andras","ruby336688","renovate-bot"]'), github.actor) && (!github.event.pull_request || contains(fromJSON('["andras","ruby336688","renovate-bot"]'),
github.event.pull_request.user.login)) }}
@ -54,30 +66,15 @@ jobs:
${{ (github.actor == 'renovate-bot' || github.event.pull_request.user.login == 'renovate-bot' || startsWith(github.ref, 'refs/heads/renovate/') || startsWith(github.head_ref,
'renovate/')) && 'renovate' || 'docker' }}
needs: validate
if:
${{ contains(fromJSON('["andras","ruby336688","renovate-bot"]'), github.actor) && (!github.event.pull_request || contains(fromJSON('["andras","ruby336688","renovate-bot"]'),
github.event.pull_request.user.login)) && (github.event_name == 'push' && github.ref == 'refs/heads/main') }}
# Never cancel an in-flight deploy: rsync --delete must finish or the live
# site can be left half-deleted. Newer deploys queue behind this one.
if: ${{ github.event_name == 'push' && github.event.ref == 'refs/heads/main' && contains(fromJSON('["andras","ruby336688"]'), github.actor) }}
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- name: Download validated build
uses: https://github.com/actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a
with:
persist-credentials: false
- name: Setup Node
uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
name: photos-validated-dist
path: dist
- name: Upload static site artifact 1
if: ${{ (true) }}
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5
with:
name: pages-deploy-0

View file

@ -37,7 +37,7 @@ Run the full local validation suite with:
npm run lint:check
```
This generates assets (validating the photo catalog against `src/pictures/` in the process), checks source photos for EXIF/XMP/IPTC metadata, type-checks, lints TypeScript and SCSS, and checks formatting.
This checks formatting, type-checks, lints TypeScript and SCSS, checks source photos for EXIF/XMP/IPTC metadata, and validates the photo catalog against `src/pictures/`. Image encoding runs separately as part of the build.
Run unit tests separately:
@ -61,6 +61,8 @@ Photo order, captions, and alt text live in `src/photo-catalog.json`. Add new so
The generated files under `src/generated/` and `public/static/photos/` are intentionally ignored because they are reproducible from the source images and catalog.
CI sets `PHOTO_ASSET_CACHE_URL=https://photos.schmelczer.dev/static/photos/` to reuse published image variants. Filenames include a hash of the source photo and encoding settings, so changed photos or settings produce new files. Downloads are checked for image format and dimensions and saved atomically. Missing variants are encoded locally with the same quality settings. Builds without this variable work offline; a clean build encoding every photo can take around 25 minutes on the two-core runner. The generator reports progress for each photo.
## Gallery Navigation
Photo selections use `#photo=<id>` links, where the ID comes from the source filename rather than its position or generated asset hash. Selecting a thumbnail or using the arrow, Home, or End keys updates the URL; thumbnails can also be copied or opened in another tab. Reloading or opening a photo link selects that photo with the slideshow paused. Back and Forward restore selections, and automatic slideshow advances replace the current URL without adding history entries. Missing or unknown IDs fall back to the first photo.
@ -85,4 +87,4 @@ Review image changes after stripping because this rewrites the JPEG files.
## Deployment
The Forgejo workflow validates pull requests and trusted pushes with `npm ci`, `npm run lint:check`, `npm test`, `npm run build`, and a Playwright smoke test. Only pushes to `main` deploy, by copying `dist/` to `/pages/photos/`.
The Forgejo workflow validates pull requests and trusted pushes with `npm ci`, `npm run lint:check`, `npm test`, `npm run build`, and a Playwright smoke test. CI previews the existing build for the smoke test instead of rebuilding. Trusted human pushes to `main` hand that validated `dist/` artifact to the deploy job and the Pages copier, which publishes it to `/pages/photos/` without another build.

View file

@ -7,7 +7,7 @@
"scripts": {
"dev": "node scripts/generate-assets.mjs && vite --host 0.0.0.0",
"lint": "eslint . --fix && stylelint \"src/**/*.scss\" --fix && prettier --write .",
"lint:check": "prettier --check . && tsc --noEmit && eslint . && stylelint \"src/**/*.scss\" && node scripts/check-image-metadata.mjs && node scripts/generate-assets.mjs",
"lint:check": "prettier --check . && tsc --noEmit && eslint . && stylelint \"src/**/*.scss\" && node scripts/check-image-metadata.mjs && node scripts/generate-assets.mjs --check",
"test": "vitest run",
"test:e2e": "playwright test",
"build": "node scripts/generate-assets.mjs && vite build"

View file

@ -8,7 +8,10 @@ export default defineConfig({
trace: 'on-first-retry',
},
webServer: {
command: 'npm run build && npx vite preview --host 127.0.0.1',
command:
process.env.PLAYWRIGHT_USE_EXISTING_BUILD === '1'
? 'npx vite preview --host 127.0.0.1'
: 'npm run build && npx vite preview --host 127.0.0.1',
url: 'http://127.0.0.1:4173',
reuseExistingServer: !process.env.CI,
timeout: 120_000,

View file

@ -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).`
);
};

View 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 });
}
};
};

View 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([]);
});
});

View file

@ -4,6 +4,6 @@ export default defineConfig({
test: {
environment: 'jsdom',
globals: true,
include: ['src/**/*.test.ts'],
include: ['src/**/*.test.ts', 'scripts/**/*.test.mjs'],
},
});