mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 17:07:42 +00:00
feat(storage): add archive storage support for assets
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
import * as fs from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AssetStatus, prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
getArchiveStorageService,
|
||||
resetArchiveStorageServiceForTests,
|
||||
} from '@shumai/core/src/s3/archive-storage'
|
||||
import { archiveAssetWorkflow } from '../workflows/archive-asset'
|
||||
import { restoreAssetWorkflow } from '../workflows/restore-asset'
|
||||
|
||||
describe('Archive & Restore Workflows and Activities', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let tmpArchiveRoot: string
|
||||
const savedEnv: Record<string, string | undefined> = {}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const k of [
|
||||
'ARCHIVE_STORAGE_BACKEND',
|
||||
'ARCHIVE_LOCAL_ROOT',
|
||||
'ARCHIVE_RESTORE_POLL_INTERVAL_MS',
|
||||
]) {
|
||||
savedEnv[k] = process.env[k]
|
||||
}
|
||||
tmpArchiveRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-wf-archive-'))
|
||||
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
|
||||
process.env.ARCHIVE_LOCAL_ROOT = tmpArchiveRoot
|
||||
process.env.ARCHIVE_RESTORE_POLL_INTERVAL_MS = '10'
|
||||
resetArchiveStorageServiceForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const [k, v] of Object.entries(savedEnv)) {
|
||||
if (v === undefined) {
|
||||
delete process.env[k]
|
||||
} else {
|
||||
process.env[k] = v
|
||||
}
|
||||
}
|
||||
resetArchiveStorageServiceForTests()
|
||||
vi.restoreAllMocks()
|
||||
fs.rmSync(tmpArchiveRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('archives an asset original to local archive storage, syncs shared copies, and deletes main original', async () => {
|
||||
const key = 'files/wf-test/clip.mp4'
|
||||
const payloadBytes = Buffer.from('raw-video-content-bytes-12345')
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
await s3Service.putObject(bucket, key, payloadBytes, payloadBytes.length, 'video/mp4')
|
||||
|
||||
const sk = await prisma.storageKey.create({
|
||||
data: { key, isArchived: false },
|
||||
})
|
||||
const asset1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: 'file',
|
||||
status: AssetStatus.archiving,
|
||||
sizeByte: BigInt(payloadBytes.length),
|
||||
mediaType: 'video/mp4',
|
||||
storageKeyId: sk.id,
|
||||
},
|
||||
})
|
||||
const asset2Copy = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip-copy.mp4',
|
||||
type: 'file',
|
||||
status: AssetStatus.archiving,
|
||||
sizeByte: BigInt(payloadBytes.length),
|
||||
mediaType: 'video/mp4',
|
||||
storageKeyId: sk.id,
|
||||
},
|
||||
})
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset1.id,
|
||||
type: WorkflowTaskType.archive_asset,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
payload: { projectId: 'proj-1', archive: { storageKeyId: sk.id } },
|
||||
},
|
||||
})
|
||||
|
||||
await archiveAssetWorkflow(task)
|
||||
|
||||
const archiveStorage = getArchiveStorageService()!
|
||||
const archHead = await archiveStorage.headObject(key)
|
||||
expect(archHead.size).toBe(payloadBytes.length)
|
||||
|
||||
await expect(s3Service.headObject(bucket, key)).rejects.toThrow('NoSuchKey')
|
||||
|
||||
const updatedSk = await prisma.storageKey.findUniqueOrThrow({ where: { id: sk.id } })
|
||||
expect(updatedSk.isArchived).toBe(true)
|
||||
|
||||
const updatedA1 = await prisma.asset.findUniqueOrThrow({ where: { id: asset1.id } })
|
||||
const updatedA2 = await prisma.asset.findUniqueOrThrow({ where: { id: asset2Copy.id } })
|
||||
expect(updatedA1.status).toBe(AssetStatus.archived)
|
||||
expect(updatedA2.status).toBe(AssetStatus.archived)
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUniqueOrThrow({ where: { id: task.id } })
|
||||
expect(updatedTask.status).toBe(WorkflowTaskStatus.completed)
|
||||
})
|
||||
|
||||
it('restores an archived asset back to main storage, polls cold storage when needed, and deletes archive copy', async () => {
|
||||
const key = 'files/wf-test/restore-me.mp4'
|
||||
const payloadBytes = Buffer.from('restored-video-bytes-987654')
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
const archiveStorage = getArchiveStorageService()!
|
||||
const webStream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(payloadBytes))
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
await archiveStorage.uploadStream(key, webStream, payloadBytes.length, 'video/mp4')
|
||||
|
||||
// Simulate one cold-storage 'restoring' poll iteration before 'ready'
|
||||
let pollCalls = 0
|
||||
vi.spyOn(archiveStorage, 'checkOrInitiateObjectRestore').mockImplementation(async () => {
|
||||
pollCalls++
|
||||
return pollCalls === 1 ? { status: 'restoring' } : { status: 'ready' }
|
||||
})
|
||||
|
||||
const sk = await prisma.storageKey.create({
|
||||
data: { key, isArchived: true },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'restore-me.mp4',
|
||||
type: 'file',
|
||||
status: AssetStatus.restoring,
|
||||
sizeByte: BigInt(payloadBytes.length),
|
||||
mediaType: 'video/mp4',
|
||||
storageKeyId: sk.id,
|
||||
},
|
||||
})
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
type: WorkflowTaskType.restore_asset,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
payload: { projectId: 'proj-1', archive: { storageKeyId: sk.id } },
|
||||
},
|
||||
})
|
||||
|
||||
await restoreAssetWorkflow(task)
|
||||
|
||||
expect(pollCalls).toBe(2)
|
||||
|
||||
const mainHead = await s3Service.headObject(bucket, key)
|
||||
expect(mainHead.size).toBe(payloadBytes.length)
|
||||
|
||||
await expect(archiveStorage.headObject(key)).rejects.toThrow('NoSuchKey')
|
||||
|
||||
const updatedSk = await prisma.storageKey.findUniqueOrThrow({ where: { id: sk.id } })
|
||||
expect(updatedSk.isArchived).toBe(false)
|
||||
|
||||
const updatedAsset = await prisma.asset.findUniqueOrThrow({ where: { id: asset.id } })
|
||||
expect(updatedAsset.status).toBe(AssetStatus.processed)
|
||||
|
||||
// Clean up main storage object
|
||||
await s3Service.deleteObject(bucket, key)
|
||||
})
|
||||
|
||||
it('reverts asset status back to processed when archive workflow fails before commit', async () => {
|
||||
const sk = await prisma.storageKey.create({
|
||||
data: { key: 'files/wf-test/missing-in-main.mp4', isArchived: false },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'missing-in-main.mp4',
|
||||
type: 'file',
|
||||
status: AssetStatus.archiving,
|
||||
sizeByte: BigInt(500),
|
||||
mediaType: 'video/mp4',
|
||||
storageKeyId: sk.id,
|
||||
},
|
||||
})
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
type: WorkflowTaskType.archive_asset,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
payload: { projectId: 'proj-1', archive: { storageKeyId: sk.id } },
|
||||
},
|
||||
})
|
||||
|
||||
await expect(archiveAssetWorkflow(task)).rejects.toThrow('Original file not found')
|
||||
|
||||
const updatedAsset = await prisma.asset.findUniqueOrThrow({ where: { id: asset.id } })
|
||||
expect(updatedAsset.status).toBe(AssetStatus.processed)
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUniqueOrThrow({ where: { id: task.id } })
|
||||
expect(updatedTask.status).toBe(WorkflowTaskStatus.failed)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,572 @@
|
||||
import { AssetStatus, prisma, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
getArchiveStorageService,
|
||||
isColdStorageRestoreError,
|
||||
type ArchiveStorageService,
|
||||
} from '@shumai/core/src/s3/archive-storage'
|
||||
import { ApplicationFailure, defineStep } from '@shumai/workflow-core'
|
||||
|
||||
function isNotFoundError(err: unknown): boolean {
|
||||
if (!err || typeof err !== 'object') return false
|
||||
const record = err as Record<string, unknown>
|
||||
const name = typeof record.name === 'string' ? record.name : ''
|
||||
const code = typeof record.code === 'string' ? record.code : ''
|
||||
const msg = typeof record.message === 'string' ? record.message : ''
|
||||
const metadata = record.$metadata as { httpStatusCode?: number } | undefined
|
||||
return (
|
||||
name === 'NotFound' ||
|
||||
name === 'NoSuchKey' ||
|
||||
code === 'NotFound' ||
|
||||
code === 'NoSuchKey' ||
|
||||
code === 'ENOENT' ||
|
||||
metadata?.httpStatusCode === 404 ||
|
||||
msg.includes('NoSuchKey') ||
|
||||
msg.includes('NotFound')
|
||||
)
|
||||
}
|
||||
|
||||
async function tryHeadMainObject(
|
||||
bucket: string,
|
||||
key: string,
|
||||
): Promise<{ exists: boolean; size?: number }> {
|
||||
try {
|
||||
const info = await s3Service.headObject(bucket, key)
|
||||
return { exists: true, size: info.size }
|
||||
} catch (err) {
|
||||
if (isNotFoundError(err)) {
|
||||
return { exists: false }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function tryHeadArchiveObject(
|
||||
archiveStorage: ArchiveStorageService,
|
||||
key: string,
|
||||
): Promise<{ exists: boolean; size?: number }> {
|
||||
try {
|
||||
const info = await archiveStorage.headObject(key)
|
||||
return { exists: true, size: info.size }
|
||||
} catch (err) {
|
||||
if (isNotFoundError(err)) {
|
||||
return { exists: false }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export interface PrepareArchiveOrRestoreParams {
|
||||
taskId: string
|
||||
assetId?: string | null
|
||||
storageKeyId?: string | null
|
||||
mode: 'archive' | 'restore'
|
||||
}
|
||||
|
||||
export interface PrepareArchiveOrRestoreResult {
|
||||
noop: boolean
|
||||
storageKeyId: string
|
||||
key: string
|
||||
expectedSize: number
|
||||
contentType: string
|
||||
}
|
||||
|
||||
export const prepareArchiveOrRestoreActivity = defineStep(
|
||||
async function prepareArchiveOrRestoreActivity(
|
||||
params: PrepareArchiveOrRestoreParams,
|
||||
): Promise<PrepareArchiveOrRestoreResult> {
|
||||
let storageKeyId = params.storageKeyId ?? null
|
||||
if (!storageKeyId && params.assetId) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
select: { storageKeyId: true },
|
||||
})
|
||||
storageKeyId = asset?.storageKeyId ?? null
|
||||
}
|
||||
|
||||
if (!storageKeyId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `StorageKey not found for ${params.mode} task ${params.taskId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const sk = await prisma.storageKey.findUnique({
|
||||
where: { id: storageKeyId },
|
||||
include: {
|
||||
assets: {
|
||||
where: { deletedAt: null, type: 'file' },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
sizeByte: true,
|
||||
mediaType: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (
|
||||
!sk ||
|
||||
sk.status === 'purging' ||
|
||||
sk.assets.length === 0 ||
|
||||
sk.assets.every(
|
||||
(a) => a.status === AssetStatus.trashed || a.status === AssetStatus.pending_purge,
|
||||
)
|
||||
) {
|
||||
logger.info(
|
||||
{ taskId: params.taskId, storageKeyId, mode: params.mode },
|
||||
'Skipping archive/restore task because storage key or all referencing assets are purged/trashed',
|
||||
)
|
||||
return {
|
||||
noop: true,
|
||||
storageKeyId,
|
||||
key: sk?.key || '',
|
||||
expectedSize: 0,
|
||||
contentType: 'application/octet-stream',
|
||||
}
|
||||
}
|
||||
|
||||
if (params.mode === 'archive' && sk.isArchived) {
|
||||
await prisma.asset.updateMany({
|
||||
where: {
|
||||
storageKeyId: sk.id,
|
||||
deletedAt: null,
|
||||
type: 'file',
|
||||
status: { notIn: [AssetStatus.trashed, AssetStatus.pending_purge] },
|
||||
},
|
||||
data: { status: AssetStatus.archived },
|
||||
})
|
||||
return {
|
||||
noop: true,
|
||||
storageKeyId: sk.id,
|
||||
key: sk.key,
|
||||
expectedSize: 0,
|
||||
contentType: 'application/octet-stream',
|
||||
}
|
||||
}
|
||||
|
||||
if (params.mode === 'restore' && !sk.isArchived) {
|
||||
await prisma.asset.updateMany({
|
||||
where: {
|
||||
storageKeyId: sk.id,
|
||||
deletedAt: null,
|
||||
type: 'file',
|
||||
status: { notIn: [AssetStatus.trashed, AssetStatus.pending_purge] },
|
||||
},
|
||||
data: { status: AssetStatus.processed },
|
||||
})
|
||||
return {
|
||||
noop: true,
|
||||
storageKeyId: sk.id,
|
||||
key: sk.key,
|
||||
expectedSize: 0,
|
||||
contentType: 'application/octet-stream',
|
||||
}
|
||||
}
|
||||
|
||||
const primaryAsset =
|
||||
sk.assets.find((a) => a.id === params.assetId) ||
|
||||
sk.assets.find((a) => a.sizeByte !== null && Number(a.sizeByte) > 0) ||
|
||||
sk.assets[0]
|
||||
|
||||
const expectedSize = primaryAsset?.sizeByte ? Number(primaryAsset.sizeByte) : 0
|
||||
const contentType = primaryAsset?.mediaType || 'application/octet-stream'
|
||||
|
||||
return {
|
||||
noop: false,
|
||||
storageKeyId: sk.id,
|
||||
key: sk.key,
|
||||
expectedSize,
|
||||
contentType,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export interface CopyOriginalToArchiveParams {
|
||||
storageKeyId: string
|
||||
key: string
|
||||
expectedSize: number
|
||||
contentType: string
|
||||
}
|
||||
|
||||
export const copyOriginalToArchiveStorageActivity = defineStep(
|
||||
async function copyOriginalToArchiveStorageActivity(
|
||||
params: CopyOriginalToArchiveParams,
|
||||
): Promise<{ copiedSize: number }> {
|
||||
const archiveStorage = getArchiveStorageService()
|
||||
if (!archiveStorage) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Archive storage is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const sk = await prisma.storageKey.findUnique({
|
||||
where: { id: params.storageKeyId },
|
||||
select: { status: true },
|
||||
})
|
||||
if (!sk || sk.status === 'purging') {
|
||||
throw ApplicationFailure.create({
|
||||
message: `StorageKey ${params.storageKeyId} is missing or purging`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
if (archiveStorage.isSameS3Target) {
|
||||
if (
|
||||
!archiveStorage.storageClass ||
|
||||
archiveStorage.storageClass.toUpperCase() === 'STANDARD'
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message:
|
||||
'Same-bucket S3 archive requires a non-STANDARD ARCHIVE_S3_STORAGE_CLASS to tier objects in place',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
let objectSize = params.expectedSize
|
||||
if (objectSize <= 0) {
|
||||
const mainHead = await tryHeadMainObject(bucket, params.key)
|
||||
if (!mainHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Original file not found in main storage: ${params.key}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
objectSize = mainHead.size ?? 0
|
||||
}
|
||||
|
||||
await archiveStorage.rewriteObjectStorageClassInPlace(
|
||||
params.key,
|
||||
archiveStorage.storageClass,
|
||||
objectSize,
|
||||
params.contentType,
|
||||
)
|
||||
|
||||
const verifyHead = await tryHeadArchiveObject(archiveStorage, params.key)
|
||||
if (!verifyHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to verify in-place archived object in S3: ${params.key}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
|
||||
return { copiedSize: verifyHead.size ?? objectSize }
|
||||
}
|
||||
|
||||
// Separate bucket or local archive storage: check if already uploaded in a prior attempt
|
||||
const existingArchiveHead = await tryHeadArchiveObject(archiveStorage, params.key)
|
||||
if (
|
||||
existingArchiveHead.exists &&
|
||||
existingArchiveHead.size !== undefined &&
|
||||
((params.expectedSize > 0 && existingArchiveHead.size === params.expectedSize) ||
|
||||
(params.expectedSize === 0 && existingArchiveHead.size > 0))
|
||||
) {
|
||||
return { copiedSize: existingArchiveHead.size }
|
||||
}
|
||||
|
||||
const mainHead = await tryHeadMainObject(bucket, params.key)
|
||||
if (!mainHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Original file not found in main storage: ${params.key}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedExpectedSize =
|
||||
params.expectedSize > 0 ? params.expectedSize : (mainHead.size ?? 0)
|
||||
const {
|
||||
stream,
|
||||
contentLength,
|
||||
contentType: sourceContentType,
|
||||
} = await s3Service.getObjectStream(bucket, params.key)
|
||||
|
||||
const uploadSize = contentLength ?? resolvedExpectedSize
|
||||
await archiveStorage.uploadStream(
|
||||
params.key,
|
||||
stream,
|
||||
uploadSize,
|
||||
sourceContentType || params.contentType,
|
||||
)
|
||||
|
||||
const verifyHead = await tryHeadArchiveObject(archiveStorage, params.key)
|
||||
if (!verifyHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Archive upload verification failed: object ${params.key} not found in archive storage`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
if (
|
||||
resolvedExpectedSize > 0 &&
|
||||
verifyHead.size !== undefined &&
|
||||
verifyHead.size !== resolvedExpectedSize
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Archive upload size mismatch for ${params.key}: expected ${resolvedExpectedSize}, got ${verifyHead.size}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
|
||||
return { copiedSize: verifyHead.size ?? uploadSize }
|
||||
},
|
||||
)
|
||||
|
||||
export const commitArchiveDbStateActivity = defineStep(
|
||||
async function commitArchiveDbStateActivity(params: { storageKeyId: string }): Promise<void> {
|
||||
await prisma.$transaction([
|
||||
prisma.storageKey.update({
|
||||
where: { id: params.storageKeyId },
|
||||
data: { isArchived: true },
|
||||
}),
|
||||
prisma.asset.updateMany({
|
||||
where: {
|
||||
storageKeyId: params.storageKeyId,
|
||||
deletedAt: null,
|
||||
type: 'file',
|
||||
status: { notIn: [AssetStatus.trashed, AssetStatus.pending_purge] },
|
||||
},
|
||||
data: { status: AssetStatus.archived },
|
||||
}),
|
||||
])
|
||||
},
|
||||
)
|
||||
|
||||
export const deleteMainOriginalAfterArchiveActivity = defineStep(
|
||||
async function deleteMainOriginalAfterArchiveActivity(params: { key: string }): Promise<void> {
|
||||
const archiveStorage = getArchiveStorageService()
|
||||
if (archiveStorage?.isSameS3Target) {
|
||||
return
|
||||
}
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
},
|
||||
)
|
||||
|
||||
export const checkOrInitiateColdRestoreActivity = defineStep(
|
||||
async function checkOrInitiateColdRestoreActivity(params: {
|
||||
key: string
|
||||
}): Promise<{ status: 'ready' | 'restoring' }> {
|
||||
const archiveStorage = getArchiveStorageService()
|
||||
if (!archiveStorage) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Archive storage is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
return await archiveStorage.checkOrInitiateObjectRestore(params.key)
|
||||
},
|
||||
)
|
||||
|
||||
export interface CopyOriginalFromArchiveToMainParams {
|
||||
storageKeyId: string
|
||||
key: string
|
||||
expectedSize: number
|
||||
contentType: string
|
||||
}
|
||||
|
||||
export const copyOriginalFromArchiveToMainActivity = defineStep(
|
||||
async function copyOriginalFromArchiveToMainActivity(
|
||||
params: CopyOriginalFromArchiveToMainParams,
|
||||
): Promise<{ status: 'copied' | 'restoring'; copiedSize?: number }> {
|
||||
const archiveStorage = getArchiveStorageService()
|
||||
if (!archiveStorage) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Archive storage is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const sk = await prisma.storageKey.findUnique({
|
||||
where: { id: params.storageKeyId },
|
||||
select: { status: true },
|
||||
})
|
||||
if (!sk || sk.status === 'purging') {
|
||||
throw ApplicationFailure.create({
|
||||
message: `StorageKey ${params.storageKeyId} is missing or purging`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
try {
|
||||
if (archiveStorage.isSameS3Target) {
|
||||
let objectSize = params.expectedSize
|
||||
if (objectSize <= 0) {
|
||||
const archiveHead = await tryHeadArchiveObject(archiveStorage, params.key)
|
||||
if (!archiveHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Archived file not found in S3: ${params.key}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
objectSize = archiveHead.size ?? 0
|
||||
}
|
||||
|
||||
await archiveStorage.rewriteObjectStorageClassInPlace(
|
||||
params.key,
|
||||
'STANDARD',
|
||||
objectSize,
|
||||
params.contentType,
|
||||
)
|
||||
|
||||
const verifyHead = await tryHeadMainObject(bucket, params.key)
|
||||
if (!verifyHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to verify restored object in S3: ${params.key}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
|
||||
return { status: 'copied', copiedSize: verifyHead.size ?? objectSize }
|
||||
}
|
||||
|
||||
// Separate bucket or local archive storage: check if already restored to main storage
|
||||
const existingMainHead = await tryHeadMainObject(bucket, params.key)
|
||||
if (
|
||||
existingMainHead.exists &&
|
||||
existingMainHead.size !== undefined &&
|
||||
((params.expectedSize > 0 && existingMainHead.size === params.expectedSize) ||
|
||||
(params.expectedSize === 0 && existingMainHead.size > 0))
|
||||
) {
|
||||
return { status: 'copied', copiedSize: existingMainHead.size }
|
||||
}
|
||||
|
||||
const archiveHead = await tryHeadArchiveObject(archiveStorage, params.key)
|
||||
if (!archiveHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Archived original file not found in archive storage: ${params.key}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedExpectedSize =
|
||||
params.expectedSize > 0 ? params.expectedSize : (archiveHead.size ?? 0)
|
||||
const {
|
||||
stream,
|
||||
contentLength,
|
||||
contentType: archiveContentType,
|
||||
} = await archiveStorage.getObjectStream(params.key)
|
||||
|
||||
const uploadSize = contentLength ?? resolvedExpectedSize
|
||||
await s3Service.uploadStream({
|
||||
bucket,
|
||||
key: params.key,
|
||||
stream,
|
||||
contentLength: uploadSize,
|
||||
contentType: archiveContentType || params.contentType,
|
||||
})
|
||||
|
||||
const verifyMainHead = await tryHeadMainObject(bucket, params.key)
|
||||
if (!verifyMainHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Restore upload verification failed: object ${params.key} not found in main storage`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
if (
|
||||
resolvedExpectedSize > 0 &&
|
||||
verifyMainHead.size !== undefined &&
|
||||
verifyMainHead.size !== resolvedExpectedSize
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Restore upload size mismatch for ${params.key}: expected ${resolvedExpectedSize}, got ${verifyMainHead.size}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
|
||||
return { status: 'copied', copiedSize: verifyMainHead.size ?? uploadSize }
|
||||
} catch (err) {
|
||||
if (isColdStorageRestoreError(err)) {
|
||||
logger.info(
|
||||
{ key: params.key },
|
||||
'Encountered cold storage InvalidObjectState during restore copy; initiating RestoreObject polling',
|
||||
)
|
||||
await archiveStorage.initiateObjectRestoreExplicitly(params.key)
|
||||
return { status: 'restoring' }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export const commitRestoreDbStateActivity = defineStep(
|
||||
async function commitRestoreDbStateActivity(params: { storageKeyId: string }): Promise<void> {
|
||||
await prisma.$transaction([
|
||||
prisma.storageKey.update({
|
||||
where: { id: params.storageKeyId },
|
||||
data: { isArchived: false },
|
||||
}),
|
||||
prisma.asset.updateMany({
|
||||
where: {
|
||||
storageKeyId: params.storageKeyId,
|
||||
deletedAt: null,
|
||||
type: 'file',
|
||||
status: { notIn: [AssetStatus.trashed, AssetStatus.pending_purge] },
|
||||
},
|
||||
data: { status: AssetStatus.processed },
|
||||
}),
|
||||
])
|
||||
},
|
||||
)
|
||||
|
||||
export const deleteArchiveOriginalAfterRestoreActivity = defineStep(
|
||||
async function deleteArchiveOriginalAfterRestoreActivity(params: { key: string }): Promise<void> {
|
||||
const archiveStorage = getArchiveStorageService()
|
||||
if (!archiveStorage || archiveStorage.isSameS3Target) {
|
||||
return
|
||||
}
|
||||
await archiveStorage.deleteObject(params.key)
|
||||
},
|
||||
)
|
||||
|
||||
export const revertArchiveOrRestoreStatusOnFailureActivity = defineStep(
|
||||
async function revertArchiveOrRestoreStatusOnFailureActivity(params: {
|
||||
taskId: string
|
||||
storageKeyId?: string | null
|
||||
assetId?: string | null
|
||||
errorMessage: string
|
||||
}): Promise<void> {
|
||||
let storageKeyId = params.storageKeyId ?? null
|
||||
if (!storageKeyId && params.assetId) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
select: { storageKeyId: true },
|
||||
})
|
||||
storageKeyId = asset?.storageKeyId ?? null
|
||||
}
|
||||
|
||||
if (storageKeyId) {
|
||||
const sk = await prisma.storageKey.findUnique({
|
||||
where: { id: storageKeyId },
|
||||
select: { isArchived: true },
|
||||
})
|
||||
if (sk) {
|
||||
await prisma.asset.updateMany({
|
||||
where: {
|
||||
storageKeyId,
|
||||
deletedAt: null,
|
||||
type: 'file',
|
||||
status: { in: [AssetStatus.archiving, AssetStatus.restoring] },
|
||||
},
|
||||
data: {
|
||||
status: sk.isArchived ? AssetStatus.archived : AssetStatus.processed,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: params.errorMessage },
|
||||
},
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
@@ -798,5 +798,72 @@ describe('Watermark Activities', () => {
|
||||
expect(row?.status).toBe(WatermarkFileStatus.completed)
|
||||
expect(row?.media).toBeDefined()
|
||||
})
|
||||
|
||||
it('falls back to highest-resolution proxy when original video is archived', async () => {
|
||||
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 5,
|
||||
bitRate: 4000000,
|
||||
frameRate: 30,
|
||||
totalFrames: 150,
|
||||
hasAudio: false,
|
||||
mimeType: 'video/mp4',
|
||||
})
|
||||
|
||||
const sk = await prisma.storageKey.create({
|
||||
data: { key: 'files/arch/raw.mp4', isArchived: true },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'raw.mp4',
|
||||
type: 'file',
|
||||
status: 'archived',
|
||||
mediaType: 'video/mp4',
|
||||
storageKeyId: sk.id,
|
||||
media: {
|
||||
duration: 5,
|
||||
filesize: 1000,
|
||||
frames: 150,
|
||||
finishedAt: '2026-01-01T00:00:00Z',
|
||||
proxyType: 'video',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [
|
||||
{
|
||||
key: 'files/arch/raw-720p.mp4',
|
||||
width: 1280,
|
||||
height: 720,
|
||||
resolution: '720p',
|
||||
},
|
||||
{
|
||||
key: 'files/arch/raw-1080p.mp4',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
],
|
||||
metadata: null,
|
||||
original: { key: 'files/arch/raw.mp4', filesizeInBytes: 10000, codec: 'h264' },
|
||||
},
|
||||
},
|
||||
})
|
||||
const config = await prisma.watermarkConfig.create({
|
||||
data: {
|
||||
hash: 'arch-wm-hash-' + Math.random(),
|
||||
config: { blocks: [] },
|
||||
},
|
||||
})
|
||||
|
||||
await transcodeWatermarkMediaActivity({
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: config.id,
|
||||
})
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/arch/raw-1080p.mp4',
|
||||
expect.any(String),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -183,16 +183,39 @@ export const transcodeWatermarkMediaActivity = defineStep(
|
||||
})
|
||||
}
|
||||
|
||||
const inputKey = is3d
|
||||
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
|
||||
const isArchived = Boolean(asset.storageKey.isArchived || asset.status === 'archived')
|
||||
let inputKey: string | undefined
|
||||
if (is3d) {
|
||||
inputKey =
|
||||
(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,
|
||||
})
|
||||
if (!inputKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
} else if (isArchived) {
|
||||
const media = asset.media as PrismaJson.MediaInfo | null
|
||||
if (isVideo) {
|
||||
const sortedVideos = [...(media?.videoTranscodes || [])]
|
||||
.filter((t) => Boolean(t.key))
|
||||
.sort((a, b) => (b.height || 0) - (a.height || 0))
|
||||
inputKey = sortedVideos[0]?.key || media?.videoPreview?.key
|
||||
} else if (isImage) {
|
||||
const sortedImages = [...(media?.imageTranscodes || [])]
|
||||
.filter((t) => Boolean(t.key))
|
||||
.sort((a, b) => (b.width || 0) * (b.height || 0) - (a.width || 0) * (a.height || 0))
|
||||
inputKey = sortedImages[0]?.key
|
||||
}
|
||||
if (!inputKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Original file is archived and no transcoded proxy is available in main storage for asset ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
inputKey = assetKey
|
||||
}
|
||||
|
||||
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
|
||||
|
||||
@@ -9,6 +9,8 @@ import { overlayImageAnnotationWorkflow } from './workflows/overlay-image-annota
|
||||
import { transcodeWatermarkWorkflow } from './workflows/transcode-watermark'
|
||||
import { transcode3dWorkflow } from './workflows/transcode-3d'
|
||||
import { transcodeMedia } from './workflows/transcode'
|
||||
import { archiveAssetWorkflow } from './workflows/archive-asset'
|
||||
import { restoreAssetWorkflow } from './workflows/restore-asset'
|
||||
|
||||
export function initTranscodeWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.transcode, transcodeMedia)
|
||||
@@ -20,11 +22,16 @@ export function initTranscodeWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_watermark, transcodeWatermarkWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.archive_asset, archiveAssetWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.restore_asset, restoreAssetWorkflow)
|
||||
}
|
||||
|
||||
export * from './transcoder'
|
||||
export * from './workflows/transcode'
|
||||
export * from './workflows/transcode-3d'
|
||||
export * from './workflows/transcode-watermark'
|
||||
export * from './workflows/archive-asset'
|
||||
export * from './workflows/restore-asset'
|
||||
export * from './activities/transcode'
|
||||
export * from './activities/watermark'
|
||||
export * from './activities/archive'
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import {
|
||||
commitArchiveDbStateActivity,
|
||||
copyOriginalToArchiveStorageActivity,
|
||||
deleteMainOriginalAfterArchiveActivity,
|
||||
prepareArchiveOrRestoreActivity,
|
||||
revertArchiveOrRestoreStatusOnFailureActivity,
|
||||
} from '../activities/archive'
|
||||
import { completeTask, startTask } from './common'
|
||||
|
||||
export async function archiveAssetWorkflow(task: WorkflowTask): Promise<void> {
|
||||
const storageKeyId = task.payload?.archive?.storageKeyId
|
||||
|
||||
try {
|
||||
await startTask(task)
|
||||
|
||||
const prep = await prepareArchiveOrRestoreActivity({
|
||||
taskId: task.id,
|
||||
assetId: task.assetId,
|
||||
storageKeyId,
|
||||
mode: 'archive',
|
||||
})
|
||||
|
||||
if (prep.noop) {
|
||||
await completeTask(task.id)
|
||||
return
|
||||
}
|
||||
|
||||
await copyOriginalToArchiveStorageActivity({
|
||||
storageKeyId: prep.storageKeyId,
|
||||
key: prep.key,
|
||||
expectedSize: prep.expectedSize,
|
||||
contentType: prep.contentType,
|
||||
})
|
||||
|
||||
await commitArchiveDbStateActivity({
|
||||
storageKeyId: prep.storageKeyId,
|
||||
})
|
||||
|
||||
await deleteMainOriginalAfterArchiveActivity({
|
||||
key: prep.key,
|
||||
})
|
||||
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : String(err)
|
||||
await revertArchiveOrRestoreStatusOnFailureActivity({
|
||||
taskId: task.id,
|
||||
storageKeyId,
|
||||
assetId: task.assetId,
|
||||
errorMessage,
|
||||
}).catch((revertErr) => {
|
||||
console.error('Failed to revert archive status on failure:', revertErr)
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,17 @@ export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promis
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
key === asset.storageKey?.key &&
|
||||
(asset.storageKey?.isArchived || asset.status === 'archived')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message:
|
||||
'Original image file is archived and no proxy is available. Restore the asset to overlay annotations.',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const keyWithOverlay = await overlayAnnotationsActivity({
|
||||
assetKey: key,
|
||||
assetId: asset.id,
|
||||
|
||||
@@ -17,6 +17,12 @@ export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void>
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
const pdfKey = (asset.media as PrismaJson.MediaInfo | null)?.pdfTranscode?.key || key
|
||||
if (pdfKey === key && (asset.storageKey?.isArchived || asset.status === 'archived')) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Original PDF file is archived. Restore the asset to render pages.',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const pages = await renderPdfPagesActivity({
|
||||
taskId: task.id,
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { ApplicationFailure, sleep } from '@shumai/workflow-core'
|
||||
import {
|
||||
checkOrInitiateColdRestoreActivity,
|
||||
commitRestoreDbStateActivity,
|
||||
copyOriginalFromArchiveToMainActivity,
|
||||
deleteArchiveOriginalAfterRestoreActivity,
|
||||
prepareArchiveOrRestoreActivity,
|
||||
revertArchiveOrRestoreStatusOnFailureActivity,
|
||||
} from '../activities/archive'
|
||||
import { completeTask, startTask } from './common'
|
||||
|
||||
const DEFAULT_INITIAL_RESTORE_POLL_MS = 60_000
|
||||
const DEFAULT_STEADY_RESTORE_POLL_MS = 300_000
|
||||
const MAX_RESTORE_WAIT_MS = 48 * 60 * 60 * 1000
|
||||
|
||||
export async function restoreAssetWorkflow(task: WorkflowTask): Promise<void> {
|
||||
const storageKeyId = task.payload?.archive?.storageKeyId
|
||||
|
||||
try {
|
||||
await startTask(task)
|
||||
|
||||
const prep = await prepareArchiveOrRestoreActivity({
|
||||
taskId: task.id,
|
||||
assetId: task.assetId,
|
||||
storageKeyId,
|
||||
mode: 'restore',
|
||||
})
|
||||
|
||||
if (prep.noop) {
|
||||
await completeTask(task.id)
|
||||
return
|
||||
}
|
||||
|
||||
const customPollMs = process.env.ARCHIVE_RESTORE_POLL_INTERVAL_MS
|
||||
? parseInt(process.env.ARCHIVE_RESTORE_POLL_INTERVAL_MS, 10)
|
||||
: undefined
|
||||
const initialPollMs =
|
||||
customPollMs && Number.isFinite(customPollMs) && customPollMs > 0
|
||||
? customPollMs
|
||||
: DEFAULT_INITIAL_RESTORE_POLL_MS
|
||||
const steadyPollMs =
|
||||
customPollMs && Number.isFinite(customPollMs) && customPollMs > 0
|
||||
? customPollMs
|
||||
: DEFAULT_STEADY_RESTORE_POLL_MS
|
||||
|
||||
let elapsedWaitMs = 0
|
||||
let pollAttempt = 0
|
||||
|
||||
for (;;) {
|
||||
const restoreCheck = await checkOrInitiateColdRestoreActivity({ key: prep.key })
|
||||
while (restoreCheck.status === 'restoring') {
|
||||
if (elapsedWaitMs >= MAX_RESTORE_WAIT_MS) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Cold storage restore timed out after 48 hours for key: ${prep.key}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const waitMs = pollAttempt < 10 ? initialPollMs : steadyPollMs
|
||||
await sleep(waitMs)
|
||||
elapsedWaitMs += waitMs
|
||||
pollAttempt++
|
||||
|
||||
const nextCheck = await checkOrInitiateColdRestoreActivity({ key: prep.key })
|
||||
if (nextCheck.status === 'ready') {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const copyResult = await copyOriginalFromArchiveToMainActivity({
|
||||
storageKeyId: prep.storageKeyId,
|
||||
key: prep.key,
|
||||
expectedSize: prep.expectedSize,
|
||||
contentType: prep.contentType,
|
||||
})
|
||||
|
||||
if (copyResult.status === 'copied') {
|
||||
break
|
||||
}
|
||||
|
||||
// Reactive fallback: copy encountered InvalidObjectState and initiated RestoreObject
|
||||
if (elapsedWaitMs >= MAX_RESTORE_WAIT_MS) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Cold storage restore timed out after 48 hours for key: ${prep.key}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const waitMs = pollAttempt < 10 ? initialPollMs : steadyPollMs
|
||||
await sleep(waitMs)
|
||||
elapsedWaitMs += waitMs
|
||||
pollAttempt++
|
||||
}
|
||||
|
||||
await commitRestoreDbStateActivity({
|
||||
storageKeyId: prep.storageKeyId,
|
||||
})
|
||||
|
||||
await deleteArchiveOriginalAfterRestoreActivity({
|
||||
key: prep.key,
|
||||
})
|
||||
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : String(err)
|
||||
await revertArchiveOrRestoreStatusOnFailureActivity({
|
||||
taskId: task.id,
|
||||
storageKeyId,
|
||||
assetId: task.assetId,
|
||||
errorMessage,
|
||||
}).catch((revertErr) => {
|
||||
console.error('Failed to revert restore status on failure:', revertErr)
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,14 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
if (targetKey === key && (asset.storageKey?.isArchived || asset.status === 'archived')) {
|
||||
throw ApplicationFailure.create({
|
||||
message:
|
||||
'Original video file is archived and no proxy is available. Restore the asset to take screenshots.',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const screenshots = await takeScreenshotsActivity({
|
||||
taskId: task.id,
|
||||
assetKey: targetKey,
|
||||
|
||||
Reference in New Issue
Block a user