fix(transcode): preserve trashed status during background jobs and handle permanent purge (#416)

* fix(transcode): preserve trashed status during background jobs and handle permanent purge

* fix(workflow): clear heartbeat and add info logs on task cancellation

* fix(transcode): terminate media processes and guard task activities on cancellation

- Pass AbortSignal to ffmpeg and pdftoppm child processes in transcodeService to terminate processes on task cancellation
- Add local task AbortController context and cancellation guards in executeActivity to prevent subsequent workflow activities
- Forward taskId and cancellation signals in transcode, screenshot, and PDF activities
- Use updateMany instead of update in task activities to eliminate Prisma P2025 errors on purged task records

* fix(workflow): allow cleanup activities in finally blocks during task cancellation

Remove blanket cancellation check in executeActivity so that workflows can execute cleanup and failure handling activities in catch and finally blocks upon cancellation, while relying on AbortSignal in active activities to abort execution.

* docs(changelog): improve user friendliness of changelog entries and formatting example

* docs(agents): update changelog guidelines to emphasize end-user friendly descriptions

* fix(transcode): handle queued cancellation and delete races in media workflow
This commit is contained in:
Yiling-J
2026-09-19 10:40:49 +08:00
committed by GitHub
parent 145aa6bfb4
commit b52b2ce7d8
25 changed files with 1172 additions and 65 deletions
+145 -1
View File
@@ -3,13 +3,14 @@ import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { HTTPException } from 'hono/http-exception'
import { AssetType, AssetStatus, Prisma } from '@shumai/db'
import { AssetType, AssetStatus, Prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { uploadService } from '@shumai/core/src/upload/upload'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { AssetService } from './asset'
import { ensureJpegInStorage } from '@shumai/core/src/s3/preview-converter'
import { workflowService } from '@shumai/workflow-core'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
@@ -3004,6 +3005,65 @@ describe('AssetService — natural sort by name', () => {
await expect(assetService.emptyTrash(project.id)).resolves.not.toThrow()
})
it('should purge trashed assets whose status was processed, cancel their in-flight tasks, and delete WorkflowTasks', async () => {
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
const team = await prisma.team.create({ data: { name: 'Purge Task Team' } })
const project = await prisma.project.create({
data: { name: 'Purge Task Project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const user = await prisma.user.create({
data: { name: 'Test User Purge', email: `test-purge-${Date.now()}@example.com` },
})
// Asset was deleted, but status was set to 'processed' by background activity
const file = await prisma.asset.create({
data: {
name: 'skewed-status.mp4',
type: AssetType.file,
status: AssetStatus.processed,
isDeleted: true,
deletedAt: new Date(),
project: { connect: { id: project.id } },
parent: { connect: { id: rootFolder.id } },
creator: { connect: { id: user.id } },
storageKey: { create: { key: 'files/skewed-status/raw.mp4' } },
},
})
// In-flight task for this asset
const task = await prisma.workflowTask.create({
data: {
assetId: file.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
await assetService.emptyTrash(project.id)
// Asset should be deleted from DB
const assetInDb = await prisma.asset.findUnique({ where: { id: file.id } })
expect(assetInDb).toBeNull()
// Task should be cancelled
expect(cancelSpy).toHaveBeenCalledWith(task.id)
// WorkflowTask should be deleted from DB
const taskInDb = await prisma.workflowTask.findUnique({ where: { id: task.id } })
expect(taskInDb).toBeNull()
cancelSpy.mockRestore()
})
})
describe('expireTrashedAssets', () => {
@@ -4904,4 +4964,88 @@ describe('AssetService — natural sort by name', () => {
expect(stackInfo?.commentsCount).toBe(1)
})
})
describe('restoreAssets with in-flight transcoding', () => {
it('should restore asset with status "processing" if a transcode task is still active', async () => {
const team = await prisma.team.create({ data: { name: 'Restore Transcode Team' } })
const project = await prisma.project.create({
data: { name: 'Restore Transcode Project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const file = await prisma.asset.create({
data: {
name: 'transcoding-video.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
status: AssetStatus.trashed,
isDeleted: true,
deletedAt: new Date(),
},
})
// Create an active transcode task
await prisma.workflowTask.create({
data: {
assetId: file.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
await assetService.restoreAssets([file.id])
const restored = await prisma.asset.findUnique({ where: { id: file.id } })
expect(restored?.isDeleted).toBe(false)
expect(restored?.status).toBe(AssetStatus.processing)
})
it('should restore asset with status "processed" if no active transcode task exists', async () => {
const team = await prisma.team.create({ data: { name: 'Restore Completed Team' } })
const project = await prisma.project.create({
data: { name: 'Restore Completed Project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const file = await prisma.asset.create({
data: {
name: 'completed-video.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
status: AssetStatus.trashed,
isDeleted: true,
deletedAt: new Date(),
},
})
// Completed transcode task
await prisma.workflowTask.create({
data: {
assetId: file.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.completed,
},
})
await assetService.restoreAssets([file.id])
const restored = await prisma.asset.findUnique({ where: { id: file.id } })
expect(restored?.isDeleted).toBe(false)
expect(restored?.status).toBe(AssetStatus.processed)
})
})
})
+84 -8
View File
@@ -1,4 +1,4 @@
import { prisma } from '@shumai/db'
import { cancelWorkflowTask, prisma } from '@shumai/db'
import {
AncestorFolder,
AssetInfo,
@@ -28,7 +28,15 @@ import {
type ExportOptions,
type ExportResult,
} from './comments-export'
import { type Asset, AssetStatus, AssetType, Prisma, type StorageKey } from '@shumai/db'
import {
type Asset,
AssetStatus,
AssetType,
Prisma,
type StorageKey,
WorkflowTaskStatus,
WorkflowTaskType,
} from '@shumai/db'
import { HTTPException } from 'hono/http-exception'
import { logger } from '@shumai/core/src/logger'
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
@@ -1343,7 +1351,7 @@ export class AssetService {
private async cascadeStatusToPendingPurge(rootIds: string[]): Promise<void> {
if (rootIds.length === 0) return
await this.prismaClient.$executeRaw`
const rows = await this.prismaClient.$queryRaw<{ id: string }[]>`
WITH RECURSIVE descendant AS (
SELECT id FROM assets WHERE id = ANY(${rootIds})
UNION ALL
@@ -1358,15 +1366,35 @@ export class AssetService {
WHERE s.type = 'symlink' AND s.target_id IN (SELECT id FROM all_purging_targets)
)
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
WHERE id IN (SELECT id FROM all_purging_targets) OR id IN (SELECT id FROM all_affected_symlinks);
WHERE id IN (SELECT id FROM all_purging_targets) OR id IN (SELECT id FROM all_affected_symlinks)
RETURNING id;
`
const affectedIds = rows.map((r) => r.id)
if (affectedIds.length > 0) {
const inFlightTasks = await this.prismaClient.workflowTask.findMany({
where: {
assetId: { in: affectedIds },
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
select: { id: true },
})
for (const task of inFlightTasks) {
try {
logger.info({ taskId: task.id }, 'Cancelling in-flight workflow task for purging asset')
await cancelWorkflowTask(task.id)
} catch (err) {
logger.warn({ taskId: task.id, err }, 'Failed to cancel workflow task during purge')
}
}
}
}
async emptyTrash(projectId: string): Promise<void> {
const trashedRoots = await this.prismaClient.asset.findMany({
where: {
projectId,
status: 'trashed',
isDeleted: true,
},
select: { id: true },
@@ -1418,9 +1446,9 @@ export class AssetService {
// Find up to 100 expired roots, ordered by oldest first to avoid starvation
const expiredRoots = await this.prismaClient.asset.findMany({
where: {
status: 'trashed',
deletedAt: { lt: thirtyDaysAgo },
isDeleted: true,
status: { not: AssetStatus.pending_purge },
deletedAt: { lt: thirtyDaysAgo },
},
orderBy: { deletedAt: 'asc' },
select: { id: true },
@@ -1435,6 +1463,35 @@ export class AssetService {
* Stage 2: Delete DB records for assets marked as 'pending_purge'.
*/
private async purgePendingAssets() {
const pendingAssets = await this.prismaClient.asset.findMany({
where: { status: AssetStatus.pending_purge },
select: { id: true },
})
const pendingAssetIds = pendingAssets.map((a) => a.id)
if (pendingAssetIds.length > 0) {
const inFlightTasks = await this.prismaClient.workflowTask.findMany({
where: {
assetId: { in: pendingAssetIds },
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
select: { id: true },
})
for (const task of inFlightTasks) {
try {
logger.info({ taskId: task.id }, 'Cancelling in-flight workflow task before purge')
await cancelWorkflowTask(task.id)
} catch (err) {
logger.warn({ taskId: task.id, err }, 'Failed to cancel workflow task during purge')
}
}
await this.prismaClient.workflowTask.deleteMany({
where: { assetId: { in: pendingAssetIds } },
})
}
const { count } = await this.prismaClient.asset.deleteMany({
where: { status: AssetStatus.pending_purge },
})
@@ -1577,11 +1634,30 @@ export class AssetService {
}
}
const activeTask = await tx.workflowTask.findFirst({
where: {
assetId: a.id,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
type: {
in: [
WorkflowTaskType.transcode,
WorkflowTaskType.transcode_video,
WorkflowTaskType.transcode_image,
WorkflowTaskType.transcode_pdf,
WorkflowTaskType.transcode_pdf_pages,
WorkflowTaskType.transcode_screenshot,
WorkflowTaskType.transcode_image_annotation,
WorkflowTaskType.transcode_watermark,
],
},
},
})
await tx.asset.update({
where: { id: a.id },
data: {
isDeleted: false,
status: 'processed',
status: activeTask ? AssetStatus.processing : AssetStatus.processed,
deletedAt: null,
},
})
@@ -1776,5 +1776,41 @@ describe('TranscodeService', () => {
expect.any(Function),
)
})
it('transcodeVideo with signal should pass signal to execFile', async () => {
vi.mocked(execFile).mockImplementation(
(
_cmd: unknown,
_args: unknown,
optionsOrCallback: unknown,
maybeCallback?: unknown,
): ReturnType<typeof child_process.execFile> => {
const cb = (
typeof optionsOrCallback === 'function' ? optionsOrCallback : maybeCallback
) as (err: Error | null, result: { stdout: string; stderr: string }) => void
if (typeof cb === 'function') {
cb(null, { stdout: '', stderr: '' })
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const controller = new AbortController()
const outputFile = path.join(tempDir, 'out_signal.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
signal: controller.signal,
})
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
expect.any(Array),
{ signal: controller.signal },
expect.any(Function),
)
})
})
})
+51 -8
View File
@@ -117,6 +117,7 @@ export interface TranscodeVideoParams {
videoBitrate?: string
sourceVideoBitrate?: number
threads?: number
signal?: AbortSignal
}
export interface EncoderConfig {
@@ -634,7 +635,13 @@ export class TranscodeService {
args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', params.outputFile)
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
if (params.signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], {
signal: params.signal,
})
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
}
async transcodeImage(
@@ -741,6 +748,7 @@ export class TranscodeService {
outputSprite: string,
outputPoster: string,
duration: number,
signal?: AbortSignal,
): Promise<void> {
const spriteFps = 100 / duration
const filterComplex = `[0:v]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:300:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
@@ -771,19 +779,30 @@ export class TranscodeService {
'1024',
outputPoster,
]
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
if (signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { signal })
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
}
async generatePdfSprite(
inputFile: string,
outputSprite: string,
outputPoster: string,
signal?: AbortSignal,
): Promise<{ pageCount: number; originalWidth: number; originalHeight: number }> {
const tmpDir = this.createTempDir('pdf-sprite-')
try {
const pagePrefix = path.join(tmpDir, 'page')
try {
await execFileAsync('pdftoppm', ['-png', '-f', '1', '-l', '100', inputFile, pagePrefix])
if (signal) {
await execFileAsync('pdftoppm', ['-png', '-f', '1', '-l', '100', inputFile, pagePrefix], {
signal,
})
} else {
await execFileAsync('pdftoppm', ['-png', '-f', '1', '-l', '100', inputFile, pagePrefix])
}
} catch (err) {
const errCode = (err as Record<string, unknown>)?.code
const msg = err instanceof Error ? err.message : String(err)
@@ -840,7 +859,11 @@ export class TranscodeService {
'75',
outputSprite,
]
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...spriteArgs])
if (signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...spriteArgs], { signal })
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...spriteArgs])
}
await sharp(firstPagePath, { limitInputPixels: false })
.toColorspace('srgb')
@@ -1090,6 +1113,7 @@ export class TranscodeService {
outputFile: string
bitrate?: string
threads?: number
signal?: AbortSignal
}): Promise<void> {
const bitrate = params.bitrate || '128k'
const args = ['-i', params.inputFile, '-vn', '-c:a', 'aac', '-b:a', bitrate, '-ac', '2']
@@ -1097,7 +1121,13 @@ export class TranscodeService {
args.push('-threads', params.threads.toString())
}
args.push(params.outputFile)
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
if (params.signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], {
signal: params.signal,
})
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
}
async extractVideoFrames(params: ExtractVideoFramesParams): Promise<string[]> {
@@ -1198,6 +1228,7 @@ export class TranscodeService {
count: number
commentTimestamp?: number | null
annotations?: PrismaJson.AnnotationList | null
signal?: AbortSignal
}): Promise<Array<{ key: string; timestamp: number }>> {
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = this.createTempDir('screenshot-')
@@ -1259,7 +1290,13 @@ export class TranscodeService {
'80',
localShotPath,
]
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
if (params.signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], {
signal: params.signal,
})
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
const isMatch =
commentTimestamp !== undefined &&
@@ -1295,6 +1332,7 @@ export class TranscodeService {
end: number
commentTimestamp?: number | null
annotations?: PrismaJson.AnnotationList | null
signal?: AbortSignal
}): Promise<Array<{ key: string; page: number }>> {
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = this.createTempDir('pdf-pages-')
@@ -1307,7 +1345,7 @@ export class TranscodeService {
// 2. Render pages via pdftoppm (-png -f start -l end)
const pagePrefix = path.join(tmpDir, 'page')
try {
await execFileAsync('pdftoppm', [
const pdftoppmArgs = [
'-png',
'-f',
params.start.toString(),
@@ -1315,7 +1353,12 @@ export class TranscodeService {
params.end.toString(),
pdfPath,
pagePrefix,
])
]
if (params.signal) {
await execFileAsync('pdftoppm', pdftoppmArgs, { signal: params.signal })
} else {
await execFileAsync('pdftoppm', pdftoppmArgs)
}
} catch (err) {
const errCode = (err as Record<string, unknown>)?.code
const msg = err instanceof Error ? err.message : String(err)