diff --git a/packages/starpod/src/components/explorer/archive.ts b/packages/starpod/src/components/explorer/archive.ts index c9270471..dc433308 100644 --- a/packages/starpod/src/components/explorer/archive.ts +++ b/packages/starpod/src/components/explorer/archive.ts @@ -6,11 +6,11 @@ * * Server-only. */ -import { getImage } from 'astro:assets'; import starpodConfig from 'virtual:starpod/config'; import { sortCast, type CastPerson } from '../../lib/cast'; import { faceOf, peopleBySlug } from '../../lib/people'; +import { getLoadableImage } from '../../lib/remote-image'; import type { Episode, Show } from '../../lib/rss'; export interface ArchivePerson { @@ -46,7 +46,7 @@ async function cardArt(src: string | undefined, fallback: string) { return { src: fallback }; } try { - const image = await getImage({ + const image = await getLoadableImage({ src, format: 'avif', height: 320, diff --git a/packages/starpod/src/lib/optimize-episode-image.ts b/packages/starpod/src/lib/optimize-episode-image.ts index 12c5f624..7161f7b9 100644 --- a/packages/starpod/src/lib/optimize-episode-image.ts +++ b/packages/starpod/src/lib/optimize-episode-image.ts @@ -4,8 +4,8 @@ export async function optimizeImage( ) { if (image) { try { - const { getImage } = await import('astro:assets'); - const optimizedImage = await getImage({ + const { getLoadableImage } = await import('./remote-image'); + const optimizedImage = await getLoadableImage({ src: image, format: 'avif', height: options?.height ?? 160, diff --git a/packages/starpod/src/lib/people.ts b/packages/starpod/src/lib/people.ts index 756e62ee..b2ba3e2b 100644 --- a/packages/starpod/src/lib/people.ts +++ b/packages/starpod/src/lib/people.ts @@ -8,7 +8,6 @@ * Server-only. */ import type { ImageMetadata } from 'astro'; -import { getImage } from 'astro:assets'; import { eq } from 'drizzle-orm'; import { database } from 'virtual:starpod/config'; @@ -18,6 +17,7 @@ import { createDb } from '../db'; import { HostOrGuest, Person } from '../db/schema'; import { dasherize } from '../utils/dasherize'; import { matchEach, type CastPerson } from './cast'; +import { getLoadableImage } from './remote-image'; import { getAllEpisodes } from './rss'; interface Records { @@ -136,7 +136,12 @@ export function faceOf( } try { return ( - await getImage({ src, width: size, height: size, format: 'webp' }) + await getLoadableImage({ + src, + width: size, + height: size, + format: 'webp' + }) ).src; } catch { return avatar; diff --git a/packages/starpod/src/lib/remote-image.ts b/packages/starpod/src/lib/remote-image.ts new file mode 100644 index 00000000..7c742faa --- /dev/null +++ b/packages/starpod/src/lib/remote-image.ts @@ -0,0 +1,41 @@ +/** + * Astro's getImage for artwork from the feed or the guests database. In a + * build, getImage only plans a remote image's transform: Astro fetches the + * image later, and one it cannot load (a dead link, a page that isn't an + * image) fails the whole build. So a remote image is read here first, once + * per URL, and one Astro cannot load is refused like any other getImage + * error, for the caller to fall back. + * + * Server-only. + */ +import { getImage, inferRemoteSize } from 'astro:assets'; +import type { UnresolvedImageTransform } from 'astro'; + +const READ_TIMEOUT_MS = 10_000; + +const loadable = new Map>(); + +function canLoad(src: string): Promise { + if (!loadable.has(src)) { + loadable.set( + src, + Promise.race([ + inferRemoteSize(src).then( + () => true, + () => false + ), + new Promise((resolve) => + setTimeout(() => resolve(false), READ_TIMEOUT_MS).unref() + ) + ]) + ); + } + return loadable.get(src)!; +} + +export async function getLoadableImage(options: UnresolvedImageTransform) { + if (typeof options.src === 'string' && !(await canLoad(options.src))) { + throw new Error(`Astro cannot load the image ${options.src}`); + } + return getImage(options); +} diff --git a/tests/unit/remote-image.test.ts b/tests/unit/remote-image.test.ts new file mode 100644 index 00000000..08e06c29 --- /dev/null +++ b/tests/unit/remote-image.test.ts @@ -0,0 +1,103 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const getImage = vi.hoisted(() => vi.fn()); + +vi.mock('astro:assets', async (importOriginal) => { + const assets = await importOriginal(); + getImage.mockImplementation(assets.getImage); + return { ...assets, getImage }; +}); + +const PNG = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', + 'base64' +); + +const ROUTES: Record Response> = { + 'https://art.example/ep.png': () => + new Response(PNG, { headers: { 'content-type': 'image/png' } }), + 'https://art.example/moved.png': () => + new Response(null, { + status: 307, + headers: { location: 'https://s3.example/ep.png?signed=1' } + }), + 'https://s3.example/ep.png?signed=1': () => new Response(PNG), + 'https://art.example/page.png': () => + new Response('Moved', { + headers: { 'content-type': 'text/html' } + }) +}; + +const fetchMock = vi.fn(async (request: Request) => { + if (request.url === 'https://art.example/stalled.png') { + return new Promise(() => {}); + } + const response = + ROUTES[request.url]?.() ?? new Response(null, { status: 404 }); + // A fetched response carries its URL, which Astro checks against the allowed hosts. + return Object.defineProperty(response, 'url', { value: request.url }); +}); + +async function optimize(url: string) { + const { optimizeImage } = + await import('starpod/src/lib/optimize-episode-image'); + return optimizeImage(url); +} + +describe('remote artwork', () => { + beforeEach(() => { + vi.resetModules(); + getImage.mockClear(); + fetchMock.mockClear(); + vi.stubGlobal('fetch', fetchMock); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it('is optimized when Astro can load it, through redirects too', async () => { + expect(await optimize('https://art.example/ep.png')).toBe( + '/_image?href=https%3A%2F%2Fart.example%2Fep.png' + ); + expect(await optimize('https://art.example/moved.png')).toBe( + '/_image?href=https%3A%2F%2Fart.example%2Fmoved.png' + ); + }); + + it('falls back to its own URL, never reaching Astro, when it is missing', async () => { + expect(await optimize('https://art.example/missing.png')).toBe( + 'https://art.example/missing.png' + ); + expect(getImage).not.toHaveBeenCalled(); + }); + + it('falls back when the URL answers with something that is not an image', async () => { + expect(await optimize('https://art.example/page.png')).toBe( + 'https://art.example/page.png' + ); + expect(getImage).not.toHaveBeenCalled(); + }); + + it('falls back when its host stalls', async () => { + vi.useFakeTimers(); + const optimized = optimize('https://art.example/stalled.png'); + await vi.advanceTimersByTimeAsync(10_000); + expect(await optimized).toBe('https://art.example/stalled.png'); + expect(getImage).not.toHaveBeenCalled(); + }); + + it('is fetched once however many times a build asks for it', async () => { + const { optimizeImage } = + await import('starpod/src/lib/optimize-episode-image'); + await Promise.all([ + optimizeImage('https://art.example/ep.png'), + optimizeImage('https://art.example/ep.png', { width: 960, height: 960 }), + optimizeImage('https://art.example/missing.png'), + optimizeImage('https://art.example/missing.png') + ]); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(getImage).toHaveBeenCalledTimes(2); + }); +}); diff --git a/tests/unit/stubs/astro-assets.ts b/tests/unit/stubs/astro-assets.ts new file mode 100644 index 00000000..acf1dfb2 --- /dev/null +++ b/tests/unit/stubs/astro-assets.ts @@ -0,0 +1,13 @@ +import { inferRemoteSize as probe } from 'astro/assets/utils/inferRemoteSize.js'; + +// Astro's own probe, with the remote patterns the integration configures. +export const inferRemoteSize = (url: string) => + probe(url, { + domains: [], + remotePatterns: [{ protocol: 'https' }, { protocol: 'http' }] + }); + +// Names the image Astro would transform, as getImage does in a build. +export async function getImage({ src }: { src: string }) { + return { src: `/_image?href=${encodeURIComponent(src)}` }; +} diff --git a/vitest.config.ts b/vitest.config.ts index 704b0d7e..7b19e4d2 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -27,6 +27,10 @@ export default defineConfig({ 'astro:content': fileURLToPath( new URL('./tests/unit/stubs/astro-content.ts', import.meta.url) ), + // Image services exist only inside an Astro build; tests stub getImage. + 'astro:assets': fileURLToPath( + new URL('./tests/unit/stubs/astro-assets.ts', import.meta.url) + ), // The dock navigates with Astro's client router; tests stub it. 'astro:transitions/client': fileURLToPath( new URL('./tests/unit/stubs/astro-transitions-client.ts', import.meta.url)