Skip to content

Commit 8282414

Browse files
fix(storage-vercel-blob): keep image-size filenames separate with addRandomSuffix (#18920)
Stacked on #18913. Review and merge #18388 and #18913 first. This PR does not depend on their changes. It is in the stack because #18921 changes the same adapter code. Fixes #9589. ## Summary With `addRandomSuffix: true`, Vercel Blob uploads the main file and each image size in parallel. Every upload wrote its suffixed name to the same `data.filename`. As a result, the document filename could point to an image size, and no image size got its suffixed name. Every image-size URL returned 404. Now each upload writes its suffixed name only to its own entry: an image size updates `sizes.<name>.filename`, and the main file updates `filename`. ## How - After each upload finishes, the adapter finds the image size whose filename matches the uploaded file. If no size matches, the file is the main file. - Two image sizes with the same dimensions get the same filename. The adapter finds the entry after the upload, so a size that an earlier upload renamed does not match again. Each size gets its own entry. - `storage-uploadthing` already uses this pattern for its per-file keys. - `plugin-cloud-storage` does not change. ## Tests - A unit test checks that the main file and an image size each update only their own filename. - A unit test uploads two image sizes with the same filename in parallel. It checks that each size gets its own suffixed filename. This test failed before this change. - An integration test uploads an image with one image size and `addRandomSuffix: true`. It checks that every filename on the document has an object in storage, and that the main object size is equal to the document `filesize`. This test failed on every run before this change. ## Related work - Stack: #18388 → #18913 → this PR → #18921 - The bug started in #5928, the first version of the storage packages. - Not in scope: #18384 (the create response has a `url` without the suffix) and #18804 (focal point with a new filename). --------- Co-authored-by: Jarrod Flesch <[email protected]>
1 parent 6fc83d7 commit 8282414

9 files changed

Lines changed: 207 additions & 6 deletions

File tree

‎packages/plugin-cloud-storage/src/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ export interface File {
1414
clientUploadContext?: unknown
1515
filename: string
1616
filesize: number
17+
/** Configured image-size name. Undefined for the original file. */
18+
imageSizeName?: string
1719
mimeType: string
1820
tempFilePath?: string
1921
}

‎packages/plugin-cloud-storage/src/utilities/getIncomingFiles.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,14 @@ export function getIncomingFiles({
3434
files = [mainFile]
3535

3636
if (data?.sizes) {
37-
Object.entries(data.sizes).forEach(([key, resizedFileData]) => {
38-
if (payloadUploadSizes?.[key] && resizedFileData.mimeType) {
37+
Object.entries(data.sizes).forEach(([imageSizeName, resizedFileData]) => {
38+
if (payloadUploadSizes?.[imageSizeName] && resizedFileData.mimeType) {
3939
files = files.concat([
4040
{
41-
buffer: payloadUploadSizes[key],
41+
buffer: payloadUploadSizes[imageSizeName],
4242
filename: `${resizedFileData.filename}`,
43-
filesize: payloadUploadSizes[key].length,
43+
filesize: payloadUploadSizes[imageSizeName].length,
44+
imageSizeName,
4445
mimeType: resizedFileData.mimeType,
4546
},
4647
])
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { put } from '@vercel/blob'
2+
import { describe, expect, it, vi } from 'vitest'
3+
4+
vi.mock('@vercel/blob', async (importOriginal) => ({
5+
...(await importOriginal<typeof import('@vercel/blob')>()),
6+
put: vi.fn(async (pathname: string) => ({ pathname: pathname.replace('.png', '-suffix.png') })),
7+
}))
8+
9+
import { createVercelBlobAdapter } from './adapter.js'
10+
11+
const adapter = createVercelBlobAdapter({
12+
access: 'public',
13+
addRandomSuffix: true,
14+
baseUrl: 'https://example.com',
15+
cacheControlMaxAge: 60,
16+
token: 'token',
17+
})({ collection: { fields: [], slug: 'media', upload: {} }, prefix: '' })
18+
19+
describe('handleUpload with addRandomSuffix', () => {
20+
it.each([
21+
['main file', 'image.png', { filename: 'image-suffix.png', square: 'image-400x400.png' }],
22+
[
23+
'image size',
24+
'image-400x400.png',
25+
{ filename: 'image.png', square: 'image-400x400-suffix.png' },
26+
],
27+
])('should set the suffixed filename only on the %s', async (_, filename, expected) => {
28+
const data = { filename: 'image.png', sizes: { square: { filename: 'image-400x400.png' } } }
29+
30+
await adapter.handleUpload({
31+
data,
32+
file: {
33+
buffer: Buffer.from('file'),
34+
filename,
35+
filesize: 4,
36+
imageSizeName: filename === 'image.png' ? undefined : 'square',
37+
mimeType: 'image/png',
38+
},
39+
storageFilePath: filename,
40+
} as never)
41+
42+
expect({ filename: data.filename, square: data.sizes.square.filename }).toEqual(expected)
43+
})
44+
45+
it('should give image sizes with the same dimensions their own suffixed filenames', async () => {
46+
vi.mocked(put)
47+
.mockResolvedValueOnce({ pathname: 'image-400x400-a.png' } as never)
48+
.mockResolvedValueOnce({ pathname: 'image-400x400-b.png' } as never)
49+
50+
const data = {
51+
filename: 'image.png',
52+
sizes: { card: { filename: 'image-400x400.png' }, square: { filename: 'image-400x400.png' } },
53+
}
54+
const uploadImageSize = (imageSizeName: string) =>
55+
adapter.handleUpload({
56+
data,
57+
file: {
58+
buffer: Buffer.from('file'),
59+
filename: 'image-400x400.png',
60+
filesize: 4,
61+
imageSizeName,
62+
mimeType: 'image/png',
63+
},
64+
storageFilePath: 'image-400x400.png',
65+
} as never)
66+
67+
await Promise.all([uploadImageSize('card'), uploadImageSize('square')])
68+
69+
expect(data.sizes).toEqual({
70+
card: { filename: 'image-400x400-a.png' },
71+
square: { filename: 'image-400x400-b.png' },
72+
})
73+
})
74+
})

‎packages/storage-vercel-blob/src/adapter.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ export function createVercelBlobAdapter({
4949
token,
5050
}),
5151

52-
handleUpload: async ({ data, file: { buffer, mimeType, tempFilePath }, storageFilePath }) => {
52+
handleUpload: async ({
53+
data,
54+
file: { buffer, imageSizeName, mimeType, tempFilePath },
55+
storageFilePath,
56+
}) => {
5357
const result = await uploadFile({
5458
access,
5559
addRandomSuffix,
@@ -62,7 +66,11 @@ export function createVercelBlobAdapter({
6266
})
6367

6468
if (result.filename) {
65-
data.filename = result.filename
69+
if (imageSizeName !== undefined) {
70+
data.sizes[imageSizeName].filename = result.filename
71+
} else {
72+
data.filename = result.filename
73+
}
6674
}
6775

6876
return data
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import type { CollectionConfig } from 'payload'
2+
3+
import { mediaWithRandomSuffixSlug } from '../shared.js'
4+
5+
export const MediaWithRandomSuffix: CollectionConfig = {
6+
slug: mediaWithRandomSuffixSlug,
7+
fields: [],
8+
upload: {
9+
imageSizes: [
10+
{
11+
name: 'square',
12+
height: 400,
13+
width: 400,
14+
},
15+
],
16+
},
17+
}

‎test/storage-vercel-blob/config.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@ import { MediaWithAlwaysInsertFields } from './collections/MediaWithAlwaysInsert
1010
import { MediaWithDirectAccess } from './collections/MediaWithDirectAccess.js'
1111
import { MediaWithDynamicPrefix } from './collections/MediaWithDynamicPrefix.js'
1212
import { MediaWithPrefix } from './collections/MediaWithPrefix.js'
13+
import { MediaWithRandomSuffix } from './collections/MediaWithRandomSuffix.js'
1314
import { Users } from './collections/Users.js'
1415
import {
1516
mediaSlug,
1617
mediaWithAlwaysInsertFieldsSlug,
1718
mediaWithDirectAccessSlug,
1819
mediaWithDynamicPrefixSlug,
1920
mediaWithPrefixSlug,
21+
mediaWithRandomSuffixSlug,
2022
prefix,
2123
} from './shared.js'
2224

@@ -44,6 +46,7 @@ export default buildConfigWithDefaults({
4446
MediaWithDirectAccess,
4547
MediaWithDynamicPrefix,
4648
MediaWithPrefix,
49+
MediaWithRandomSuffix,
4750
Users,
4851
],
4952
onInit: async (payload) => {
@@ -69,6 +72,13 @@ export default buildConfigWithDefaults({
6972
},
7073
token: process.env.BLOB_READ_WRITE_TOKEN,
7174
}),
75+
vercelBlobStorage({
76+
addRandomSuffix: true,
77+
collections: {
78+
[mediaWithRandomSuffixSlug]: true,
79+
},
80+
token: process.env.BLOB_READ_WRITE_TOKEN,
81+
}),
7282
// Test alwaysInsertFields with enabled: false
7383
vercelBlobStorage({
7484
alwaysInsertFields: true,

‎test/storage-vercel-blob/int.spec.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { Payload } from 'payload'
22

3+
import { list } from '@vercel/blob'
34
import dotenv from 'dotenv'
45
import path from 'path'
56
import { fileURLToPath } from 'url'
@@ -14,6 +15,7 @@ import {
1415
mediaWithDirectAccessSlug,
1516
mediaWithDynamicPrefixSlug,
1617
mediaWithPrefixSlug,
18+
mediaWithRandomSuffixSlug,
1719
prefix,
1820
} from './shared.js'
1921
import { clearTestBlobs, verifyUploads } from './test-utils.js'
@@ -45,6 +47,7 @@ describe('@payloadcms/storage-vercel-blob', () => {
4547
payload.delete({ collection: mediaWithAlwaysInsertFieldsSlug, where: {} }),
4648
payload.delete({ collection: mediaWithDirectAccessSlug, where: {} }),
4749
payload.delete({ collection: mediaWithDynamicPrefixSlug, where: {} }),
50+
payload.delete({ collection: mediaWithRandomSuffixSlug, where: {} }),
4851
])
4952
})
5053

@@ -66,6 +69,24 @@ describe('@payloadcms/storage-vercel-blob', () => {
6669
expect(upload.url).toEqual(`/api/${mediaSlug}/file/${String(upload.filename)}`)
6770
})
6871

72+
it('should store the main file and image sizes under their suffixed filenames', async () => {
73+
const upload = await payload.create({
74+
collection: mediaWithRandomSuffixSlug,
75+
data: {},
76+
filePath: path.resolve(dirname, '../uploads/image.png'),
77+
})
78+
const { blobs } = await list()
79+
const storedMain = blobs.find(({ pathname }) => pathname === upload.filename)
80+
81+
expect(storedMain?.size).toBe(upload.filesize)
82+
83+
await verifyUploads({
84+
collectionSlug: mediaWithRandomSuffixSlug,
85+
payload,
86+
uploadId: upload.id,
87+
})
88+
})
89+
6990
it('can upload with prefix', async () => {
7091
const upload = await payload.create({
7192
collection: mediaWithPrefixSlug,

‎test/storage-vercel-blob/payload-types.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ export interface Config {
7272
'media-with-direct-access': MediaWithDirectAccess;
7373
'media-with-dynamic-prefix': MediaWithDynamicPrefix;
7474
'media-with-prefix': MediaWithPrefix;
75+
'media-with-random-suffix': MediaWithRandomSuffix;
7576
users: User;
7677
'payload-kv': PayloadKv;
7778
'payload-locked-documents': PayloadLockedDocument;
@@ -85,6 +86,7 @@ export interface Config {
8586
'media-with-direct-access': MediaWithDirectAccessSelect<false> | MediaWithDirectAccessSelect<true>;
8687
'media-with-dynamic-prefix': MediaWithDynamicPrefixSelect<false> | MediaWithDynamicPrefixSelect<true>;
8788
'media-with-prefix': MediaWithPrefixSelect<false> | MediaWithPrefixSelect<true>;
89+
'media-with-random-suffix': MediaWithRandomSuffixSelect<false> | MediaWithRandomSuffixSelect<true>;
8890
users: UsersSelect<false> | UsersSelect<true>;
8991
'payload-kv': PayloadKvSelect<false> | PayloadKvSelect<true>;
9092
'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;
@@ -255,6 +257,35 @@ export interface MediaWithPrefix {
255257
focalX?: number | null;
256258
focalY?: number | null;
257259
}
260+
/**
261+
* This interface was referenced by `Config`'s JSON-Schema
262+
* via the `definition` "media-with-random-suffix".
263+
*/
264+
export interface MediaWithRandomSuffix {
265+
id: string;
266+
_objectKey?: string | null;
267+
updatedAt: string;
268+
createdAt: string;
269+
url?: string | null;
270+
thumbnailURL?: string | null;
271+
filename?: string | null;
272+
mimeType?: string | null;
273+
filesize?: number | null;
274+
width?: number | null;
275+
height?: number | null;
276+
focalX?: number | null;
277+
focalY?: number | null;
278+
sizes?: {
279+
square?: {
280+
url?: string | null;
281+
width?: number | null;
282+
height?: number | null;
283+
mimeType?: string | null;
284+
filesize?: number | null;
285+
filename?: string | null;
286+
};
287+
};
288+
}
258289
/**
259290
* This interface was referenced by `Config`'s JSON-Schema
260291
* via the `definition` "users".
@@ -325,6 +356,10 @@ export interface PayloadLockedDocument {
325356
relationTo: 'media-with-prefix';
326357
value: string | MediaWithPrefix;
327358
} | null)
359+
| ({
360+
relationTo: 'media-with-random-suffix';
361+
value: string | MediaWithRandomSuffix;
362+
} | null)
328363
| ({
329364
relationTo: 'users';
330365
value: string | User;
@@ -506,6 +541,38 @@ export interface MediaWithPrefixSelect<T extends boolean = true> {
506541
focalX?: T;
507542
focalY?: T;
508543
}
544+
/**
545+
* This interface was referenced by `Config`'s JSON-Schema
546+
* via the `definition` "media-with-random-suffix_select".
547+
*/
548+
export interface MediaWithRandomSuffixSelect<T extends boolean = true> {
549+
_objectKey?: T;
550+
updatedAt?: T;
551+
createdAt?: T;
552+
url?: T;
553+
thumbnailURL?: T;
554+
filename?: T;
555+
mimeType?: T;
556+
filesize?: T;
557+
width?: T;
558+
height?: T;
559+
focalX?: T;
560+
focalY?: T;
561+
sizes?:
562+
| T
563+
| {
564+
square?:
565+
| T
566+
| {
567+
url?: T;
568+
width?: T;
569+
height?: T;
570+
mimeType?: T;
571+
filesize?: T;
572+
filename?: T;
573+
};
574+
};
575+
}
509576
/**
510577
* This interface was referenced by `Config`'s JSON-Schema
511578
* via the `definition` "users_select".

‎test/storage-vercel-blob/shared.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ export const mediaWithCompositePrefixesSlug = 'media-with-composite-prefixes'
44
export const mediaWithAlwaysInsertFieldsSlug = 'media-with-always-insert-fields'
55
export const mediaWithDynamicPrefixSlug = 'media-with-dynamic-prefix'
66
export const mediaWithDirectAccessSlug = 'media-with-direct-access'
7+
export const mediaWithRandomSuffixSlug = 'media-with-random-suffix'
78
export const resizedMediaSlug = 'resized-media'
89
export const prefix = 'test-prefix'
910
export const collectionPrefix = 'collection-prefix'

0 commit comments

Comments
 (0)