mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
refactor(transcode): offload video embedding chunk slicing to transcode queue (#539)
* refactor(transcode): offload video embedding chunk slicing to transcode queue * fix(transcode): address video chunk offloading review findings
This commit is contained in:
@@ -0,0 +1,262 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodeVideoChunksWorkflow } from './transcode-video-chunks'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
|
||||
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
transcodeVideoChunkActivity: vi.fn(),
|
||||
deleteS3ObjectActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
function createMockTask(overrides?: Partial<WorkflowTask>): WorkflowTask {
|
||||
return {
|
||||
id: 'task-video-chunks',
|
||||
assetId: 'asset-video',
|
||||
type: WorkflowTaskType.transcode_video_chunks,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
videoChunks: {
|
||||
parentTaskId: 'parent-emb-1',
|
||||
assetKey: 'files/asset-video/proxy.mp4',
|
||||
format: 'video',
|
||||
chunks: [
|
||||
{ startTime: 0, endTime: 60 },
|
||||
{ startTime: 55, endTime: 110 },
|
||||
],
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('transcodeVideoChunksWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
transcodeVideoChunkActivity: vi.mocked(transcodeVideoChunkActivity),
|
||||
deleteS3ObjectActivity: vi.mocked(deleteS3ObjectActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({} as never)
|
||||
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('should transcode all requested video chunks and complete with chunk keys', async () => {
|
||||
const task = createMockTask()
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-video',
|
||||
status: 'processed',
|
||||
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
|
||||
mediaType: 'video/mp4',
|
||||
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
|
||||
|
||||
mockActivities.transcodeVideoChunkActivity
|
||||
.mockResolvedValueOnce({
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
|
||||
})
|
||||
|
||||
await transcodeVideoChunksWorkflow(task)
|
||||
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(2)
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
|
||||
taskId: 'task-video-chunks',
|
||||
assetId: 'asset-video',
|
||||
assetKey: 'files/asset-video/proxy.mp4',
|
||||
startTime: 0,
|
||||
endTime: 60,
|
||||
format: 'video',
|
||||
})
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
|
||||
taskId: 'task-video-chunks',
|
||||
assetId: 'asset-video',
|
||||
assetKey: 'files/asset-video/proxy.mp4',
|
||||
startTime: 55,
|
||||
endTime: 110,
|
||||
format: 'video',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-video-chunks',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: {
|
||||
chunks: [
|
||||
{
|
||||
startTime: 0,
|
||||
endTime: 60,
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
},
|
||||
{
|
||||
startTime: 55,
|
||||
endTime: 110,
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should fall back to videoTranscodes proxy when assetKey is omitted and support frames format on archived assets', async () => {
|
||||
const task = createMockTask({
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
videoChunks: {
|
||||
parentTaskId: 'parent-emb-2',
|
||||
format: 'frames',
|
||||
chunks: [{ startTime: 0, endTime: 30 }],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-video',
|
||||
status: 'archived',
|
||||
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: true },
|
||||
mediaType: 'video/mp4',
|
||||
media: {
|
||||
videoTranscodes: [{ key: 'files/asset-video/proxy-720p.mp4' }],
|
||||
},
|
||||
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
|
||||
|
||||
mockActivities.transcodeVideoChunkActivity.mockResolvedValueOnce({
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/frames-0-30.tar',
|
||||
})
|
||||
|
||||
await transcodeVideoChunksWorkflow(task)
|
||||
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-video-chunks',
|
||||
assetId: 'asset-video',
|
||||
assetKey: 'files/asset-video/proxy-720p.mp4',
|
||||
startTime: 0,
|
||||
endTime: 30,
|
||||
format: 'frames',
|
||||
})
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-video-chunks',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: {
|
||||
chunks: [
|
||||
{
|
||||
startTime: 0,
|
||||
endTime: 30,
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/frames-0-30.tar',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should fail with non-retryable ApplicationFailure when payload is invalid', async () => {
|
||||
const task = createMockTask({
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
|
||||
'Invalid payload for videoChunks task',
|
||||
)
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-video-chunks',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Invalid payload for videoChunks task' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should fail fast when asset is archived and no videoTranscodes proxy is available', async () => {
|
||||
const task = createMockTask({
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
videoChunks: {
|
||||
assetKey: 'files/asset-video/raw.mp4',
|
||||
format: 'video',
|
||||
chunks: [{ startTime: 0, endTime: 60 }],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-video',
|
||||
status: 'archived',
|
||||
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: true },
|
||||
mediaType: 'video/mp4',
|
||||
media: {
|
||||
videoTranscodes: [],
|
||||
},
|
||||
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
|
||||
|
||||
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
|
||||
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
|
||||
)
|
||||
|
||||
expect(mockActivities.transcodeVideoChunkActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-video-chunks',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: {
|
||||
error:
|
||||
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should clean up already-uploaded chunk files in S3 if a subsequent chunk fails', async () => {
|
||||
const task = createMockTask()
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-video',
|
||||
status: 'processed',
|
||||
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
|
||||
mediaType: 'video/mp4',
|
||||
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
|
||||
|
||||
mockActivities.transcodeVideoChunkActivity
|
||||
.mockResolvedValueOnce({
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
})
|
||||
.mockRejectedValueOnce(new Error('ffmpeg slice failed on chunk 2'))
|
||||
|
||||
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
|
||||
'ffmpeg slice failed on chunk 2',
|
||||
)
|
||||
|
||||
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(1)
|
||||
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledWith({
|
||||
key: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
})
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-video-chunks',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'ffmpeg slice failed on chunk 2' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
|
||||
import { completeTask, failTask, fetchAssetWithKey, startTask } from './common'
|
||||
|
||||
export interface TranscodedVideoChunkItem {
|
||||
startTime: number
|
||||
endTime: number
|
||||
chunkKey: string
|
||||
}
|
||||
|
||||
export async function transcodeVideoChunksWorkflow(task: WorkflowTask): Promise<void> {
|
||||
const uploadedChunkKeys: string[] = []
|
||||
|
||||
try {
|
||||
await startTask(task)
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload?.videoChunks || !Array.isArray(payload.videoChunks.chunks)) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Invalid payload for videoChunks task',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
let targetKey = payload.videoChunks.assetKey || key
|
||||
|
||||
if (!payload.videoChunks.assetKey && asset?.media) {
|
||||
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
|
||||
if (mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) {
|
||||
const transcode = mediaInfo.videoTranscodes[0]
|
||||
if (transcode?.key) {
|
||||
targetKey = transcode.key
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targetKey === key && (asset.storageKey?.isArchived || asset.status === 'archived')) {
|
||||
throw ApplicationFailure.create({
|
||||
message:
|
||||
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const chunks: TranscodedVideoChunkItem[] = []
|
||||
for (const range of payload.videoChunks.chunks) {
|
||||
const { chunkKey } = await transcodeVideoChunkActivity({
|
||||
taskId: task.id,
|
||||
assetId: asset.id,
|
||||
assetKey: targetKey,
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
format: payload.videoChunks.format,
|
||||
})
|
||||
uploadedChunkKeys.push(chunkKey)
|
||||
chunks.push({
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
chunkKey,
|
||||
})
|
||||
}
|
||||
|
||||
await completeTask(task.id, { chunks })
|
||||
} catch (err) {
|
||||
logger.error({ taskId: task.id, err }, 'transcodeVideoChunksWorkflow failed')
|
||||
for (const chunkKey of uploadedChunkKeys) {
|
||||
try {
|
||||
await deleteS3ObjectActivity({ key: chunkKey })
|
||||
} catch (cleanupErr) {
|
||||
logger.error(
|
||||
{ taskId: task.id, chunkKey, err: cleanupErr },
|
||||
'Failed to clean up partial chunk',
|
||||
)
|
||||
}
|
||||
}
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user