fix(transcode): co-locate screenshots and derived artifacts in asset storage directory (#399)

* fix(transcode): co-locate screenshots and derived artifacts in asset storage directory

* refactor(transcode): centralize derived artifact directory resolution and strengthen upload assertions
This commit is contained in:
Yiling-J
2026-09-09 11:03:48 +08:00
committed by GitHub
parent 941000d277
commit b37b2172e7
9 changed files with 151 additions and 25 deletions
+83 -2
View File
@@ -727,8 +727,14 @@ describe('TranscodeService', () => {
expect(result.length).toBe(1)
expect(result[0].page).toBe(1)
expect(result[0].key).toContain('files/asset-1/pdf_pages/doc-page-1-')
expect(s3Service.putObject).toHaveBeenCalled()
expect(result[0].key).toContain('projects/p1/pdf_pages/doc-page-1-')
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
result[0].key,
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
})
describe('overlayAnnotationsOnBuffer Pixel Tests', () => {
@@ -976,6 +982,81 @@ describe('TranscodeService', () => {
)
})
it('should save screenshots in the same storage directory as assetKey', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(file: string, args: string[], cb: any) => {
if (file === 'ffmpeg') {
const outPath = args[args.length - 1]
fs.writeFileSync(outPath, 'fake-webp-image')
}
cb(null, { stdout: '', stderr: '' })
},
)
const results = await transcodeService.takeScreenshots({
assetKey: 'files/storage-ulid-abc/video.mp4',
assetId: 'asset-db-id-xyz',
start: 0,
end: 0,
count: 1,
})
expect(results).toHaveLength(1)
expect(results[0].key).toMatch(/^files\/storage-ulid-abc\/screenshots\/shot-.*\.webp$/)
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
results[0].key,
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
})
it('should save overlay annotations in the same storage directory as assetKey', async () => {
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_bucket, _key, filePath) => {
// Create a dummy image file
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actualSharp = (await vi.importActual('sharp')) as any
const realSharp = (actualSharp.default || actualSharp) as typeof sharp
await realSharp({
create: {
width: 100,
height: 100,
channels: 4,
background: { r: 255, g: 255, b: 255, alpha: 1 },
},
})
.webp()
.toFile(filePath)
})
const key = await transcodeService.overlayAnnotations({
assetKey: 'files/storage-ulid-img/photo.webp',
assetId: 'asset-db-id-xyz',
annotations: [
{
type: 'box',
color: '#ff0000',
points: [
[0.1, 0.1],
[0.5, 0.5],
],
},
],
})
expect(key).toMatch(/^files\/storage-ulid-img\/annotations\/annotation-.*\.webp$/)
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
key,
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
})
it('should generate PDF from text file including CJK characters', async () => {
const txtFile = path.join(tempDir, 'test.txt')
const pdfFile = path.join(tempDir, 'output.pdf')
+7 -4
View File
@@ -1,5 +1,5 @@
import { s3Service } from '@shumai/core/src/s3/s3'
import { stemFromKey } from '@shumai/core/src/utils/filename'
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
import { mapConcurrent } from '../utils/async'
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
@@ -1275,7 +1275,8 @@ export class TranscodeService {
}
// 6. Upload to S3
const s3Key = `files/${params.assetId}/screenshots/${outName}`
const assetDir = getDerivedArtifactDirectory(params.assetKey, params.assetId)
const s3Key = `${assetDir}/screenshots/${outName}`
const fileBuffer = fs.readFileSync(localShotPath)
await s3Service.putObject(bucket, s3Key, fileBuffer, fileBuffer.length, 'image/webp')
@@ -1374,7 +1375,8 @@ export class TranscodeService {
}
// Upload to S3 directly from buffer
const s3Key = `files/${params.assetId}/pdf_pages/${webpName}`
const assetDir = getDerivedArtifactDirectory(params.assetKey, params.assetId)
const s3Key = `${assetDir}/pdf_pages/${webpName}`
await s3Service.putObject(bucket, s3Key, webpBuffer, webpBuffer.length, 'image/webp')
results.push({ key: s3Key, page: pageNum })
@@ -1429,7 +1431,8 @@ export class TranscodeService {
)
// 3. Upload to S3
const s3Key = `files/${params.assetId}/annotations/${outName}`
const assetDir = getDerivedArtifactDirectory(params.assetKey, params.assetId)
const s3Key = `${assetDir}/annotations/${outName}`
await s3Service.putObject(
bucket,
s3Key,
+19 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { sanitizeFilename, stemFromKey } from './filename'
import { getDerivedArtifactDirectory, sanitizeFilename, stemFromKey } from './filename'
describe('sanitizeFilename', () => {
it('returns the filename unchanged when it is already safe', () => {
@@ -64,3 +64,21 @@ describe('stemFromKey', () => {
expect(stemFromKey('raw')).toBe('raw')
})
})
describe('getDerivedArtifactDirectory', () => {
it('extracts the directory from a standard storage key', () => {
expect(getDerivedArtifactDirectory('files/01ABC/video.mp4')).toBe('files/01ABC')
expect(getDerivedArtifactDirectory('projects/p1/doc.pdf', 'asset-123')).toBe('projects/p1')
expect(getDerivedArtifactDirectory('a/b/c/file.txt')).toBe('a/b/c')
})
it('falls back to files/<assetId> when assetKey has no directory segment', () => {
expect(getDerivedArtifactDirectory('video.mp4', 'asset-123')).toBe('files/asset-123')
expect(getDerivedArtifactDirectory('doc.pdf', '01M21XYZ')).toBe('files/01M21XYZ')
})
it('returns empty string when assetKey has no directory segment and assetId is omitted or null', () => {
expect(getDerivedArtifactDirectory('video.mp4')).toBe('')
expect(getDerivedArtifactDirectory('video.mp4', null)).toBe('')
})
})
+16
View File
@@ -34,3 +34,19 @@ export function stemFromKey(key: string): string {
const ext = path.extname(basename)
return ext ? basename.slice(0, -ext.length) : basename
}
/**
* Resolves the parent directory for derived artifacts (e.g. screenshots, proxies, annotations).
* Prefers the directory of the asset's storage key, falling back to `files/<assetId>` if the key
* has no directory prefix.
*
* e.g. 'files/01ABC.../video.mp4' → 'files/01ABC...'
* 'video.mp4' (with assetId '01XYZ...') → 'files/01XYZ...'
*/
export function getDerivedArtifactDirectory(assetKey: string, assetId?: string | null): string {
const dir = path.posix.dirname(assetKey)
if (dir === '.' || !dir) {
return assetId ? `files/${assetId}` : ''
}
return dir
}
@@ -125,7 +125,7 @@ describe.each(['local', 'temporal'] as const)(
expect(output).toBeDefined()
expect(output.screenshots).toBeDefined()
expect(output.screenshots.length).toBe(1)
expect(output.screenshots[0].key).toContain('screenshots/')
expect(output.screenshots[0].key).toMatch(/^projects\/e2e\/screenshots\/shot-.*\.webp$/)
}, 50000)
it('should draw annotation box correctly for 5 random comment timestamps', async () => {
@@ -150,7 +150,7 @@ describe.each(['local', 'temporal'] as const)(
}
expect(mediaInfo).toBeDefined()
expect(mediaInfo.proxyType).toBe('pdf')
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
expect(mediaInfo.pdfTranscode?.key).toBe('projects/e2e/proxy.pdf')
expect(mediaInfo.poster?.key).toContain('poster.webp')
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
expect(mediaInfo.frames).toBeGreaterThan(0)
@@ -231,7 +231,7 @@ describe.each(['local', 'temporal'] as const)(
}
expect(mediaInfo).toBeDefined()
expect(mediaInfo.proxyType).toBe('pdf')
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
expect(mediaInfo.pdfTranscode?.key).toBe('projects/e2e/proxy.pdf')
expect(mediaInfo.poster?.key).toContain('poster.webp')
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
expect(mediaInfo.frames).toBeGreaterThan(0)
@@ -312,7 +312,7 @@ describe.each(['local', 'temporal'] as const)(
}
expect(mediaInfo).toBeDefined()
expect(mediaInfo.proxyType).toBe('pdf')
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
expect(mediaInfo.pdfTranscode?.key).toBe('projects/e2e/proxy.pdf')
expect(mediaInfo.poster?.key).toContain('poster.webp')
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
expect(mediaInfo.frames).toBeGreaterThan(0)
+2 -2
View File
@@ -222,7 +222,7 @@ describe.each(['local', 'temporal'] as const)(
}
expect(mediaInfo).toBeDefined()
expect(mediaInfo.proxyType).toBe('pdf')
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
expect(mediaInfo.pdfTranscode?.key).toBe('projects/e2e/proxy.pdf')
expect(mediaInfo.poster?.key).toContain('poster.webp')
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
expect(mediaInfo.frames).toBeGreaterThan(0)
@@ -308,7 +308,7 @@ describe.each(['local', 'temporal'] as const)(
}
expect(mediaInfo).toBeDefined()
expect(mediaInfo.proxyType).toBe('pdf')
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
expect(mediaInfo.pdfTranscode?.key).toBe('projects/e2e/proxy.pdf')
expect(mediaInfo.poster?.key).toContain('poster.webp')
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
expect(mediaInfo.frames).toBeGreaterThan(0)
@@ -131,7 +131,7 @@ describe('Transcode Activities', () => {
filename: 'wide.csv',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(convertSpy).toHaveBeenCalledWith('/tmp/wide.csv', 'wide.csv', { landscape: true })
vi.mocked(fs.readFileSync).mockImplementation(() => Buffer.from('fake data') as never)
})
@@ -161,7 +161,7 @@ describe('Transcode Activities', () => {
filename: 'narrow.csv',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(convertSpy).toHaveBeenCalledWith('/tmp/narrow.csv', 'narrow.csv', { landscape: false })
vi.mocked(fs.readFileSync).mockImplementation(() => Buffer.from('fake data') as never)
})
@@ -333,7 +333,14 @@ describe('Transcode Activities', () => {
filename: 'test.txt',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'files/asset1/proxy.pdf',
expect.anything(),
expect.any(Number),
'application/pdf',
)
expect(generatePdfFromTextSpy).toHaveBeenCalled()
generatePdfFromTextSpy.mockRestore()
})
@@ -359,7 +366,7 @@ describe('Transcode Activities', () => {
filename: 'README.md',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(generatePdfFromTextSpy).toHaveBeenCalledWith(
'/tmp/README.md',
expect.stringContaining('proxy.pdf'),
@@ -385,7 +392,7 @@ describe('Transcode Activities', () => {
filename: 'README.md',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(convertMdSpy).toHaveBeenCalledWith('/tmp/README.md', 'README.md')
})
@@ -407,7 +414,7 @@ describe('Transcode Activities', () => {
filename: 'document.docx',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(convertSpy).toHaveBeenCalledWith('/tmp/document.docx', 'document.docx')
})
@@ -429,7 +436,7 @@ describe('Transcode Activities', () => {
filename: 'index.html',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(convertHtmlSpy).toHaveBeenCalledWith('/tmp/index.html', 'index.html')
})
@@ -490,7 +497,7 @@ describe('Transcode Activities', () => {
filename: 'data.csv',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(generatePdfFromCsvSpy).toHaveBeenCalledWith(
'/tmp/data.csv',
expect.stringContaining('proxy.pdf'),
@@ -516,7 +523,7 @@ describe('Transcode Activities', () => {
filename: 'notes.txt',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(convertSpy).toHaveBeenCalledWith('/tmp/notes.txt', 'notes.txt')
})
@@ -541,7 +548,7 @@ describe('Transcode Activities', () => {
filename: 'notes.txt',
})
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
expect(res.pdfProxyKey).toBe('files/asset1/proxy.pdf')
expect(generatePdfFromTextSpy).toHaveBeenCalledWith(
'/tmp/notes.txt',
expect.stringContaining('proxy.pdf'),
@@ -2,7 +2,7 @@ import { prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { stemFromKey } from '@shumai/core/src/utils/filename'
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { parseCsvContent } from '@shumai/core/src/transcode/transcode'
import {
@@ -535,7 +535,8 @@ export async function generatePdfProxyActivity(
}
const bucket = process.env.S3_BUCKET || 'shumai'
const pdfProxyKey = `files/${params.assetId}/proxy.pdf`
const assetDir = getDerivedArtifactDirectory(params.assetKey, params.assetId)
const pdfProxyKey = `${assetDir}/proxy.pdf`
const tmpDir = path.dirname(params.filePath)
const pdfFilePath = path.join(tmpDir, 'proxy.pdf')