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:
@@ -1,7 +1,11 @@
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { prisma, AssetStatus, AssetType } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import {
|
||||
registerLocalTaskAbortController,
|
||||
unregisterLocalTaskAbortController,
|
||||
} from '@shumai/workflow-core'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
||||
@@ -1464,6 +1468,109 @@ describe('Transcode Activities', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('should fail fast with non-retryable error when task is already cancelled', async () => {
|
||||
const taskId = 'task-chunk-pre-aborted'
|
||||
const abortController = new AbortController()
|
||||
abortController.abort()
|
||||
registerLocalTaskAbortController(taskId, abortController)
|
||||
|
||||
try {
|
||||
expect.assertions(3)
|
||||
try {
|
||||
await transcodeVideoChunkActivity({
|
||||
taskId,
|
||||
assetId: 'asset-abc',
|
||||
filePath: '/tmp/test.mp4',
|
||||
startTime: 0,
|
||||
endTime: 10,
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
|
||||
expect((err as Error).message).toContain('Video chunk transcoding cancelled')
|
||||
}
|
||||
expect(child_process.execFile).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
unregisterLocalTaskAbortController(taskId)
|
||||
}
|
||||
})
|
||||
|
||||
it('should pass AbortSignal to ffmpeg and throw non-retryable error on in-flight cancellation', async () => {
|
||||
const taskId = 'task-chunk-inflight-abort'
|
||||
const abortController = new AbortController()
|
||||
registerLocalTaskAbortController(taskId, abortController)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- execFile mockImplementation uses 4-arg overload with options
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
(
|
||||
_file: string,
|
||||
_args: string[],
|
||||
options: { signal?: AbortSignal },
|
||||
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
|
||||
) => {
|
||||
expect(options?.signal).toBe(abortController.signal)
|
||||
abortController.abort()
|
||||
const abortErr = new Error('The operation was aborted') as Error & { code?: string }
|
||||
abortErr.code = 'ABORT_ERR'
|
||||
cb(abortErr, { stdout: '', stderr: '' })
|
||||
},
|
||||
)
|
||||
|
||||
try {
|
||||
expect.assertions(4)
|
||||
try {
|
||||
await transcodeVideoChunkActivity({
|
||||
taskId,
|
||||
assetId: 'asset-abc',
|
||||
filePath: '/tmp/test.mp4',
|
||||
startTime: 0,
|
||||
endTime: 10,
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
|
||||
expect((err as Error).message).toContain('Video chunk transcoding cancelled')
|
||||
}
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
unregisterLocalTaskAbortController(taskId)
|
||||
}
|
||||
})
|
||||
|
||||
it('should fail with non-retryable error before S3 upload if asset is pending_purge', async () => {
|
||||
const purgingAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'purging-video.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.pending_purge,
|
||||
mediaType: 'video/mp4',
|
||||
},
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- execFile mockImplementation returns void rather than ChildProcess
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
(
|
||||
_file: string,
|
||||
_args: string[],
|
||||
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
|
||||
) => {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
},
|
||||
)
|
||||
|
||||
expect.assertions(3)
|
||||
try {
|
||||
await transcodeVideoChunkActivity({
|
||||
assetId: purgingAsset.id,
|
||||
assetKey: 'files/proxy-720p.mp4',
|
||||
startTime: 0,
|
||||
endTime: 10,
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
|
||||
expect((err as Error).message).toContain('pending purge')
|
||||
}
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should return existing poster if already present in S3', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({} as any)
|
||||
|
||||
@@ -1580,7 +1580,27 @@ export const createAutofillTaskIfEnabledActivity = defineStep(
|
||||
},
|
||||
)
|
||||
|
||||
async function ensureAssetNotPurgingByIdOrKey(assetId: string, assetKey?: string): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { status: true, storageKey: { select: { status: true } } },
|
||||
})
|
||||
if (
|
||||
asset &&
|
||||
(asset.status === AssetStatus.pending_purge || asset.storageKey?.status === 'purging')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Asset or storage key has been purged or is pending purge',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (assetKey) {
|
||||
await ensureAssetNotPurging(assetKey)
|
||||
}
|
||||
}
|
||||
|
||||
export interface TranscodeVideoChunkParams {
|
||||
taskId?: string
|
||||
assetId: string
|
||||
assetKey?: string
|
||||
filePath?: string
|
||||
@@ -1599,6 +1619,28 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
})
|
||||
}
|
||||
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Video chunk transcoding cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const runFfmpeg = (args: string[]) =>
|
||||
signal ? execFileAsync('ffmpeg', args, { signal }) : execFileAsync('ffmpeg', args)
|
||||
|
||||
const isAbortError = (err: unknown): boolean => {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
return (
|
||||
Boolean(signal?.aborted) ||
|
||||
code === 'ABORT_ERR' ||
|
||||
message.includes('aborted') ||
|
||||
lowerMsg.includes('abort')
|
||||
)
|
||||
}
|
||||
|
||||
if (params.format === 'frames') {
|
||||
const tmpDir = transcodeService.createTempDir('video-chunk-frames-')
|
||||
try {
|
||||
@@ -1618,7 +1660,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
const fpsFilter = duration > 16 ? `fps=${16 / duration}` : 'fps=1'
|
||||
const vframesArgs = duration > 16 ? ['-vframes', '16'] : []
|
||||
|
||||
await execFileAsync('ffmpeg', [
|
||||
await runFfmpeg([
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
@@ -1658,6 +1700,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
archiveBytes.byteOffset,
|
||||
archiveBytes.byteLength,
|
||||
)
|
||||
await ensureAssetNotPurgingByIdOrKey(params.assetId, params.assetKey)
|
||||
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
|
||||
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
|
||||
|
||||
@@ -1666,6 +1709,13 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
if (isAbortError(err)) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Video chunk transcoding cancelled',
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to extract video chunk frames for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: false,
|
||||
@@ -1691,7 +1741,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
|
||||
// Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization
|
||||
// Note: -ss placed before -i for fast input seeking via demuxer Range requests
|
||||
await execFileAsync('ffmpeg', [
|
||||
await runFfmpeg([
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
@@ -1720,6 +1770,8 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
|
||||
const chunkData = fs.readFileSync(chunkTmp)
|
||||
|
||||
await ensureAssetNotPurgingByIdOrKey(params.assetId, params.assetKey)
|
||||
|
||||
// Upload to S3
|
||||
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
|
||||
|
||||
@@ -1730,6 +1782,13 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
if (isAbortError(err)) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Video chunk transcoding cancelled',
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: false,
|
||||
@@ -1739,7 +1798,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
try {
|
||||
fs.unlinkSync(chunkTmp)
|
||||
} catch (e) {
|
||||
console.error('Failed to cleanup local chunk file:', e)
|
||||
logger.error({ err: e, chunkTmp }, 'Failed to cleanup local chunk file')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { takeVideoScreenshotsWorkflow } from './workflows/take-video-screenshots
|
||||
import { overlayImageAnnotationWorkflow } from './workflows/overlay-image-annotation'
|
||||
import { transcodeWatermarkWorkflow } from './workflows/transcode-watermark'
|
||||
import { transcode3dWorkflow } from './workflows/transcode-3d'
|
||||
import { transcodeVideoChunksWorkflow } from './workflows/transcode-video-chunks'
|
||||
import { transcodeMedia } from './workflows/transcode'
|
||||
import { archiveAssetWorkflow } from './workflows/archive-asset'
|
||||
import { restoreAssetWorkflow } from './workflows/restore-asset'
|
||||
@@ -22,6 +23,7 @@ export function initTranscodeWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_watermark, transcodeWatermarkWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_video_chunks, transcodeVideoChunksWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.archive_asset, archiveAssetWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.restore_asset, restoreAssetWorkflow)
|
||||
}
|
||||
@@ -30,6 +32,7 @@ export * from './transcoder'
|
||||
export * from './workflows/transcode'
|
||||
export * from './workflows/transcode-3d'
|
||||
export * from './workflows/transcode-watermark'
|
||||
export * from './workflows/transcode-video-chunks'
|
||||
export * from './workflows/archive-asset'
|
||||
export * from './workflows/restore-asset'
|
||||
export * from './activities/transcode'
|
||||
|
||||
@@ -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