mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 01:58:24 +00:00
refactor(workflow): simplify activities to use defineStep and direct calls (#482)
* refactor(workflow): simplify activities to use defineStep and direct calls - Wrap activities using defineStep from @shumai/workflow-core - Remove obsolete getActivities, registerActivities, dynamic activity proxies, and workerQueue arguments - Remove executor.ts and registry.ts, consolidating workflow registration into workflow.ts - Call activities directly across transcode and agent workflows - Update all corresponding workflow tests and developer guide documentation * fix(workflow): properly detect DBOSWorkflowCancelledError in runOnCancel fallback - DBOSWorkflowCancelledError in DBOS SDK does not set name, inheriting 'Error' - Implement isDbosWorkflowCancelledError checking instanceof, constructor.name, and dbosErrorCode - Update unit tests to verify real DBOS SDK cancellation error instances
This commit is contained in:
@@ -23,7 +23,7 @@ import {
|
||||
isOfficeDocument,
|
||||
} from '@shumai/core/src/utils/mime'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { ApplicationFailure, getLocalTaskAbortSignal } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure, defineStep, getLocalTaskAbortSignal } from '@shumai/workflow-core'
|
||||
|
||||
function getActivityCancellationSignal(taskId?: string): AbortSignal | undefined {
|
||||
return getLocalTaskAbortSignal(taskId)
|
||||
@@ -93,7 +93,7 @@ async function ensureAssetNotPurging(assetKey: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMediaInfoActivity(params: {
|
||||
export const getMediaInfoActivity = defineStep(async function getMediaInfoActivity(params: {
|
||||
filePath: string
|
||||
assetId: string
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
@@ -329,7 +329,7 @@ export async function getMediaInfoActivity(params: {
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface VideoActivityParams {
|
||||
taskId?: string
|
||||
@@ -351,7 +351,7 @@ export interface VideoActivityParams {
|
||||
audioStreamIndex?: number
|
||||
}
|
||||
|
||||
export async function transcodeVideoActivity(
|
||||
export const transcodeVideoActivity = defineStep(async function transcodeVideoActivity(
|
||||
params: VideoActivityParams,
|
||||
): Promise<PrismaJson.VideoTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -460,7 +460,7 @@ export async function transcodeVideoActivity(
|
||||
} finally {
|
||||
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface HlsActivityParams {
|
||||
taskId: string
|
||||
@@ -484,7 +484,9 @@ export interface HlsActivityParams {
|
||||
audioStreamIndex?: number
|
||||
}
|
||||
|
||||
export async function transcodeHlsActivity(params: HlsActivityParams): Promise<PrismaJson.HlsInfo> {
|
||||
export const transcodeHlsActivity = defineStep(async function transcodeHlsActivity(
|
||||
params: HlsActivityParams,
|
||||
): Promise<PrismaJson.HlsInfo> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const assetDir = path.posix.dirname(params.assetKey)
|
||||
const hlsDirKey = path.posix.join(assetDir, 'hls')
|
||||
@@ -648,7 +650,7 @@ export async function transcodeHlsActivity(params: HlsActivityParams): Promise<P
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface AudioActivityParams {
|
||||
taskId?: string
|
||||
@@ -658,7 +660,7 @@ export interface AudioActivityParams {
|
||||
audioStreamIndex?: number
|
||||
}
|
||||
|
||||
export async function transcodeAudioActivity(
|
||||
export const transcodeAudioActivity = defineStep(async function transcodeAudioActivity(
|
||||
params: AudioActivityParams,
|
||||
): Promise<PrismaJson.VideoTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -736,7 +738,7 @@ export async function transcodeAudioActivity(
|
||||
} finally {
|
||||
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface ImageActivityParams {
|
||||
assetKey: string
|
||||
@@ -744,7 +746,7 @@ export interface ImageActivityParams {
|
||||
imageSpec: PrismaJson.ImageTranscode
|
||||
}
|
||||
|
||||
export async function transcodeImageActivity(
|
||||
export const transcodeImageActivity = defineStep(async function transcodeImageActivity(
|
||||
params: ImageActivityParams,
|
||||
): Promise<PrismaJson.ImageTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -807,7 +809,7 @@ export async function transcodeImageActivity(
|
||||
} finally {
|
||||
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface GenerateSpriteActivityParams {
|
||||
taskId?: string
|
||||
@@ -818,7 +820,9 @@ export interface GenerateSpriteActivityParams {
|
||||
posterSpec: PrismaJson.PosterInfo
|
||||
}
|
||||
|
||||
export async function generateSpriteActivity(params: GenerateSpriteActivityParams) {
|
||||
export const generateSpriteActivity = defineStep(async function generateSpriteActivity(
|
||||
params: GenerateSpriteActivityParams,
|
||||
) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
@@ -929,7 +933,7 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
|
||||
if (fs.existsSync(spriteFile)) fs.unlinkSync(spriteFile)
|
||||
if (fs.existsSync(posterFile)) fs.unlinkSync(posterFile)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface GeneratePdfProxyActivityParams {
|
||||
teamId?: string | null
|
||||
@@ -940,7 +944,7 @@ export interface GeneratePdfProxyActivityParams {
|
||||
filename: string
|
||||
}
|
||||
|
||||
export async function generatePdfProxyActivity(
|
||||
export const generatePdfProxyActivity = defineStep(async function generatePdfProxyActivity(
|
||||
params: GeneratePdfProxyActivityParams,
|
||||
): Promise<{ pdfProxyKey: string; pdfFilePath: string }> {
|
||||
const isOffice = isOfficeDocument(params.mediaType, params.filename)
|
||||
@@ -1054,47 +1058,54 @@ export async function generatePdfProxyActivity(
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export async function downloadMediaToTmpActivity(params: {
|
||||
assetKey: string
|
||||
}): Promise<{ filePath: string; tmpDir: string }> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = transcodeService.createTempDir('transcode-')
|
||||
const filePath = path.join(tmpDir, path.basename(params.assetKey))
|
||||
export const downloadMediaToTmpActivity = defineStep(
|
||||
async function downloadMediaToTmpActivity(params: {
|
||||
assetKey: string
|
||||
}): Promise<{ filePath: string; tmpDir: string }> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = transcodeService.createTempDir('transcode-')
|
||||
const filePath = path.join(tmpDir, path.basename(params.assetKey))
|
||||
|
||||
if (!fs.existsSync(tmpDir)) {
|
||||
fs.mkdirSync(tmpDir, { recursive: true })
|
||||
}
|
||||
|
||||
try {
|
||||
await s3Service.downloadToFile(bucket, params.assetKey, filePath)
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
if (code === 'ENOENT' || lowerMsg.includes('enoent') || lowerMsg.includes('nosuchkey')) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to download media to tmp: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
if (!fs.existsSync(tmpDir)) {
|
||||
fs.mkdirSync(tmpDir, { recursive: true })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
return { filePath, tmpDir }
|
||||
}
|
||||
try {
|
||||
await s3Service.downloadToFile(bucket, params.assetKey, filePath)
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
if (code === 'ENOENT' || lowerMsg.includes('enoent') || lowerMsg.includes('nosuchkey')) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to download media to tmp: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
export async function cleanupTmpDirActivity(params: { tmpDir: string }): Promise<void> {
|
||||
transcodeService.removeDir(params.tmpDir)
|
||||
}
|
||||
return { filePath, tmpDir }
|
||||
},
|
||||
)
|
||||
|
||||
export const cleanupTmpDirActivity = defineStep(
|
||||
async function cleanupTmpDirActivity(params: { tmpDir: string }): Promise<void> {
|
||||
transcodeService.removeDir(params.tmpDir)
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface UpdateAssetMediaActivityParams {
|
||||
assetId: string
|
||||
mediaInfo: PrismaJson.MediaInfo
|
||||
}
|
||||
|
||||
export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityParams) {
|
||||
export const updateAssetMediaActivity = defineStep(async function updateAssetMediaActivity(
|
||||
params: UpdateAssetMediaActivityParams,
|
||||
) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
@@ -1126,9 +1137,9 @@ export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityP
|
||||
'[updateAssetMediaActivity] Asset was deleted or pending purge before media update completed',
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export async function takeScreenshotsActivity(params: {
|
||||
export const takeScreenshotsActivity = defineStep(async function takeScreenshotsActivity(params: {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
assetId: string
|
||||
@@ -1180,7 +1191,7 @@ export async function takeScreenshotsActivity(params: {
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface ExtractPosterActivityParams {
|
||||
assetKey: string
|
||||
@@ -1193,7 +1204,7 @@ export interface ExtractPosterActivityParams {
|
||||
streamIndex?: number
|
||||
}
|
||||
|
||||
export async function extractPosterActivity(
|
||||
export const extractPosterActivity = defineStep(async function extractPosterActivity(
|
||||
params: ExtractPosterActivityParams,
|
||||
): Promise<{ poster: PrismaJson.PosterInfo }> {
|
||||
const signal = params.signal || getActivityCancellationSignal(params.taskId)
|
||||
@@ -1272,36 +1283,38 @@ export async function extractPosterActivity(
|
||||
} finally {
|
||||
transcodeService.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export async function overlayAnnotationsActivity(params: {
|
||||
assetKey: string
|
||||
assetId: string
|
||||
annotations: PrismaJson.AnnotationList
|
||||
}): Promise<string> {
|
||||
try {
|
||||
return await transcodeService.overlayAnnotations(params)
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('nosuchkey') ||
|
||||
lowerMsg.includes('ffmpeg') ||
|
||||
lowerMsg.includes('sharp')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Overlay annotations failed: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
export const overlayAnnotationsActivity = defineStep(
|
||||
async function overlayAnnotationsActivity(params: {
|
||||
assetKey: string
|
||||
assetId: string
|
||||
annotations: PrismaJson.AnnotationList
|
||||
}): Promise<string> {
|
||||
try {
|
||||
return await transcodeService.overlayAnnotations(params)
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('nosuchkey') ||
|
||||
lowerMsg.includes('ffmpeg') ||
|
||||
lowerMsg.includes('sharp')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Overlay annotations failed: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export async function renderPdfPagesActivity(params: {
|
||||
export const renderPdfPagesActivity = defineStep(async function renderPdfPagesActivity(params: {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
assetId: string
|
||||
@@ -1352,7 +1365,7 @@ export async function renderPdfPagesActivity(params: {
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface CreateEmbeddingTaskIfEnabledParams {
|
||||
assetId: string
|
||||
@@ -1360,75 +1373,77 @@ export interface CreateEmbeddingTaskIfEnabledParams {
|
||||
projectId: string | null
|
||||
}
|
||||
|
||||
export async function createEmbeddingTaskIfEnabledActivity(
|
||||
params: CreateEmbeddingTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
})
|
||||
if (!asset) {
|
||||
return
|
||||
}
|
||||
|
||||
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
|
||||
const isVideo = asset.mediaType?.startsWith('video/')
|
||||
const isImage =
|
||||
asset.mediaType?.startsWith('image/') ||
|
||||
(mediaInfo?.proxyType === '3d' && (mediaInfo.imageTranscodes?.length ?? 0) > 0)
|
||||
if (!isVideo && !isImage) {
|
||||
return
|
||||
}
|
||||
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active embedding agent for the team
|
||||
const embeddingAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!embeddingAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing embedding task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create embedding task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: embeddingAgent.id },
|
||||
export const createEmbeddingTaskIfEnabledActivity = defineStep(
|
||||
async function createEmbeddingTaskIfEnabledActivity(
|
||||
params: CreateEmbeddingTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
if (!asset) {
|
||||
return
|
||||
}
|
||||
|
||||
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
|
||||
const isVideo = asset.mediaType?.startsWith('video/')
|
||||
const isImage =
|
||||
asset.mediaType?.startsWith('image/') ||
|
||||
(mediaInfo?.proxyType === '3d' && (mediaInfo.imageTranscodes?.length ?? 0) > 0)
|
||||
if (!isVideo && !isImage) {
|
||||
return
|
||||
}
|
||||
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active embedding agent for the team
|
||||
const embeddingAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!embeddingAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing embedding task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create embedding task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: embeddingAgent.id },
|
||||
},
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export interface CreateAutofillTaskIfEnabledParams {
|
||||
assetId: string
|
||||
@@ -1436,66 +1451,68 @@ export interface CreateAutofillTaskIfEnabledParams {
|
||||
projectId: string | null
|
||||
}
|
||||
|
||||
export async function createAutofillTaskIfEnabledActivity(
|
||||
params: CreateAutofillTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
})
|
||||
if (!asset || (asset.type !== 'file' && asset.type !== 'version_stack')) {
|
||||
return
|
||||
}
|
||||
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active autofill agent for the team
|
||||
const autofillAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!autofillAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing autofill task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create autofill task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: autofillAgent.id },
|
||||
export const createAutofillTaskIfEnabledActivity = defineStep(
|
||||
async function createAutofillTaskIfEnabledActivity(
|
||||
params: CreateAutofillTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
if (!asset || (asset.type !== 'file' && asset.type !== 'version_stack')) {
|
||||
return
|
||||
}
|
||||
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active autofill agent for the team
|
||||
const autofillAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!autofillAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing autofill task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create autofill task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: autofillAgent.id },
|
||||
},
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export interface TranscodeVideoChunkParams {
|
||||
assetId: string
|
||||
@@ -1506,7 +1523,7 @@ export interface TranscodeVideoChunkParams {
|
||||
format?: 'video' | 'frames'
|
||||
}
|
||||
|
||||
export async function transcodeVideoChunkActivity(
|
||||
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
|
||||
params: TranscodeVideoChunkParams,
|
||||
): Promise<{ chunkKey: string }> {
|
||||
if (!params.filePath && !params.assetKey) {
|
||||
@@ -1660,12 +1677,15 @@ export async function transcodeVideoChunkActivity(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
}
|
||||
export const deleteS3ObjectActivity = defineStep(
|
||||
async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface Render3dModelActivityParams {
|
||||
taskId: string
|
||||
@@ -1702,7 +1722,7 @@ export interface Start3dRenderActivityResult {
|
||||
modelMetadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export async function start3dRenderActivity(
|
||||
export const start3dRenderActivity = defineStep(async function start3dRenderActivity(
|
||||
params: Start3dRenderActivityParams,
|
||||
): Promise<Start3dRenderActivityResult> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
@@ -1783,7 +1803,7 @@ export async function start3dRenderActivity(
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface WaitFor3dVideoRenderActivityParams {
|
||||
taskId: string
|
||||
@@ -1798,7 +1818,7 @@ export interface WaitFor3dVideoRenderActivityResult {
|
||||
videoFilePath: string
|
||||
}
|
||||
|
||||
export async function waitFor3dVideoRenderActivity(
|
||||
export const waitFor3dVideoRenderActivity = defineStep(async function waitFor3dVideoRenderActivity(
|
||||
params: WaitFor3dVideoRenderActivityParams,
|
||||
): Promise<WaitFor3dVideoRenderActivityResult> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
@@ -1897,12 +1917,12 @@ export async function waitFor3dVideoRenderActivity(
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* @deprecated Legacy monolithic 3D render activity. Prefer using `start3dRenderActivity` and `waitFor3dVideoRenderActivity`.
|
||||
*/
|
||||
export async function render3dModelActivity(
|
||||
export const render3dModelActivity = defineStep(async function render3dModelActivity(
|
||||
params: Render3dModelActivityParams,
|
||||
): Promise<Render3dModelActivityResult> {
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
@@ -1930,7 +1950,7 @@ export async function render3dModelActivity(
|
||||
posterFilePath: startResult.posterFilePath,
|
||||
modelMetadata: startResult.modelMetadata,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface Generate3dSpriteActivityParams {
|
||||
taskId: string
|
||||
@@ -1939,7 +1959,7 @@ export interface Generate3dSpriteActivityParams {
|
||||
spriteKey: string
|
||||
}
|
||||
|
||||
export async function generate3dSpriteActivity(
|
||||
export const generate3dSpriteActivity = defineStep(async function generate3dSpriteActivity(
|
||||
params: Generate3dSpriteActivityParams,
|
||||
): Promise<{ spriteKey: string }> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
@@ -1978,7 +1998,7 @@ export async function generate3dSpriteActivity(
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface Generate3dViewsActivityParams {
|
||||
taskId: string
|
||||
@@ -1987,7 +2007,7 @@ export interface Generate3dViewsActivityParams {
|
||||
viewsKey: string
|
||||
}
|
||||
|
||||
export async function generate3dViewsActivity(
|
||||
export const generate3dViewsActivity = defineStep(async function generate3dViewsActivity(
|
||||
params: Generate3dViewsActivityParams,
|
||||
): Promise<{ viewsKey: string }> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
@@ -2026,4 +2046,4 @@ export async function generate3dViewsActivity(
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure, defineStep } from '@shumai/workflow-core'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
import { ulid } from 'ulid'
|
||||
@@ -35,7 +35,7 @@ export interface InitWatermarkFileResult {
|
||||
media?: PrismaJson.MediaInfo | null
|
||||
}
|
||||
|
||||
export async function initWatermarkFileActivity(
|
||||
export const initWatermarkFileActivity = defineStep(async function initWatermarkFileActivity(
|
||||
params: InitWatermarkFileParams,
|
||||
): Promise<InitWatermarkFileResult> {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
@@ -46,12 +46,12 @@ export async function initWatermarkFileActivity(
|
||||
media: PrismaJson.MediaInfo | null
|
||||
}>
|
||||
>`
|
||||
SELECT id, status, media
|
||||
FROM watermark_files
|
||||
WHERE asset_id = ${params.assetId}
|
||||
AND watermark_config_id = ${params.watermarkConfigId}
|
||||
FOR UPDATE
|
||||
`
|
||||
SELECT id, status, media
|
||||
FROM watermark_files
|
||||
WHERE asset_id = ${params.assetId}
|
||||
AND watermark_config_id = ${params.watermarkConfigId}
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
if (rows.length > 0) {
|
||||
const existing = rows[0]
|
||||
@@ -74,7 +74,7 @@ export async function initWatermarkFileActivity(
|
||||
|
||||
return { action: 'created' }
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export interface WaitForWatermarkFileParams {
|
||||
assetId: string
|
||||
@@ -86,7 +86,7 @@ export interface WaitForWatermarkFileResult {
|
||||
media?: PrismaJson.MediaInfo | null
|
||||
}
|
||||
|
||||
export async function waitForWatermarkFileActivity(
|
||||
export const waitForWatermarkFileActivity = defineStep(async function waitForWatermarkFileActivity(
|
||||
params: WaitForWatermarkFileParams,
|
||||
): Promise<WaitForWatermarkFileResult> {
|
||||
const pollIntervalMs = 1000
|
||||
@@ -113,358 +113,278 @@ export async function waitForWatermarkFileActivity(
|
||||
}
|
||||
|
||||
return { status: WatermarkFileStatus.failed }
|
||||
}
|
||||
})
|
||||
|
||||
export interface TranscodeWatermarkMediaParams {
|
||||
assetId: string
|
||||
watermarkConfigId: string
|
||||
}
|
||||
|
||||
export async function transcodeWatermarkMediaActivity(
|
||||
params: TranscodeWatermarkMediaParams,
|
||||
): Promise<PrismaJson.MediaInfo> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
export const transcodeWatermarkMediaActivity = defineStep(
|
||||
async function transcodeWatermarkMediaActivity(
|
||||
params: TranscodeWatermarkMediaParams,
|
||||
): Promise<PrismaJson.MediaInfo> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
const watermarkConfigRecord = await prisma.watermarkConfig.findUnique({
|
||||
where: { id: params.watermarkConfigId },
|
||||
})
|
||||
if (!watermarkConfigRecord) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Watermark config not found: ${params.watermarkConfigId}`,
|
||||
nonRetryable: true,
|
||||
const watermarkConfigRecord = await prisma.watermarkConfig.findUnique({
|
||||
where: { id: params.watermarkConfigId },
|
||||
})
|
||||
}
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: { team: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!asset || !asset.storageKey?.key) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset or storage key not found: ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const teamSettings = asset.project?.team?.settings as PrismaJson.Settings | null
|
||||
const hardwareAcceleration = teamSettings?.transcode?.hardwareAcceleration ?? 'off'
|
||||
const threads = teamSettings?.transcode?.threads ?? 0
|
||||
|
||||
// The config column is declared as PrismaJson.WatermarkConfigSpec, which is
|
||||
// structurally identical to the DTO type, so no cast is required.
|
||||
const config: WatermarkConfigSpec = watermarkConfigRecord.config
|
||||
const assetKey = asset.storageKey.key
|
||||
const stem = stemFromKey(assetKey)
|
||||
|
||||
const tmpDir = transcodeService.createTempDir('watermark-')
|
||||
|
||||
try {
|
||||
const is3d = (asset.media as PrismaJson.MediaInfo | null)?.proxyType === '3d'
|
||||
const isVideo =
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('video/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video')
|
||||
const isImage =
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('image/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image')
|
||||
|
||||
if (!isVideo && !isImage && !is3d) {
|
||||
if (!watermarkConfigRecord) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset ${params.assetId} is neither video nor image`,
|
||||
message: `Watermark config not found: ${params.watermarkConfigId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const inputKey = is3d
|
||||
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
|
||||
: assetKey
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: { team: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (is3d && !inputKey) {
|
||||
if (!asset || !asset.storageKey?.key) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
|
||||
message: `Asset or storage key not found: ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
|
||||
await s3Service.downloadToFile(bucket, inputKey!, rawFilePath)
|
||||
const teamSettings = asset.project?.team?.settings as PrismaJson.Settings | null
|
||||
const hardwareAcceleration = teamSettings?.transcode?.hardwareAcceleration ?? 'off'
|
||||
const threads = teamSettings?.transcode?.threads ?? 0
|
||||
|
||||
let originalWidth = 1920
|
||||
let originalHeight = 1080
|
||||
let duration = 0
|
||||
let bitRate = 0
|
||||
let videoBitRate: number | undefined
|
||||
let frameRate = 30
|
||||
let totalFrames = 0
|
||||
let startTimecode = '00:00:00:00'
|
||||
let hasAudio = false
|
||||
let sourceVideoBitrate: number | undefined
|
||||
let colorTransfer: string | undefined
|
||||
let colorPrimaries: string | undefined
|
||||
let colorSpace: string | undefined
|
||||
let isHdr: boolean | undefined
|
||||
let hdrType: PrismaJson.HdrType | undefined
|
||||
let dvProfile: number | undefined
|
||||
// The config column is declared as PrismaJson.WatermarkConfigSpec, which is
|
||||
// structurally identical to the DTO type, so no cast is required.
|
||||
const config: WatermarkConfigSpec = watermarkConfigRecord.config
|
||||
const assetKey = asset.storageKey.key
|
||||
const stem = stemFromKey(assetKey)
|
||||
|
||||
if (isVideo || is3d) {
|
||||
const info = await transcodeService.getVideoInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
duration = info.duration
|
||||
bitRate = info.bitRate
|
||||
videoBitRate = info.videoBitRate
|
||||
frameRate = info.frameRate
|
||||
totalFrames = info.totalFrames
|
||||
startTimecode = info.startTimecode || '00:00:00:00'
|
||||
hasAudio = info.hasAudio
|
||||
sourceVideoBitrate = info.videoBitRate || info.bitRate
|
||||
colorTransfer = info.colorTransfer
|
||||
colorPrimaries = info.colorPrimaries
|
||||
colorSpace = info.colorSpace
|
||||
isHdr = info.isHdr
|
||||
hdrType = info.hdrType
|
||||
dvProfile = info.dvProfile
|
||||
} else if (isImage) {
|
||||
const info = await transcodeService.getImageInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
}
|
||||
const tmpDir = transcodeService.createTempDir('watermark-')
|
||||
|
||||
// Process image blocks if any
|
||||
const blockImagesMap = new Map<string, RenderBlockImageData>()
|
||||
const imageBlocks = (config.blocks || []).filter(
|
||||
(b) => b.type === 'image',
|
||||
) as WatermarkBlockImage[]
|
||||
try {
|
||||
const is3d = (asset.media as PrismaJson.MediaInfo | null)?.proxyType === '3d'
|
||||
const isVideo =
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('video/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video')
|
||||
const isImage =
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('image/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image')
|
||||
|
||||
for (const imgBlock of imageBlocks) {
|
||||
if (!imgBlock.imageAssetKey) continue
|
||||
try {
|
||||
const imgTmpPath = path.join(tmpDir, `block-${ulid()}`)
|
||||
await s3Service.downloadToFile(bucket, imgBlock.imageAssetKey, imgTmpPath)
|
||||
const buffer = fs.readFileSync(imgTmpPath)
|
||||
// Downscale to a bounded size and normalize to PNG so large logo assets
|
||||
// don't balloon the SVG/base64 payload.
|
||||
const processed = await transcodeService.downscaleImageToPng(
|
||||
buffer,
|
||||
MAX_BLOCK_IMAGE_DIMENSION,
|
||||
)
|
||||
blockImagesMap.set(imgBlock.imageAssetKey, {
|
||||
imageAssetKey: imgBlock.imageAssetKey,
|
||||
base64Data: processed.buffer.toString('base64'),
|
||||
mimeType: 'image/png',
|
||||
width: processed.width,
|
||||
height: processed.height,
|
||||
})
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ imageAssetKey: imgBlock.imageAssetKey, err },
|
||||
'Failed to load watermark block image',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const originalMedia = asset.media as PrismaJson.MediaInfo | null
|
||||
|
||||
const mediaInfo: PrismaJson.MediaInfo = {
|
||||
duration,
|
||||
filesize: 0,
|
||||
frames: totalFrames,
|
||||
proxyType: is3d ? '3d' : isVideo ? 'video' : 'image',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
poster: originalMedia?.poster,
|
||||
sprite: originalMedia?.sprite,
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth,
|
||||
originalHeight,
|
||||
duration,
|
||||
bitRate,
|
||||
videoBitRate,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
startTimecode,
|
||||
hasAudio,
|
||||
colorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
colorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
colorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
isHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
hdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
dvProfile: dvProfile ?? originalMedia?.metadata?.dvProfile,
|
||||
format: originalMedia?.metadata?.format ?? {},
|
||||
},
|
||||
original: {
|
||||
key: assetKey,
|
||||
filesizeInBytes: 0,
|
||||
codec: '',
|
||||
},
|
||||
}
|
||||
|
||||
if (isImage) {
|
||||
const originalTranscodes = originalMedia?.imageTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
for (let i = 0; i < originalTranscodes.length; i++) {
|
||||
const it = originalTranscodes[i]
|
||||
const targetWidth = it.width || originalWidth
|
||||
const targetHeight = it.height || originalHeight
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${targetWidth}x${targetHeight}.webp`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.compositeOverlayToWebpFile(
|
||||
rawFilePath,
|
||||
overlayPngBuffer,
|
||||
outFilePath,
|
||||
targetWidth,
|
||||
targetHeight,
|
||||
)
|
||||
|
||||
const stat = fs.statSync(outFilePath)
|
||||
totalSize += stat.size
|
||||
const outputKey = path.posix.join(path.posix.dirname(assetKey), outFileName)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
outputKey,
|
||||
Bun.file(outFilePath).stream(),
|
||||
stat.size,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
mediaInfo.imageTranscodes.push({
|
||||
key: outputKey,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
quality: it.quality ?? 90,
|
||||
format: it.format ?? 'webp',
|
||||
})
|
||||
}
|
||||
mediaInfo.filesize = totalSize
|
||||
} else if (isVideo || is3d) {
|
||||
const originalTranscodes = originalMedia?.videoTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
for (let i = 0; i < originalTranscodes.length; i++) {
|
||||
const vt = originalTranscodes[i]
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const resolution = vt.resolution || `${targetHeight}p`
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
const suffix = isVtHdr ? `${resolution}-hdr` : resolution
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-${i}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${suffix}.mp4`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: rawFilePath,
|
||||
outputFile: outFilePath,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
disableAudio: !hasAudio,
|
||||
overlayFile: overlayPngPath,
|
||||
hardwareAcceleration,
|
||||
sourceVideoBitrate,
|
||||
threads,
|
||||
hdr: isVtHdr,
|
||||
sourceIsHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
sourceHdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
sourceColorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
sourceColorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
streamIndex: originalMedia?.metadata?.videoStreamIndex,
|
||||
audioStreamIndex: originalMedia?.metadata?.audioStreamIndex,
|
||||
})
|
||||
|
||||
const stat = fs.statSync(outFilePath)
|
||||
totalSize += stat.size
|
||||
const outputKey = path.posix.join(path.posix.dirname(assetKey), outFileName)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
outputKey,
|
||||
Bun.file(outFilePath).stream(),
|
||||
stat.size,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
mediaInfo.videoTranscodes.push({
|
||||
key: outputKey,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
resolution,
|
||||
hdr: isVtHdr,
|
||||
if (!isVideo && !isImage && !is3d) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset ${params.assetId} is neither video nor image`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (is3d && mediaInfo.videoTranscodes.length > 0) {
|
||||
mediaInfo.videoPreview = {
|
||||
key: mediaInfo.videoTranscodes[0].key,
|
||||
width: mediaInfo.videoTranscodes[0].width,
|
||||
height: mediaInfo.videoTranscodes[0].height,
|
||||
resolution: mediaInfo.videoTranscodes[0].resolution,
|
||||
const inputKey = is3d
|
||||
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
|
||||
: assetKey
|
||||
|
||||
if (is3d && !inputKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
|
||||
await s3Service.downloadToFile(bucket, inputKey!, rawFilePath)
|
||||
|
||||
let originalWidth = 1920
|
||||
let originalHeight = 1080
|
||||
let duration = 0
|
||||
let bitRate = 0
|
||||
let videoBitRate: number | undefined
|
||||
let frameRate = 30
|
||||
let totalFrames = 0
|
||||
let startTimecode = '00:00:00:00'
|
||||
let hasAudio = false
|
||||
let sourceVideoBitrate: number | undefined
|
||||
let colorTransfer: string | undefined
|
||||
let colorPrimaries: string | undefined
|
||||
let colorSpace: string | undefined
|
||||
let isHdr: boolean | undefined
|
||||
let hdrType: PrismaJson.HdrType | undefined
|
||||
let dvProfile: number | undefined
|
||||
|
||||
if (isVideo || is3d) {
|
||||
const info = await transcodeService.getVideoInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
duration = info.duration
|
||||
bitRate = info.bitRate
|
||||
videoBitRate = info.videoBitRate
|
||||
frameRate = info.frameRate
|
||||
totalFrames = info.totalFrames
|
||||
startTimecode = info.startTimecode || '00:00:00:00'
|
||||
hasAudio = info.hasAudio
|
||||
sourceVideoBitrate = info.videoBitRate || info.bitRate
|
||||
colorTransfer = info.colorTransfer
|
||||
colorPrimaries = info.colorPrimaries
|
||||
colorSpace = info.colorSpace
|
||||
isHdr = info.isHdr
|
||||
hdrType = info.hdrType
|
||||
dvProfile = info.dvProfile
|
||||
} else if (isImage) {
|
||||
const info = await transcodeService.getImageInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
}
|
||||
|
||||
// Process image blocks if any
|
||||
const blockImagesMap = new Map<string, RenderBlockImageData>()
|
||||
const imageBlocks = (config.blocks || []).filter(
|
||||
(b) => b.type === 'image',
|
||||
) as WatermarkBlockImage[]
|
||||
|
||||
for (const imgBlock of imageBlocks) {
|
||||
if (!imgBlock.imageAssetKey) continue
|
||||
try {
|
||||
const imgTmpPath = path.join(tmpDir, `block-${ulid()}`)
|
||||
await s3Service.downloadToFile(bucket, imgBlock.imageAssetKey, imgTmpPath)
|
||||
const buffer = fs.readFileSync(imgTmpPath)
|
||||
// Downscale to a bounded size and normalize to PNG so large logo assets
|
||||
// don't balloon the SVG/base64 payload.
|
||||
const processed = await transcodeService.downscaleImageToPng(
|
||||
buffer,
|
||||
MAX_BLOCK_IMAGE_DIMENSION,
|
||||
)
|
||||
blockImagesMap.set(imgBlock.imageAssetKey, {
|
||||
imageAssetKey: imgBlock.imageAssetKey,
|
||||
base64Data: processed.buffer.toString('base64'),
|
||||
mimeType: 'image/png',
|
||||
width: processed.width,
|
||||
height: processed.height,
|
||||
})
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ imageAssetKey: imgBlock.imageAssetKey, err },
|
||||
'Failed to load watermark block image',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (originalMedia?.isHls && originalMedia?.hls?.resolutions?.length) {
|
||||
const hlsWatermarkDirKey = path.posix.join(
|
||||
path.posix.dirname(assetKey),
|
||||
`hls-watermark-${params.watermarkConfigId}`,
|
||||
)
|
||||
const masterKey = path.posix.join(hlsWatermarkDirKey, 'master.m3u8')
|
||||
const hlsTmpDir = path.join(tmpDir, `hls-watermark-${params.watermarkConfigId}`)
|
||||
fs.mkdirSync(hlsTmpDir, { recursive: true })
|
||||
const originalMedia = asset.media as PrismaJson.MediaInfo | null
|
||||
|
||||
const renditionSpecs: Array<{
|
||||
resolution: string
|
||||
width: number
|
||||
height: number
|
||||
bitrateBps: number
|
||||
isHdr?: boolean
|
||||
}> = []
|
||||
const hlsResolutions: PrismaJson.VideoTranscode[] = []
|
||||
const mediaInfo: PrismaJson.MediaInfo = {
|
||||
duration,
|
||||
filesize: 0,
|
||||
frames: totalFrames,
|
||||
proxyType: is3d ? '3d' : isVideo ? 'video' : 'image',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
poster: originalMedia?.poster,
|
||||
sprite: originalMedia?.sprite,
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth,
|
||||
originalHeight,
|
||||
duration,
|
||||
bitRate,
|
||||
videoBitRate,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
startTimecode,
|
||||
hasAudio,
|
||||
colorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
colorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
colorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
isHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
hdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
dvProfile: dvProfile ?? originalMedia?.metadata?.dvProfile,
|
||||
format: originalMedia?.metadata?.format ?? {},
|
||||
},
|
||||
original: {
|
||||
key: assetKey,
|
||||
filesizeInBytes: 0,
|
||||
codec: '',
|
||||
},
|
||||
}
|
||||
|
||||
for (const vt of originalMedia.hls.resolutions) {
|
||||
const ladder = vt.resolution || `${vt.height}p`
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
if (isImage) {
|
||||
const originalTranscodes = originalMedia?.imageTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
for (let i = 0; i < originalTranscodes.length; i++) {
|
||||
const it = originalTranscodes[i]
|
||||
const targetWidth = it.width || originalWidth
|
||||
const targetHeight = it.height || originalHeight
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-hls-${ladder}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const ladderDir = path.join(hlsTmpDir, ladder)
|
||||
await transcodeService.transcodeHlsRendition({
|
||||
inputFile: rawFilePath,
|
||||
outputDir: ladderDir,
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${targetWidth}x${targetHeight}.webp`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.compositeOverlayToWebpFile(
|
||||
rawFilePath,
|
||||
overlayPngBuffer,
|
||||
outFilePath,
|
||||
targetWidth,
|
||||
targetHeight,
|
||||
)
|
||||
|
||||
const stat = fs.statSync(outFilePath)
|
||||
totalSize += stat.size
|
||||
const outputKey = path.posix.join(path.posix.dirname(assetKey), outFileName)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
outputKey,
|
||||
Bun.file(outFilePath).stream(),
|
||||
stat.size,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
mediaInfo.imageTranscodes.push({
|
||||
key: outputKey,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
quality: it.quality ?? 90,
|
||||
format: it.format ?? 'webp',
|
||||
})
|
||||
}
|
||||
mediaInfo.filesize = totalSize
|
||||
} else if (isVideo || is3d) {
|
||||
const originalTranscodes = originalMedia?.videoTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
for (let i = 0; i < originalTranscodes.length; i++) {
|
||||
const vt = originalTranscodes[i]
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const resolution = vt.resolution || `${targetHeight}p`
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
const suffix = isVtHdr ? `${resolution}-hdr` : resolution
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-${i}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${suffix}.mp4`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: rawFilePath,
|
||||
outputFile: outFilePath,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
disableAudio: !hasAudio,
|
||||
overlayFile: overlayPngPath,
|
||||
frameRate,
|
||||
hardwareAcceleration,
|
||||
sourceVideoBitrate,
|
||||
threads,
|
||||
hdr: isVtHdr,
|
||||
disableAudio: !hasAudio,
|
||||
sourceIsHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
sourceHdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
@@ -474,82 +394,169 @@ export async function transcodeWatermarkMediaActivity(
|
||||
audioStreamIndex: originalMedia?.metadata?.audioStreamIndex,
|
||||
})
|
||||
|
||||
const targetBps = calculateEffectiveBitrateBps(
|
||||
targetHeight,
|
||||
targetWidth,
|
||||
sourceVideoBitrate,
|
||||
frameRate,
|
||||
const stat = fs.statSync(outFilePath)
|
||||
totalSize += stat.size
|
||||
const outputKey = path.posix.join(path.posix.dirname(assetKey), outFileName)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
outputKey,
|
||||
Bun.file(outFilePath).stream(),
|
||||
stat.size,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
renditionSpecs.push({
|
||||
resolution: ladder,
|
||||
mediaInfo.videoTranscodes.push({
|
||||
key: outputKey,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
bitrateBps: targetBps,
|
||||
isHdr: isVtHdr,
|
||||
})
|
||||
|
||||
const ladderFiles = fs.readdirSync(ladderDir)
|
||||
for (const file of ladderFiles) {
|
||||
const filePath = path.join(ladderDir, file)
|
||||
const stat = fs.statSync(filePath)
|
||||
totalSize += stat.size
|
||||
const contentType = file.endsWith('.m3u8')
|
||||
? 'application/vnd.apple.mpegurl'
|
||||
: file.endsWith('.m4s')
|
||||
? 'video/iso.segment'
|
||||
: 'video/mp4'
|
||||
const s3Key = path.posix.join(hlsWatermarkDirKey, ladder, file)
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
s3Key,
|
||||
Bun.file(filePath).stream(),
|
||||
stat.size,
|
||||
contentType,
|
||||
)
|
||||
}
|
||||
|
||||
hlsResolutions.push({
|
||||
key: path.posix.join(hlsWatermarkDirKey, ladder, 'index.m3u8'),
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
resolution: ladder,
|
||||
resolution,
|
||||
hdr: isVtHdr,
|
||||
})
|
||||
}
|
||||
|
||||
const masterM3u8Content = buildHlsMasterPlaylist(renditionSpecs)
|
||||
const masterM3u8Buffer = Buffer.from(masterM3u8Content, 'utf-8')
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
masterKey,
|
||||
masterM3u8Buffer,
|
||||
masterM3u8Buffer.length,
|
||||
'application/vnd.apple.mpegurl',
|
||||
)
|
||||
|
||||
mediaInfo.isHls = true
|
||||
mediaInfo.hls = {
|
||||
key: masterKey,
|
||||
resolutions: hlsResolutions,
|
||||
if (is3d && mediaInfo.videoTranscodes.length > 0) {
|
||||
mediaInfo.videoPreview = {
|
||||
key: mediaInfo.videoTranscodes[0].key,
|
||||
width: mediaInfo.videoTranscodes[0].width,
|
||||
height: mediaInfo.videoTranscodes[0].height,
|
||||
resolution: mediaInfo.videoTranscodes[0].resolution,
|
||||
}
|
||||
}
|
||||
|
||||
if (originalMedia?.isHls && originalMedia?.hls?.resolutions?.length) {
|
||||
const hlsWatermarkDirKey = path.posix.join(
|
||||
path.posix.dirname(assetKey),
|
||||
`hls-watermark-${params.watermarkConfigId}`,
|
||||
)
|
||||
const masterKey = path.posix.join(hlsWatermarkDirKey, 'master.m3u8')
|
||||
const hlsTmpDir = path.join(tmpDir, `hls-watermark-${params.watermarkConfigId}`)
|
||||
fs.mkdirSync(hlsTmpDir, { recursive: true })
|
||||
|
||||
const renditionSpecs: Array<{
|
||||
resolution: string
|
||||
width: number
|
||||
height: number
|
||||
bitrateBps: number
|
||||
isHdr?: boolean
|
||||
}> = []
|
||||
const hlsResolutions: PrismaJson.VideoTranscode[] = []
|
||||
|
||||
for (const vt of originalMedia.hls.resolutions) {
|
||||
const ladder = vt.resolution || `${vt.height}p`
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
|
||||
const svgString = generateWatermarkSvg(
|
||||
config,
|
||||
targetWidth,
|
||||
targetHeight,
|
||||
blockImagesMap,
|
||||
)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-hls-${ladder}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const ladderDir = path.join(hlsTmpDir, ladder)
|
||||
await transcodeService.transcodeHlsRendition({
|
||||
inputFile: rawFilePath,
|
||||
outputDir: ladderDir,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
overlayFile: overlayPngPath,
|
||||
frameRate,
|
||||
hardwareAcceleration,
|
||||
sourceVideoBitrate,
|
||||
threads,
|
||||
hdr: isVtHdr,
|
||||
disableAudio: !hasAudio,
|
||||
sourceIsHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
sourceHdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
sourceColorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
sourceColorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
streamIndex: originalMedia?.metadata?.videoStreamIndex,
|
||||
audioStreamIndex: originalMedia?.metadata?.audioStreamIndex,
|
||||
})
|
||||
|
||||
const targetBps = calculateEffectiveBitrateBps(
|
||||
targetHeight,
|
||||
targetWidth,
|
||||
sourceVideoBitrate,
|
||||
frameRate,
|
||||
)
|
||||
|
||||
renditionSpecs.push({
|
||||
resolution: ladder,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
bitrateBps: targetBps,
|
||||
isHdr: isVtHdr,
|
||||
})
|
||||
|
||||
const ladderFiles = fs.readdirSync(ladderDir)
|
||||
for (const file of ladderFiles) {
|
||||
const filePath = path.join(ladderDir, file)
|
||||
const stat = fs.statSync(filePath)
|
||||
totalSize += stat.size
|
||||
const contentType = file.endsWith('.m3u8')
|
||||
? 'application/vnd.apple.mpegurl'
|
||||
: file.endsWith('.m4s')
|
||||
? 'video/iso.segment'
|
||||
: 'video/mp4'
|
||||
const s3Key = path.posix.join(hlsWatermarkDirKey, ladder, file)
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
s3Key,
|
||||
Bun.file(filePath).stream(),
|
||||
stat.size,
|
||||
contentType,
|
||||
)
|
||||
}
|
||||
|
||||
hlsResolutions.push({
|
||||
key: path.posix.join(hlsWatermarkDirKey, ladder, 'index.m3u8'),
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
resolution: ladder,
|
||||
hdr: isVtHdr,
|
||||
})
|
||||
}
|
||||
|
||||
const masterM3u8Content = buildHlsMasterPlaylist(renditionSpecs)
|
||||
const masterM3u8Buffer = Buffer.from(masterM3u8Content, 'utf-8')
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
masterKey,
|
||||
masterM3u8Buffer,
|
||||
masterM3u8Buffer.length,
|
||||
'application/vnd.apple.mpegurl',
|
||||
)
|
||||
|
||||
mediaInfo.isHls = true
|
||||
mediaInfo.hls = {
|
||||
key: masterKey,
|
||||
resolutions: hlsResolutions,
|
||||
}
|
||||
}
|
||||
|
||||
mediaInfo.filesize = totalSize
|
||||
}
|
||||
|
||||
mediaInfo.filesize = totalSize
|
||||
return mediaInfo
|
||||
} catch (err) {
|
||||
logger.error({ assetId: params.assetId, err }, 'Failed to generate watermark proxy')
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate watermark proxy: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
} finally {
|
||||
transcodeService.removeDir(tmpDir)
|
||||
}
|
||||
|
||||
return mediaInfo
|
||||
} catch (err) {
|
||||
logger.error({ assetId: params.assetId, err }, 'Failed to generate watermark proxy')
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate watermark proxy: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
} finally {
|
||||
transcodeService.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export interface CompleteWatermarkFileParams {
|
||||
assetId: string
|
||||
@@ -559,30 +566,31 @@ export interface CompleteWatermarkFileParams {
|
||||
shareLinkId?: string | null
|
||||
}
|
||||
|
||||
export async function completeWatermarkFileActivity(
|
||||
params: CompleteWatermarkFileParams,
|
||||
): Promise<void> {
|
||||
await prisma.watermarkFile.upsert({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_watermarkConfigId: {
|
||||
export const completeWatermarkFileActivity = defineStep(
|
||||
async function completeWatermarkFileActivity(params: CompleteWatermarkFileParams): Promise<void> {
|
||||
await prisma.watermarkFile.upsert({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_watermarkConfigId: {
|
||||
assetId: params.assetId,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
assetId: params.assetId,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
media: params.mediaInfo ?? undefined,
|
||||
status: params.status,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
assetId: params.assetId,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
media: params.mediaInfo ?? undefined,
|
||||
status: params.status,
|
||||
},
|
||||
update: {
|
||||
media: params.mediaInfo ?? undefined,
|
||||
status: params.status,
|
||||
},
|
||||
})
|
||||
update: {
|
||||
media: params.mediaInfo ?? undefined,
|
||||
status: params.status,
|
||||
},
|
||||
})
|
||||
|
||||
if (params.shareLinkId) {
|
||||
await watermarkService.checkAndUpdateShareLinkStatus(params.shareLinkId)
|
||||
}
|
||||
}
|
||||
if (params.shareLinkId) {
|
||||
await watermarkService.checkAndUpdateShareLinkStatus(params.shareLinkId)
|
||||
}
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { WorkflowTaskType } from '@shumai/db'
|
||||
import { registerActivities, registerWorkflow } from '@shumai/workflow-core'
|
||||
import * as transcodeActivities from './activities/transcode'
|
||||
import * as watermarkActivities from './activities/watermark'
|
||||
import { registerWorkflow } from '@shumai/workflow-core'
|
||||
import { transcodeVideoWorkflow } from './workflows/transcode-video'
|
||||
import { transcodeImageWorkflow } from './workflows/transcode-image'
|
||||
import { transcodePdfWorkflow } from './workflows/transcode-pdf'
|
||||
@@ -22,8 +20,6 @@ export function initTranscodeWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_watermark, transcodeWatermarkWorkflow)
|
||||
registerActivities(transcodeActivities)
|
||||
registerActivities(watermarkActivities)
|
||||
}
|
||||
|
||||
export * from './transcoder'
|
||||
|
||||
@@ -1,23 +1,31 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
executeActivity,
|
||||
getActivities,
|
||||
TaskQueueTranscode,
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import { cleanupTmpDirActivity } from '../activities/transcode'
|
||||
|
||||
export async function getWorkerQueueAndStartTask(task: WorkflowTask): Promise<string> {
|
||||
const { updateTaskStatusActivity } = getActivities()
|
||||
await executeActivity(TaskQueueTranscode, updateTaskStatusActivity, {
|
||||
export async function startTask(task: WorkflowTask): Promise<void> {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
return TaskQueueTranscode
|
||||
}
|
||||
|
||||
export async function fetchAssetWithKey(workerQueue: string, assetId: string) {
|
||||
const { getAssetActivity } = getActivities()
|
||||
const asset = await executeActivity(workerQueue, getAssetActivity, assetId)
|
||||
/**
|
||||
* @deprecated Use `startTask(task)` instead.
|
||||
*/
|
||||
export async function getWorkerQueueAndStartTask(task: WorkflowTask): Promise<string> {
|
||||
await startTask(task)
|
||||
return ''
|
||||
}
|
||||
|
||||
export async function fetchAssetWithKey(
|
||||
assetId: string,
|
||||
): Promise<{ asset: NonNullable<Awaited<ReturnType<typeof getAssetActivity>>>; key: string }> {
|
||||
const asset = await getAssetActivity(assetId)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key || asset.status === 'pending_purge') {
|
||||
throw ApplicationFailure.create({
|
||||
@@ -28,52 +36,38 @@ export async function fetchAssetWithKey(workerQueue: string, assetId: string) {
|
||||
return { asset, key }
|
||||
}
|
||||
|
||||
export async function completeTask(
|
||||
workerQueue: string,
|
||||
taskId: string,
|
||||
output?: Record<string, unknown>,
|
||||
) {
|
||||
const { updateTaskStatusActivity } = getActivities()
|
||||
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||
export async function completeTask(taskId: string, output?: Record<string, unknown>) {
|
||||
await updateTaskStatusActivity({
|
||||
taskId,
|
||||
status: 'completed',
|
||||
...(output ? { output } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export async function failTask(
|
||||
workerQueue: string,
|
||||
taskId: string,
|
||||
err: unknown,
|
||||
assetId?: string,
|
||||
) {
|
||||
const { updateTaskStatusActivity, updateAssetStatusActivity } = getActivities()
|
||||
if (workerQueue) {
|
||||
const errorMsg = err instanceof Error ? err.message : String(err)
|
||||
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||
taskId,
|
||||
status: 'failed',
|
||||
output: { error: errorMsg },
|
||||
})
|
||||
if (assetId) {
|
||||
try {
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
assetId,
|
||||
status: 'failed',
|
||||
error: errorMsg,
|
||||
})
|
||||
} catch (assetErr) {
|
||||
console.error('Failed to update asset status to failed:', assetErr)
|
||||
}
|
||||
export async function failTask(taskId: string, err: unknown, assetId?: string) {
|
||||
const errorMsg = err instanceof Error ? err.message : String(err)
|
||||
await updateTaskStatusActivity({
|
||||
taskId,
|
||||
status: 'failed',
|
||||
output: { error: errorMsg },
|
||||
})
|
||||
if (assetId) {
|
||||
try {
|
||||
await updateAssetStatusActivity({
|
||||
assetId,
|
||||
status: 'failed',
|
||||
error: errorMsg,
|
||||
})
|
||||
} catch (assetErr) {
|
||||
console.error('Failed to update asset status to failed:', assetErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanupTmpDir(workerQueue: string, tmpDir: string | undefined) {
|
||||
if (tmpDir && workerQueue) {
|
||||
const { cleanupTmpDirActivity } = getActivities()
|
||||
export async function cleanupTmpDir(tmpDir: string | undefined) {
|
||||
if (tmpDir) {
|
||||
try {
|
||||
await executeActivity(workerQueue, cleanupTmpDirActivity, { tmpDir })
|
||||
await cleanupTmpDirActivity({ tmpDir })
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup tmp dir:', cleanupErr)
|
||||
}
|
||||
|
||||
@@ -1,49 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { overlayImageAnnotationWorkflow } from './overlay-image-annotation'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
|
||||
import { overlayAnnotationsActivity } from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
overlayAnnotationsActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('overlayImageAnnotationWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
overlayAnnotationsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'overlayAnnotationsActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
overlayAnnotationsActivity: vi.mocked(overlayAnnotationsActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
})
|
||||
|
||||
it('should run image annotation overlay workflow successfully', async () => {
|
||||
@@ -78,7 +60,8 @@ describe('overlayImageAnnotationWorkflow', () => {
|
||||
media: {
|
||||
imageTranscodes: [{ key: 'image-transcoded.webp' }],
|
||||
},
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.overlayAnnotationsActivity.mockResolvedValue(
|
||||
'files/asset-image/annotations/ann1.webp',
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { getWorkerQueueAndStartTask, completeTask, failTask } from './common'
|
||||
import { ApplicationFailure, getAssetActivity } from '@shumai/workflow-core'
|
||||
import { overlayAnnotationsActivity } from '../activities/transcode'
|
||||
import { startTask, completeTask, failTask } from './common'
|
||||
|
||||
export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let workerQueue = ''
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload?.imageAnnotation) {
|
||||
@@ -16,8 +16,7 @@ export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promis
|
||||
})
|
||||
}
|
||||
|
||||
const { getAssetActivity, overlayAnnotationsActivity } = getActivities()
|
||||
const asset = await executeActivity(workerQueue, getAssetActivity, task.assetId)
|
||||
const asset = await getAssetActivity(task.assetId)
|
||||
let key = asset?.storageKey?.key
|
||||
if (asset?.media) {
|
||||
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
|
||||
@@ -33,16 +32,16 @@ export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promis
|
||||
})
|
||||
}
|
||||
|
||||
const keyWithOverlay = await executeActivity(workerQueue, overlayAnnotationsActivity, {
|
||||
const keyWithOverlay = await overlayAnnotationsActivity({
|
||||
assetKey: key,
|
||||
assetId: asset.id,
|
||||
annotations: payload.imageAnnotation.annotations,
|
||||
annotations: payload.imageAnnotation.annotations || [],
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id, { key: keyWithOverlay })
|
||||
await completeTask(task.id, { key: keyWithOverlay })
|
||||
} catch (err) {
|
||||
console.error(`overlayImageAnnotationWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err)
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderPdfPagesWorkflow } from './render-pdf-pages'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
|
||||
import { renderPdfPagesActivity } from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
renderPdfPagesActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('renderPdfPagesWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
renderPdfPagesActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'renderPdfPagesActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
renderPdfPagesActivity: vi.mocked(renderPdfPagesActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
})
|
||||
|
||||
it('should run renderPdfPagesWorkflow successfully', async () => {
|
||||
@@ -78,7 +60,8 @@ describe('renderPdfPagesWorkflow', () => {
|
||||
id: 'asset-pdf',
|
||||
storageKey: { key: 'doc.pdf' },
|
||||
mediaType: 'application/pdf',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.renderPdfPagesActivity.mockResolvedValue([
|
||||
{ key: 'pdf_pages/doc-page-1.webp', page: 1 },
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { getWorkerQueueAndStartTask, fetchAssetWithKey, completeTask, failTask } from './common'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { renderPdfPagesActivity } from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask } from './common'
|
||||
|
||||
export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let workerQueue = ''
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload?.pdfPages) {
|
||||
@@ -15,11 +15,10 @@ export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void>
|
||||
})
|
||||
}
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { renderPdfPagesActivity } = getActivities()
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
const pdfKey = (asset.media as PrismaJson.MediaInfo | null)?.pdfTranscode?.key || key
|
||||
|
||||
const pages = await executeActivity(workerQueue, renderPdfPagesActivity, {
|
||||
const pages = await renderPdfPagesActivity({
|
||||
taskId: task.id,
|
||||
assetKey: pdfKey,
|
||||
assetId: asset.id,
|
||||
@@ -29,10 +28,10 @@ export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void>
|
||||
annotations: payload.pdfPages.annotations,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id, { pages })
|
||||
await completeTask(task.id, { pages })
|
||||
} catch (err) {
|
||||
console.error(`renderPdfPagesWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err)
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { takeVideoScreenshotsWorkflow } from './take-video-screenshots'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
|
||||
import { takeScreenshotsActivity } from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
takeScreenshotsActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('takeVideoScreenshotsWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
takeScreenshotsActivity: Object.assign(vi.fn(), { _activityName: 'takeScreenshotsActivity' }),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
takeScreenshotsActivity: vi.mocked(takeScreenshotsActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
})
|
||||
|
||||
it('should run screenshot workflow successfully', async () => {
|
||||
@@ -77,7 +61,8 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
id: 'asset-video',
|
||||
storageKey: { key: 'video.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.takeScreenshotsActivity.mockResolvedValue([
|
||||
{ key: 'files/asset-video/screenshots/shot1.webp', timestamp: 0.0 },
|
||||
@@ -149,7 +134,8 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
{ key: 'proxy-360p.mp4', height: 360, width: 640 },
|
||||
],
|
||||
},
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.takeScreenshotsActivity.mockResolvedValue([
|
||||
{ key: 'files/asset-video-proxy/screenshots/shot1.webp', timestamp: 1.2345 },
|
||||
@@ -208,7 +194,8 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
{ key: 'proxy-720p.mp4', height: 720, width: 1280, hdr: false },
|
||||
],
|
||||
},
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.takeScreenshotsActivity.mockResolvedValue([
|
||||
{ key: 'files/asset-video-hdr/screenshots/shot1.webp', timestamp: 2.0 },
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { getWorkerQueueAndStartTask, fetchAssetWithKey, completeTask, failTask } from './common'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { takeScreenshotsActivity } from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask } from './common'
|
||||
|
||||
export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let workerQueue = ''
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload?.screenshot) {
|
||||
@@ -15,7 +15,7 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
})
|
||||
}
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
let targetKey = key
|
||||
if (asset?.media) {
|
||||
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
|
||||
@@ -34,9 +34,7 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
const { takeScreenshotsActivity } = getActivities()
|
||||
|
||||
const screenshots = await executeActivity(workerQueue, takeScreenshotsActivity, {
|
||||
const screenshots = await takeScreenshotsActivity({
|
||||
taskId: task.id,
|
||||
assetKey: targetKey,
|
||||
assetId: asset.id,
|
||||
@@ -47,10 +45,10 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
annotations: payload.screenshot.annotations,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id, { screenshots })
|
||||
await completeTask(task.id, { screenshots })
|
||||
} catch (err) {
|
||||
console.error(`takeVideoScreenshotsWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err)
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,69 +1,63 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcode3dWorkflow } from './transcode-3d'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
downloadMediaToTmpActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
generate3dSpriteActivity,
|
||||
generate3dViewsActivity,
|
||||
updateAssetMediaActivity,
|
||||
cleanupTmpDirActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
start3dRenderActivity: vi.fn(),
|
||||
waitFor3dVideoRenderActivity: vi.fn(),
|
||||
generate3dSpriteActivity: vi.fn(),
|
||||
generate3dViewsActivity: vi.fn(),
|
||||
updateAssetMediaActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.fn(),
|
||||
createAutofillTaskIfEnabledActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcode3dWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
render3dModelActivity: Object.assign(vi.fn(), { _activityName: 'render3dModelActivity' }),
|
||||
start3dRenderActivity: Object.assign(vi.fn(), { _activityName: 'start3dRenderActivity' }),
|
||||
waitFor3dVideoRenderActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'waitFor3dVideoRenderActivity',
|
||||
}),
|
||||
generate3dSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generate3dSpriteActivity' }),
|
||||
generate3dViewsActivity: Object.assign(vi.fn(), { _activityName: 'generate3dViewsActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
start3dRenderActivity: vi.mocked(start3dRenderActivity),
|
||||
waitFor3dVideoRenderActivity: vi.mocked(waitFor3dVideoRenderActivity),
|
||||
generate3dSpriteActivity: vi.mocked(generate3dSpriteActivity),
|
||||
generate3dViewsActivity: vi.mocked(generate3dViewsActivity),
|
||||
updateAssetMediaActivity: vi.mocked(updateAssetMediaActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
cleanupTmpDirActivity: vi.mocked(cleanupTmpDirActivity),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.mocked(createEmbeddingTaskIfEnabledActivity),
|
||||
createAutofillTaskIfEnabledActivity: vi.mocked(createAutofillTaskIfEnabledActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/model.glb',
|
||||
tmpDir: '/tmp',
|
||||
@@ -102,7 +96,8 @@ describe('transcode3dWorkflow', () => {
|
||||
storageKey: { key: 'files/asset-3d/robot.glb' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
sizeByte: BigInt(1024),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.start3dRenderActivity.mockResolvedValue({
|
||||
renderTaskId: 'task_render_1',
|
||||
@@ -248,7 +243,8 @@ describe('transcode3dWorkflow', () => {
|
||||
storageKey: { key: 'files/corrupt.glb' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
sizeByte: BigInt(512),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.start3dRenderActivity.mockRejectedValue(new Error('Renderer crashed'))
|
||||
|
||||
|
||||
@@ -1,42 +1,33 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import { updateAssetStatusActivity } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
downloadMediaToTmpActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
generate3dSpriteActivity,
|
||||
generate3dViewsActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
|
||||
|
||||
export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
generate3dSpriteActivity,
|
||||
generate3dViewsActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
const download = await downloadMediaToTmpActivity({
|
||||
assetKey: key,
|
||||
})
|
||||
const currentFilePath = download.filePath
|
||||
@@ -49,9 +40,9 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
const spriteKey = assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp'
|
||||
const viewsKey = assetDir ? `${assetDir}/views.webp` : 'views.webp'
|
||||
|
||||
const renderStart = await executeActivity(workerQueue, start3dRenderActivity, {
|
||||
const renderStart = await start3dRenderActivity({
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
teamId: task.teamId || '',
|
||||
assetId: asset.id,
|
||||
assetKey: key,
|
||||
filePath: currentFilePath,
|
||||
@@ -91,21 +82,21 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
},
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
const renderVideo = await executeActivity(workerQueue, waitFor3dVideoRenderActivity, {
|
||||
const renderVideo = await waitFor3dVideoRenderActivity({
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
teamId: task.teamId || '',
|
||||
assetKey: key,
|
||||
renderTaskId: renderStart.renderTaskId,
|
||||
targetVideoKey: videoKey,
|
||||
tmpDir,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, generate3dSpriteActivity, {
|
||||
await generate3dSpriteActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
videoFilePath: renderVideo.videoFilePath,
|
||||
@@ -119,7 +110,7 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
tileY: 10,
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, generate3dViewsActivity, {
|
||||
await generate3dViewsActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
videoFilePath: renderVideo.videoFilePath,
|
||||
@@ -136,7 +127,7 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
},
|
||||
]
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
@@ -157,35 +148,35 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
mediaInfo.finishedAt = new Date().toISOString()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcode3dWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
await cleanupTmpDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,64 +1,57 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodeImageWorkflow } from './transcode-image'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
downloadMediaToTmpActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeImageActivity,
|
||||
updateAssetMediaActivity,
|
||||
cleanupTmpDirActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
getMediaInfoActivity: vi.fn(),
|
||||
transcodeImageActivity: vi.fn(),
|
||||
updateAssetMediaActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.fn(),
|
||||
createAutofillTaskIfEnabledActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcodeImageWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }),
|
||||
transcodeImageActivity: Object.assign(vi.fn(), { _activityName: 'transcodeImageActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
getMediaInfoActivity: vi.mocked(getMediaInfoActivity),
|
||||
transcodeImageActivity: vi.mocked(transcodeImageActivity),
|
||||
updateAssetMediaActivity: vi.mocked(updateAssetMediaActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
cleanupTmpDirActivity: vi.mocked(cleanupTmpDirActivity),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.mocked(createEmbeddingTaskIfEnabledActivity),
|
||||
createAutofillTaskIfEnabledActivity: vi.mocked(createAutofillTaskIfEnabledActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/image.jpg',
|
||||
tmpDir: '/tmp',
|
||||
@@ -94,7 +87,8 @@ describe('transcodeImageWorkflow', () => {
|
||||
id: 'asset-image',
|
||||
storageKey: { key: 'image.jpg' },
|
||||
mediaType: 'image/jpeg',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
proxyType: 'image',
|
||||
@@ -111,12 +105,14 @@ describe('transcodeImageWorkflow', () => {
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.transcodeImageActivity.mockResolvedValue({
|
||||
key: 't.webp',
|
||||
width: 300,
|
||||
height: 300,
|
||||
quality: 80,
|
||||
format: 'webp',
|
||||
})
|
||||
|
||||
@@ -185,7 +181,8 @@ describe('transcodeImageWorkflow', () => {
|
||||
id: 'asset-raw',
|
||||
storageKey: { key: 'photo.cr2' },
|
||||
mediaType: 'image/x-canon-cr2',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
// RAW file without usable preview returns originalWidth: 0, originalHeight: 0
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
@@ -203,7 +200,8 @@ describe('transcodeImageWorkflow', () => {
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
await transcodeImageWorkflow(task)
|
||||
|
||||
|
||||
@@ -1,47 +1,38 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import { updateAssetStatusActivity } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
downloadMediaToTmpActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeImageActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
|
||||
|
||||
export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeImageActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
const download = await downloadMediaToTmpActivity({
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const spec = task.payload?.transcode || {}
|
||||
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
|
||||
const mediaInfo = await getMediaInfoActivity({
|
||||
filePath,
|
||||
assetId: asset.id,
|
||||
proxyType: 'image',
|
||||
@@ -65,7 +56,7 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
|
||||
quality: 90,
|
||||
format: 'webp',
|
||||
}
|
||||
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
const imageTranscode = await transcodeImageActivity({
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec,
|
||||
@@ -74,7 +65,7 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
|
||||
}
|
||||
|
||||
if (spec.thumbnail && hasUsablePreview) {
|
||||
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
const thumbTranscode = await transcodeImageActivity({
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec: { width: 300, height: 300, quality: 80, format: 'webp', isPreview: true },
|
||||
@@ -82,35 +73,35 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
|
||||
mediaInfo.thumbnail = thumbTranscode
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcodeImageWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
await cleanupTmpDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,67 +1,60 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodePdfWorkflow } from './transcode-pdf'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
downloadMediaToTmpActivity,
|
||||
generatePdfProxyActivity,
|
||||
getMediaInfoActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
cleanupTmpDirActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
generatePdfProxyActivity: vi.fn(),
|
||||
getMediaInfoActivity: vi.fn(),
|
||||
generateSpriteActivity: vi.fn(),
|
||||
updateAssetMediaActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.fn(),
|
||||
createAutofillTaskIfEnabledActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcodePdfWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }),
|
||||
generateSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generateSpriteActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
generatePdfProxyActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generatePdfProxyActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
getMediaInfoActivity: vi.mocked(getMediaInfoActivity),
|
||||
generateSpriteActivity: vi.mocked(generateSpriteActivity),
|
||||
updateAssetMediaActivity: vi.mocked(updateAssetMediaActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
generatePdfProxyActivity: vi.mocked(generatePdfProxyActivity),
|
||||
cleanupTmpDirActivity: vi.mocked(cleanupTmpDirActivity),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.mocked(createEmbeddingTaskIfEnabledActivity),
|
||||
createAutofillTaskIfEnabledActivity: vi.mocked(createAutofillTaskIfEnabledActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/doc.pdf',
|
||||
tmpDir: '/tmp',
|
||||
@@ -102,7 +95,8 @@ describe('transcodePdfWorkflow', () => {
|
||||
id: 'asset-pdf',
|
||||
storageKey: { key: 'document.pdf' },
|
||||
mediaType: 'application/pdf',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
proxyType: 'pdf',
|
||||
@@ -119,7 +113,8 @@ describe('transcodePdfWorkflow', () => {
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.generateSpriteActivity.mockResolvedValue({
|
||||
sprite: { key: 'sprite.webp', frames: 100, tileX: 10, tileY: 10 },
|
||||
|
||||
@@ -1,47 +1,38 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import { updateAssetStatusActivity } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
downloadMediaToTmpActivity,
|
||||
generatePdfProxyActivity,
|
||||
getMediaInfoActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
|
||||
|
||||
export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
getMediaInfoActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
generatePdfProxyActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
const download = await downloadMediaToTmpActivity({
|
||||
assetKey: key,
|
||||
})
|
||||
let currentFilePath = download.filePath
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const pdfProxy = await executeActivity(workerQueue, generatePdfProxyActivity, {
|
||||
const pdfProxy = await generatePdfProxyActivity({
|
||||
teamId: task.teamId,
|
||||
assetId: asset.id,
|
||||
assetKey: key,
|
||||
@@ -53,7 +44,7 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
currentFilePath = pdfProxy.pdfFilePath
|
||||
|
||||
const spec = task.payload?.transcode || {}
|
||||
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
|
||||
const mediaInfo = await getMediaInfoActivity({
|
||||
filePath: currentFilePath,
|
||||
assetId: asset.id,
|
||||
proxyType: 'pdf',
|
||||
@@ -83,7 +74,7 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
|
||||
}
|
||||
|
||||
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
|
||||
const spriteResult = await generateSpriteActivity({
|
||||
assetKey: key,
|
||||
filePath: currentFilePath,
|
||||
spriteSpec,
|
||||
@@ -94,35 +85,35 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
mediaInfo.poster = spriteResult.poster
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcodePdfWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
await cleanupTmpDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,71 +1,77 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodeVideoWorkflow } from './transcode-video'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
getMediaInfoActivity,
|
||||
transcodeVideoActivity,
|
||||
transcodeHlsActivity,
|
||||
transcodeAudioActivity,
|
||||
transcodeImageActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
cleanupTmpDirActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
extractPosterActivity,
|
||||
type VideoActivityParams,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
getMediaInfoActivity: vi.fn(),
|
||||
transcodeVideoActivity: vi.fn(),
|
||||
transcodeHlsActivity: vi.fn(),
|
||||
transcodeAudioActivity: vi.fn(),
|
||||
transcodeImageActivity: vi.fn(),
|
||||
generateSpriteActivity: vi.fn(),
|
||||
updateAssetMediaActivity: vi.fn(),
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.fn(),
|
||||
createAutofillTaskIfEnabledActivity: vi.fn(),
|
||||
extractPosterActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcodeVideoWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }),
|
||||
transcodeVideoActivity: Object.assign(vi.fn(), { _activityName: 'transcodeVideoActivity' }),
|
||||
transcodeHlsActivity: Object.assign(vi.fn(), { _activityName: 'transcodeHlsActivity' }),
|
||||
transcodeAudioActivity: Object.assign(vi.fn(), { _activityName: 'transcodeAudioActivity' }),
|
||||
transcodeImageActivity: Object.assign(vi.fn(), { _activityName: 'transcodeImageActivity' }),
|
||||
generateSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generateSpriteActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
extractPosterActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractPosterActivity',
|
||||
}),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to allow partial mock payloads in unit tests
|
||||
let mockActivities: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
getMediaInfoActivity: vi.mocked(getMediaInfoActivity),
|
||||
transcodeVideoActivity: vi.mocked(transcodeVideoActivity),
|
||||
transcodeHlsActivity: vi.mocked(transcodeHlsActivity),
|
||||
transcodeAudioActivity: vi.mocked(transcodeAudioActivity),
|
||||
transcodeImageActivity: vi.mocked(transcodeImageActivity),
|
||||
generateSpriteActivity: vi.mocked(generateSpriteActivity),
|
||||
updateAssetMediaActivity: vi.mocked(updateAssetMediaActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
cleanupTmpDirActivity: vi.mocked(cleanupTmpDirActivity),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.mocked(createEmbeddingTaskIfEnabledActivity),
|
||||
createAutofillTaskIfEnabledActivity: vi.mocked(createAutofillTaskIfEnabledActivity),
|
||||
extractPosterActivity: vi.mocked(extractPosterActivity),
|
||||
}
|
||||
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/video.mp4',
|
||||
tmpDir: '/tmp',
|
||||
@@ -554,15 +560,17 @@ describe('transcodeVideoWorkflow', () => {
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(async (params) => {
|
||||
return {
|
||||
key: `files/asset-hdr/video-${params.videoSpec.resolution}${params.videoSpec.hdr ? '-hdr' : ''}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
})
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(
|
||||
async (params: VideoActivityParams) => {
|
||||
return {
|
||||
key: `files/asset-hdr/video-${params.videoSpec.resolution}${params.videoSpec.hdr ? '-hdr' : ''}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
@@ -659,15 +667,17 @@ describe('transcodeVideoWorkflow', () => {
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(async (params) => {
|
||||
return {
|
||||
key: `files/asset-sdr-source/video-${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
})
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(
|
||||
async (params: VideoActivityParams) => {
|
||||
return {
|
||||
key: `files/asset-sdr-source/video-${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
@@ -846,12 +856,14 @@ describe('transcodeVideoWorkflow', () => {
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(async (params) => ({
|
||||
key: `files/asset-multi/${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
}))
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(
|
||||
async (params: VideoActivityParams) => ({
|
||||
key: `files/asset-multi/${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
}),
|
||||
)
|
||||
|
||||
return transcodeVideoWorkflow(task).then(() => {
|
||||
// 180p preview + 1080p + 720p (2160p is skipped since > 1920)
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import { updateAssetStatusActivity } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
downloadMediaToTmpActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeVideoActivity,
|
||||
transcodeHlsActivity,
|
||||
transcodeAudioActivity,
|
||||
transcodeImageActivity,
|
||||
extractPosterActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
|
||||
import {
|
||||
getTargetVideoResolutions,
|
||||
getTargetHlsResolutions,
|
||||
@@ -16,35 +23,19 @@ import {
|
||||
|
||||
export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeVideoActivity,
|
||||
transcodeHlsActivity,
|
||||
transcodeAudioActivity,
|
||||
transcodeImageActivity,
|
||||
extractPosterActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
const download = await downloadMediaToTmpActivity({
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
@@ -52,7 +43,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
|
||||
const spec = task.payload?.transcode || {}
|
||||
const proxyType = asset.mediaType?.startsWith('audio/') ? 'audio' : 'video'
|
||||
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
|
||||
const mediaInfo = await getMediaInfoActivity({
|
||||
filePath,
|
||||
assetId: asset.id,
|
||||
proxyType,
|
||||
@@ -73,7 +64,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
const posterSpec: PrismaJson.PosterInfo = {
|
||||
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
|
||||
}
|
||||
const posterResult = await executeActivity(workerQueue, extractPosterActivity, {
|
||||
const posterResult = await extractPosterActivity({
|
||||
assetKey: key,
|
||||
posterSpec,
|
||||
taskId: task.id,
|
||||
@@ -83,7 +74,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
streamIndex: mediaInfo.metadata?.videoStreamIndex,
|
||||
})
|
||||
mediaInfo.poster = posterResult.poster
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
@@ -105,7 +96,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
|
||||
}
|
||||
|
||||
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
|
||||
const spriteResult = await generateSpriteActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -120,7 +111,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
mediaInfo.poster = spriteResult.poster
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
@@ -152,7 +143,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
hdr: isHdr,
|
||||
}
|
||||
|
||||
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
|
||||
const videoTranscode = await transcodeVideoActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -183,7 +174,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
hdr: isHdr,
|
||||
}
|
||||
|
||||
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
|
||||
const videoTranscode = await transcodeVideoActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -214,7 +205,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
metadata.originalHeight,
|
||||
)
|
||||
if (hlsLadders.length > 0) {
|
||||
const hlsResult = await executeActivity(workerQueue, transcodeHlsActivity, {
|
||||
const hlsResult = await transcodeHlsActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -222,6 +213,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
originalWidth: metadata.originalWidth,
|
||||
originalHeight: metadata.originalHeight,
|
||||
originalFps: metadata.frameRate,
|
||||
duration: metadata.duration,
|
||||
sourceVideoBitrate: metadata.videoBitRate || metadata.bitRate,
|
||||
hardwareAcceleration: spec.hardwareAcceleration,
|
||||
threads: spec.threads,
|
||||
@@ -242,7 +234,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
|
||||
const isAudio = mediaInfo.proxyType === 'audio'
|
||||
if (isAudio && metadata) {
|
||||
const audioTranscode = await executeActivity(workerQueue, transcodeAudioActivity, {
|
||||
const audioTranscode = await transcodeAudioActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -253,7 +245,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
}
|
||||
|
||||
if (spec.thumbnail && isVideo) {
|
||||
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
const thumbTranscode = await transcodeImageActivity({
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec: { width: 300, height: 300, quality: 80, format: 'webp', isPreview: true },
|
||||
@@ -261,35 +253,35 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
mediaInfo.thumbnail = thumbTranscode
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcodeVideoWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
await cleanupTmpDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { getWorkerQueueAndStartTask, completeTask, failTask } from './common'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import {
|
||||
initWatermarkFileActivity,
|
||||
waitForWatermarkFileActivity,
|
||||
transcodeWatermarkMediaActivity,
|
||||
completeWatermarkFileActivity,
|
||||
} from '../activities/watermark'
|
||||
import { startTask, completeTask, failTask } from './common'
|
||||
|
||||
export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let workerQueue = ''
|
||||
const watermarkConfigId = task.payload?.watermark?.watermarkConfigId
|
||||
const shareLinkId = task.payload?.watermark?.shareLinkId
|
||||
|
||||
@@ -16,30 +21,23 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
}
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
initWatermarkFileActivity,
|
||||
waitForWatermarkFileActivity,
|
||||
transcodeWatermarkMediaActivity,
|
||||
completeWatermarkFileActivity,
|
||||
} = getActivities()
|
||||
|
||||
const initResult = await executeActivity(workerQueue, initWatermarkFileActivity, {
|
||||
const initResult = await initWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
})
|
||||
|
||||
if (initResult.action === 'completed') {
|
||||
if (shareLinkId) {
|
||||
await executeActivity(workerQueue, completeWatermarkFileActivity, {
|
||||
await completeWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
status: 'completed',
|
||||
shareLinkId,
|
||||
})
|
||||
}
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -51,21 +49,21 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
}
|
||||
|
||||
if (initResult.action === 'processing') {
|
||||
const waitResult = await executeActivity(workerQueue, waitForWatermarkFileActivity, {
|
||||
const waitResult = await waitForWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
})
|
||||
|
||||
if (waitResult.status === 'completed') {
|
||||
if (shareLinkId) {
|
||||
await executeActivity(workerQueue, completeWatermarkFileActivity, {
|
||||
await completeWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
status: 'completed',
|
||||
shareLinkId,
|
||||
})
|
||||
}
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -75,12 +73,12 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
})
|
||||
}
|
||||
|
||||
const mediaInfo = await executeActivity(workerQueue, transcodeWatermarkMediaActivity, {
|
||||
const mediaInfo = await transcodeWatermarkMediaActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, completeWatermarkFileActivity, {
|
||||
await completeWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
mediaInfo,
|
||||
@@ -88,12 +86,11 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
shareLinkId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
if (workerQueue && watermarkConfigId) {
|
||||
const { completeWatermarkFileActivity } = getActivities()
|
||||
if (watermarkConfigId) {
|
||||
try {
|
||||
await executeActivity(workerQueue, completeWatermarkFileActivity, {
|
||||
await completeWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
status: 'failed',
|
||||
@@ -103,7 +100,7 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
console.error('Failed to update watermark file status to failed:', e)
|
||||
}
|
||||
}
|
||||
await failTask(workerQueue, task.id, err)
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,52 +1,45 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodeMedia } from './transcode'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
downloadMediaToTmpActivity,
|
||||
getMediaInfoActivity,
|
||||
renderPdfPagesActivity,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
getMediaInfoActivity: vi.fn(),
|
||||
renderPdfPagesActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcodeMedia Fallback Dispatcher', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
renderPdfPagesActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'renderPdfPagesActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
renderPdfPagesActivity: vi.mocked(renderPdfPagesActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
getMediaInfoActivity: vi.mocked(getMediaInfoActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
})
|
||||
|
||||
it('should dispatch to pdfPages workflow when payload.pdfPages is present', async () => {
|
||||
@@ -79,7 +72,8 @@ describe('transcodeMedia Fallback Dispatcher', () => {
|
||||
id: 'asset-pdf',
|
||||
storageKey: { key: 'doc.pdf' },
|
||||
mediaType: 'application/pdf',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.renderPdfPagesActivity.mockResolvedValue([])
|
||||
|
||||
|
||||
Reference in New Issue
Block a user