Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/starpod/src/components/explorer/archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions packages/starpod/src/lib/optimize-episode-image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
9 changes: 7 additions & 2 deletions packages/starpod/src/lib/people.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down
41 changes: 41 additions & 0 deletions packages/starpod/src/lib/remote-image.ts
Original file line number Diff line number Diff line change
@@ -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<string, Promise<boolean>>();

function canLoad(src: string): Promise<boolean> {
if (!loadable.has(src)) {
loadable.set(
src,
Promise.race([
inferRemoteSize(src).then(
() => true,
() => false
),
new Promise<boolean>((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);
}
103 changes: 103 additions & 0 deletions tests/unit/remote-image.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import('astro:assets')>();
getImage.mockImplementation(assets.getImage);
return { ...assets, getImage };
});

const PNG = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64'
);

const ROUTES: Record<string, () => 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('<html>Moved</html>', {
headers: { 'content-type': 'text/html' }
})
};

const fetchMock = vi.fn(async (request: Request) => {
if (request.url === 'https://art.example/stalled.png') {
return new Promise<Response>(() => {});
}
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);
});
});
13 changes: 13 additions & 0 deletions tests/unit/stubs/astro-assets.ts
Original file line number Diff line number Diff line change
@@ -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)}` };
}
4 changes: 4 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading