Unverified Commit 1cb20a1d authored by Steven's avatar Steven Committed by GitHub

[image-optimizer] Refactor into lightweight transform module (#97988)

This PR is strictly a refactor, no logic should change.

The idea is that we eventually want to run the image optimizer transform
step in a child process. This PR refactors the code to make a new
`transform.ts` that is lightweight and should reduce some of the
overhead of loading a large module graph when spawning a new process.
parent f8898208
......@@ -240,6 +240,7 @@ export async function collectBuildTraces({
// only ignore image-optimizer code when
// this is being handled outside of next-server
'**/next/dist/server/image-optimizer.js',
'**/next/dist/server/image-optimizer/**/*',
]
: []),
......
import isAnimated from 'next/dist/compiled/is-animated'
import { optimizeImage } from '../../../../server/image-optimizer'
import { optimizeImage } from '../../../../server/image-optimizer/transform'
const BLUR_IMG_SIZE = 8
const BLUR_QUALITY = 70
......
......@@ -2,7 +2,7 @@ import type { CompilerNameValues } from '../../../../shared/lib/constants'
import path from 'path'
import loaderUtils from 'next/dist/compiled/loader-utils3'
import { getImageSize } from '../../../../server/image-optimizer'
import { getImageSize } from '../../../../server/image-optimizer/get-image-size'
import { getBlurImage } from './blur'
interface Options {
......
......@@ -10,7 +10,7 @@ import type {
import { existsSync, promises as fs } from 'fs'
import path from 'path'
import loaderUtils from 'next/dist/compiled/loader-utils3'
import { getImageSize } from '../../../server/image-optimizer'
import { getImageSize } from '../../../server/image-optimizer/get-image-size'
import { imageExtMimeTypeMap } from '../../../lib/mime-type'
import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants'
import { fillStaticMetadataSegment } from '../../../lib/metadata/get-metadata-route'
......
This diff is collapsed.
import { detector } from 'next/dist/compiled/image-detector/detector.js'
import {
AVIF,
BMP,
GIF,
HEIC,
ICNS,
ICO,
JPEG,
JP2,
JXL,
PDF,
PNG,
SVG,
TIFF,
WEBP,
} from './image-type'
/**
* Inspects the first few bytes of a buffer to determine if
* it matches the "magic number" of known file signatures.
* https://en.wikipedia.org/wiki/List_of_file_signatures
*/
export async function detectContentType(
buffer: Buffer
): Promise<string | null> {
if (buffer.byteLength === 0) {
return null
}
if ([0xff, 0xd8, 0xff].every((b, i) => buffer[i] === b)) {
return JPEG
}
if (
[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every(
(b, i) => buffer[i] === b
)
) {
return PNG
}
if ([0x47, 0x49, 0x46, 0x38].every((b, i) => buffer[i] === b)) {
return GIF
}
if (
[0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50].every(
(b, i) => !b || buffer[i] === b
)
) {
return WEBP
}
if ([0x3c, 0x3f, 0x78, 0x6d, 0x6c].every((b, i) => buffer[i] === b)) {
return SVG
}
if ([0x3c, 0x73, 0x76, 0x67].every((b, i) => buffer[i] === b)) {
return SVG
}
if (
[0, 0, 0, 0, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66].every(
(b, i) => !b || buffer[i] === b
)
) {
return AVIF
}
if ([0x00, 0x00, 0x01, 0x00].every((b, i) => buffer[i] === b)) {
return ICO
}
if ([0x69, 0x63, 0x6e, 0x73].every((b, i) => buffer[i] === b)) {
return ICNS
}
if ([0x49, 0x49, 0x2a, 0x00].every((b, i) => buffer[i] === b)) {
return TIFF
}
if ([0x42, 0x4d].every((b, i) => buffer[i] === b)) {
return BMP
}
if ([0xff, 0x0a].every((b, i) => buffer[i] === b)) {
return JXL
}
if (
[
0x00, 0x00, 0x00, 0x0c, 0x4a, 0x58, 0x4c, 0x20, 0x0d, 0x0a, 0x87, 0x0a,
].every((b, i) => buffer[i] === b)
) {
return JXL
}
if (
[0, 0, 0, 0, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63].every(
(b, i) => !b || buffer[i] === b
)
) {
return HEIC
}
if ([0x25, 0x50, 0x44, 0x46, 0x2d].every((b, i) => buffer[i] === b)) {
return PDF
}
if (
[
0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a,
].every((b, i) => buffer[i] === b)
) {
return JP2
}
const format = detector(buffer.subarray(0, 1024))
switch (format) {
case 'webp':
return WEBP
case 'png':
return PNG
case 'jpg':
return JPEG
case 'gif':
return GIF
case 'svg':
return SVG
case 'jxl':
case 'jxl-stream':
return JXL
case 'jp2':
return JP2
case 'tiff':
return TIFF
case 'bmp':
return BMP
case 'ico':
return ICO
case 'icns':
return ICNS
case 'heif':
case 'cur':
case 'dds':
case 'j2c':
case 'ktx':
case 'pnm':
case 'psd':
case 'tga':
case undefined:
return null // unsupported formats
default:
format satisfies never // exhaustive check
return null // impossible to reach
}
}
import { createHash } from 'crypto'
export function getHash(items: (string | number | Buffer)[]) {
const hash = createHash('sha256')
for (let item of items) {
if (typeof item === 'number') hash.update(String(item))
else {
hash.update(item)
}
}
// See https://en.wikipedia.org/wiki/Base64#URL_applications
return hash.digest('base64url')
}
export function extractEtag(
etag: string | null | undefined,
imageBuffer: Buffer
) {
if (etag) {
// upstream etag needs to be base64url encoded due to weak etag signature
// as we store this in the cache-entry file name.
return Buffer.from(etag).toString('base64url')
}
return getImageEtag(imageBuffer)
}
export function getImageEtag(image: Buffer) {
return getHash([image])
}
import imageSizeOf from 'next/dist/compiled/image-size'
export async function getImageSize(buffer: Buffer): Promise<{
width?: number
height?: number
}> {
const { width, height } = imageSizeOf(buffer)
return { width, height }
}
function parseCacheControl(
str: string | null | undefined
): Map<string, string> {
const map = new Map<string, string>()
if (!str) {
return map
}
for (let directive of str.split(',')) {
let [key, value] = directive.trim().split('=', 2)
key = key.toLowerCase()
if (value) {
value = value.toLowerCase()
}
map.set(key, value)
}
return map
}
export function getMaxAge(str: string | null | undefined): number {
const map = parseCacheControl(str)
if (map) {
let age = map.get('s-maxage') || map.get('max-age') || ''
if (age.startsWith('"') && age.endsWith('"')) {
age = age.slice(1, -1)
}
const n = parseInt(age, 10)
if (!isNaN(n)) {
return n
}
}
return 0
}
import type {
CachedImageValue,
IncrementalCacheEntry,
} from '../response-cache/types'
import type { ImageUpstream } from './transform'
export function getPreviouslyCachedImageOrNull(
upstreamImage: ImageUpstream,
previousCacheEntry: IncrementalCacheEntry | null | undefined
): CachedImageValue | null {
if (
previousCacheEntry?.value?.kind === 'IMAGE' &&
// Images that are SVGs, animated or failed the optimization previously end up using upstreamEtag as their etag as well,
// in these cases we want to trigger a new "optimization" attempt.
previousCacheEntry.value.upstreamEtag !== previousCacheEntry.value.etag &&
// and the upstream etag is the same as the previous cache entry's
upstreamImage.etag === previousCacheEntry.value.upstreamEtag
) {
return previousCacheEntry.value
}
return null
}
export class ImageError extends Error {
statusCode: number
constructor(statusCode: number, message: string) {
super(message)
// ensure an error status is used > 400
if (statusCode >= 400) {
this.statusCode = statusCode
} else {
this.statusCode = 500
}
}
}
export const AVIF = 'image/avif'
export const WEBP = 'image/webp'
export const PNG = 'image/png'
export const JPEG = 'image/jpeg'
export const JXL = 'image/jxl'
export const JP2 = 'image/jp2'
export const HEIC = 'image/heic'
export const GIF = 'image/gif'
export const SVG = 'image/svg+xml'
export const ICO = 'image/x-icon'
export const ICNS = 'image/x-icns'
export const TIFF = 'image/tiff'
export const BMP = 'image/bmp'
export const PDF = 'application/pdf'
// WARNING: Please keep this module lightweight with very few imports since
// we intend to run it in a child process in the future. Please do NOT
// add new imports without considering their impact on its dependency graph.
import isAnimated from 'next/dist/compiled/is-animated'
import type { NextConfigComplete } from '../config-shared'
import isError from '../../lib/is-error'
import { detectContentType } from './detect-content-type'
import {
AVIF,
BMP,
GIF,
HEIC,
ICNS,
ICO,
JPEG,
JXL,
PNG,
SVG,
WEBP,
} from './image-type'
import { getImageEtag } from './extract-etag'
import { getMaxAge } from './get-max-age'
import { ImageError } from './image-error'
const ANIMATABLE_TYPES = [WEBP, PNG, GIF]
const BYPASS_TYPES = [SVG, ICO, ICNS, BMP, JXL, HEIC]
let _sharp: typeof import('sharp').default
export interface ImageUpstream {
buffer: Buffer
contentType: string | null | undefined
cacheControl: string | null | undefined
etag: string
}
export interface ImageOptimizerTransformParams {
href: string
width: number
quality: number
mimeType: string
}
export type ImageOptimizerTransformConfig = {
experimental: Pick<
NextConfigComplete['experimental'],
| 'imgOptConcurrency'
| 'imgOptOperationCache'
| 'imgOptMaxInputPixels'
| 'imgOptSequentialRead'
| 'imgOptTimeoutInSeconds'
>
images: Pick<
NextConfigComplete['images'],
'dangerouslyAllowSVG' | 'minimumCacheTTL'
>
}
export interface ImageOptimizerTransformLogger {
error(...args: unknown[]): void
warnOnce(message: string): void
}
export interface ImageOptimizerTransformOptions {
isValidMime: (contentType: string) => boolean
previousOutput?: {
buffer: Buffer
maxAge?: number
etag: string
upstreamEtag: string
}
logger?: ImageOptimizerTransformLogger
handleDevOutput?: (
buffer: Buffer,
contentType: string
) => Promise<{ buffer: Buffer; contentType: string }>
}
export interface ImageOptimizerResult {
buffer: Buffer
contentType: string
maxAge: number
etag: string
upstreamEtag: string
error?: unknown
}
export function getSharp(
concurrency: number | null | undefined,
operationCache: boolean | null | undefined
) {
if (_sharp) {
return _sharp
}
try {
_sharp = require('sharp') as typeof import('sharp').default
_sharp.block({ operation: ['VipsForeignLoad'] })
_sharp.unblock({
operation: [
'VipsForeignLoadHeif', // avif
'VipsForeignLoadJpeg',
'VipsForeignLoadNsgif',
'VipsForeignLoadPng',
'VipsForeignLoadSvg',
'VipsForeignLoadTiff',
'VipsForeignLoadWebp',
],
})
if (typeof operationCache === 'boolean') {
_sharp.cache(operationCache)
}
if (_sharp.concurrency() > 1) {
// Reducing concurrency should reduce the memory usage too.
// We more aggressively reduce in dev but also reduce in prod.
// https://sharp.pixelplumbing.com/api-utility#concurrency
const divisor = process.env.NODE_ENV === 'development' ? 4 : 2
_sharp.concurrency(
concurrency ?? Math.floor(Math.max(_sharp.concurrency() / divisor, 1))
)
}
} catch (e: unknown) {
if (isError(e) && e.code === 'MODULE_NOT_FOUND') {
throw new Error(
'Module `sharp` not found. Please run `npm install --cpu=wasm32 sharp` to install it.'
)
}
throw e
}
return _sharp
}
export async function optimizeImage({
buffer,
contentType,
quality,
width,
height,
concurrency,
operationCache,
limitInputPixels,
sequentialRead,
timeoutInSeconds,
}: {
buffer: Buffer
contentType: string
quality: number
width: number
height?: number
concurrency?: number | null
operationCache?: boolean | null | undefined
limitInputPixels?: number
sequentialRead?: boolean | null
timeoutInSeconds?: number
}): Promise<Buffer> {
const sharp = getSharp(concurrency, operationCache)
const transformer = sharp(buffer, {
limitInputPixels,
sequentialRead: sequentialRead ?? undefined,
})
.timeout({
seconds: timeoutInSeconds ?? 7,
})
.rotate()
if (height) {
transformer.resize(width, height)
} else {
transformer.resize(width, undefined, {
withoutEnlargement: true,
})
}
if (contentType === AVIF) {
transformer.avif({
// Scale the quality to try and match webp. This ratio was derived
// from sharp's default 80 (webp) and 50 (avif), and then verified
// using dssim and ssimulacra2 visual quality tests.
quality: Math.max(Math.round(quality * (50 / 80)), 1),
effort: 3,
})
} else if (contentType === WEBP) {
transformer.webp({ quality })
} else if (contentType === PNG) {
transformer.png({ quality })
} else if (contentType === JPEG) {
transformer.jpeg({ quality, mozjpeg: true })
}
const optimizedBuffer = await transformer.toBuffer()
return optimizedBuffer
}
export async function imageOptimizerTransform(
imageUpstream: ImageUpstream,
paramsResult: ImageOptimizerTransformParams,
nextConfig: ImageOptimizerTransformConfig,
opts: ImageOptimizerTransformOptions
): Promise<ImageOptimizerResult> {
const { href, quality, width, mimeType } = paramsResult
const { buffer: upstreamBuffer, etag: upstreamEtag } = imageUpstream
const maxAge = Math.max(
nextConfig.images.minimumCacheTTL,
getMaxAge(imageUpstream.cacheControl)
)
const upstreamType = await detectContentType(upstreamBuffer)
if (
!upstreamType ||
!upstreamType.startsWith('image/') ||
upstreamType.includes(',')
) {
opts.logger?.error(
"The requested resource isn't a valid image for",
href,
'received',
upstreamType
)
throw new ImageError(400, "The requested resource isn't a valid image.")
}
if (
upstreamType.startsWith('image/svg') &&
!nextConfig.images.dangerouslyAllowSVG
) {
opts.logger?.error(
`The requested resource "${href}" has type "${upstreamType}" but dangerouslyAllowSVG is disabled. Consider adding the "unoptimized" property to the <Image>.`
)
throw new ImageError(
400,
'"url" parameter is valid but image type is not allowed'
)
}
if (ANIMATABLE_TYPES.includes(upstreamType) && isAnimated(upstreamBuffer)) {
opts.logger?.warnOnce(
`The requested resource "${href}" is an animated image so it will not be optimized. Consider adding the "unoptimized" property to the <Image>.`
)
return {
buffer: upstreamBuffer,
contentType: upstreamType,
maxAge,
etag: upstreamEtag,
upstreamEtag,
}
}
if (BYPASS_TYPES.includes(upstreamType)) {
return {
buffer: upstreamBuffer,
contentType: upstreamType,
maxAge,
etag: upstreamEtag,
upstreamEtag,
}
}
let contentType: string
if (mimeType) {
contentType = mimeType
} else if (
opts.isValidMime(upstreamType) &&
upstreamType !== WEBP &&
upstreamType !== AVIF
) {
contentType = upstreamType
} else {
contentType = JPEG
}
if (opts.previousOutput) {
return {
buffer: opts.previousOutput.buffer,
contentType,
maxAge: opts.previousOutput.maxAge || maxAge,
etag: opts.previousOutput.etag,
upstreamEtag: opts.previousOutput.upstreamEtag,
}
}
try {
let optimizedBuffer = await optimizeImage({
buffer: upstreamBuffer,
contentType,
quality,
width,
concurrency: nextConfig.experimental.imgOptConcurrency,
operationCache: nextConfig.experimental.imgOptOperationCache,
limitInputPixels: nextConfig.experimental.imgOptMaxInputPixels,
sequentialRead: nextConfig.experimental.imgOptSequentialRead,
timeoutInSeconds: nextConfig.experimental.imgOptTimeoutInSeconds,
})
if (opts.handleDevOutput) {
const output = await opts.handleDevOutput(optimizedBuffer, contentType)
optimizedBuffer = output.buffer
contentType = output.contentType
}
return {
buffer: optimizedBuffer,
contentType,
maxAge,
etag: getImageEtag(optimizedBuffer),
upstreamEtag,
}
} catch (error) {
if (upstreamType) {
// If we fail to optimize, fallback to the original image
return {
buffer: upstreamBuffer,
contentType: upstreamType,
maxAge: nextConfig.images.minimumCacheTTL,
etag: upstreamEtag,
upstreamEtag,
error,
}
} else {
throw new ImageError(
400,
'Unable to optimize image and unable to fallback to upstream image'
)
}
}
}
/* eslint-env jest */
import { detectContentType as dct } from 'next/dist/server/image-optimizer'
import { detectContentType as dct } from 'next/dist/server/image-optimizer/detect-content-type'
import { readFile } from 'fs-extra'
import { join } from 'path'
......
/* eslint-env jest */
import { extractEtag, getImageEtag } from 'next/dist/server/image-optimizer'
import {
extractEtag,
getImageEtag,
} from 'next/dist/server/image-optimizer/extract-etag'
import { readFile } from 'fs-extra'
import { join } from 'path'
......
/* eslint-env jest */
import { getMaxAge } from 'next/dist/server/image-optimizer'
import { getMaxAge } from 'next/dist/server/image-optimizer/get-max-age'
describe('getMaxAge', () => {
it('should return 0 when no cache-control provided', () => {
......
/* eslint-env jest */
import {
getPreviouslyCachedImageOrNull,
getImageEtag,
} from 'next/dist/server/image-optimizer'
import { getPreviouslyCachedImageOrNull } from 'next/dist/server/image-optimizer/get-previously-cached-image-or-null'
import { getImageEtag } from 'next/dist/server/image-optimizer/extract-etag'
import {
CachedRouteKind,
IncrementalCacheEntry,
......
/* eslint-env jest */
import { readFile } from 'fs-extra'
import { join } from 'path'
import {
imageOptimizerTransform,
type ImageOptimizerTransformOptions,
} from 'next/dist/server/image-optimizer/transform'
import type {
CachedRouteKind,
IncrementalResponseCacheEntry,
} from 'next/dist/server/response-cache/types'
const getImage = (filename: string) =>
readFile(join(__dirname, 'images', filename))
const isValidMime = (contentType: string) => contentType === 'image/png'
const config = {
images: {
dangerouslyAllowSVG: true,
minimumCacheTTL: 60,
},
experimental: {
imgOptConcurrency: 1,
imgOptOperationCache: false,
imgOptMaxInputPixels: 67_108_864,
imgOptSequentialRead: true,
imgOptTimeoutInSeconds: 6,
},
}
async function transform(
filename: string,
mimeType = 'image/webp',
options?: ImageOptimizerTransformOptions
) {
const buffer = await getImage(filename)
return imageOptimizerTransform(
{
buffer,
contentType: undefined,
cacheControl: 'public, max-age=120',
etag: 'source-etag',
},
{ href: `/${filename}`, width: 64, quality: 75, mimeType },
config,
{ isValidMime, ...options }
)
}
async function transformInDevelopment(
filename: string,
previousCacheEntry?: IncrementalResponseCacheEntry
) {
const { imageOptimizer } =
require('next/dist/server/image-optimizer') as typeof import('next/dist/server/image-optimizer')
const buffer = await getImage(filename)
return imageOptimizer(
{
buffer,
contentType: undefined,
cacheControl: undefined,
etag: 'source-etag',
},
{ href: `/${filename}`, width: 8, quality: 70, mimeType: 'image/webp' },
config,
{ isDev: true, silent: true, previousCacheEntry }
)
}
describe('imageOptimizerTransform', () => {
it('loads without the server image optimizer dependency graph', () => {
const loaded = Object.keys(require.cache)
expect(
loaded.some((path) => /\/server\/image-optimizer\.[jt]s$/.test(path))
).toBe(false)
expect(
loaded.some((path) => path.includes('/server/response-cache/'))
).toBe(false)
expect(
loaded.some((path) => /\/server\/serve-static\.[jt]s$/.test(path))
).toBe(false)
expect(
loaded.some((path) => /\/server\/lib\/mock-request\.[jt]s$/.test(path))
).toBe(false)
expect(
loaded.some((path) => /\/server\/config-shared\.[jt]s$/.test(path))
).toBe(false)
expect(
loaded.some((path) => /\/build\/output\/log\.[jt]s$/.test(path))
).toBe(false)
})
it('transforms a png buffer', async () => {
const result = await transform('test.png')
expect(result.contentType).toBe('image/webp')
expect(result.buffer.byteLength).toBeGreaterThan(0)
expect(result.maxAge).toBe(120)
})
it('preserves the source format when no output format is requested', async () => {
const result = await transform('test.png', '')
expect(result.contentType).toBe('image/png')
})
it('transforms an avif source', async () => {
const source = await getImage('test.avif')
const result = await transform('test.avif')
expect(result.buffer).not.toEqual(source)
expect(result.contentType).toBe('image/webp')
})
it('generates blur placeholders in development', async () => {
const result = await transformInDevelopment('test.png')
expect(result.contentType).toBe('image/svg+xml')
expect(result.buffer.toString()).toContain('<svg')
})
it('does not generate blur placeholders for bypassed images', async () => {
const source = await getImage('test.svg')
const result = await transformInDevelopment('test.svg')
expect(result.buffer).toEqual(source)
expect(result.contentType).toBe('image/svg+xml')
})
it('reuses a previous cache entry without generating a blur placeholder', async () => {
const previousBuffer = Buffer.from('previous image')
const result = await transformInDevelopment('test.png', {
value: {
kind: 'IMAGE' as CachedRouteKind.IMAGE,
buffer: previousBuffer,
etag: 'optimized-etag',
upstreamEtag: 'source-etag',
extension: 'webp',
},
cacheControl: { revalidate: 90, expire: undefined },
})
expect(result.buffer).toEqual(previousBuffer)
expect(result.contentType).toBe('image/webp')
expect(result.maxAge).toBe(90)
})
it('bypasses svg buffers', async () => {
const source = await getImage('test.svg')
const result = await transform('test.svg')
expect(result.buffer).toEqual(source)
expect(result.contentType).toBe('image/svg+xml')
})
it('bypasses animated buffers', async () => {
const source = await getImage('animated.webp')
const result = await transform('animated.webp')
expect(result.buffer).toEqual(source)
expect(result.contentType).toBe('image/webp')
})
it('rejects disallowed svg buffers', async () => {
await expect(
imageOptimizerTransform(
{
buffer: await getImage('test.svg'),
contentType: undefined,
cacheControl: undefined,
etag: 'source-etag',
},
{ href: '/test.svg', width: 64, quality: 75, mimeType: 'image/webp' },
{
...config,
images: { ...config.images, dangerouslyAllowSVG: false },
},
{ isValidMime }
)
).rejects.toMatchObject({ statusCode: 400 })
})
it('rejects unrecognized buffers', async () => {
await expect(
imageOptimizerTransform(
{
buffer: Buffer.from('not an image'),
contentType: undefined,
cacheControl: undefined,
etag: 'source-etag',
},
{ href: '/bad', width: 64, quality: 75, mimeType: 'image/webp' },
config,
{ isValidMime }
)
).rejects.toMatchObject({ statusCode: 400 })
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment