feat(storage): add archive storage support for assets

This commit is contained in:
yiling
2026-11-02 13:19:10 +08:00
parent 49a2d7c380
commit 9097ec12bb
100 changed files with 6180 additions and 170 deletions
+2
View File
@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
- **storage**: Add optional archive storage support (`local` folder/NAS or `s3` with configurable storage class and Glacier restore) allowing editors and owners to archive and restore original files while keeping previews, proxy streams, comments, and metadata available in main storage
### Fixed
### Changed
+1 -1
View File
@@ -25,7 +25,7 @@
Shumai is an open-source Frame.io alternative built for creative teams to collaborate and share media with ease:
* **S3-Compatible & Local Storage**: Store and serve creative assets securely using the local filesystem or any S3-compatible storage service, including AWS S3, Cloudflare R2, and MinIO.
* **S3-Compatible, Local & Cold Archive Storage**: Store and serve creative assets securely using the local filesystem or any S3-compatible storage service (AWS S3, Cloudflare R2, MinIO), with optional cold archive storage (`local` NAS or `s3` Glacier/storage classes) to offload original raw files while keeping previews and proxies hot.
* **Frame-by-Frame Annotations & Comments**: Leave precise feedback with frame-specific drawing tools and timestamped comments on both video and image assets.
* **Secure Sharing & Collections**: Create private share links and curated media collections for clients, stakeholders, and collaborators.
* **Granular Access Control**: Manage workspace permissions with team-level and project-level role-based access control.
+1 -1
View File
@@ -25,7 +25,7 @@
Shumai 是一个专为广告,短剧,漫剧等各类创意团队打造的开源协作管理平台,功能上类似阅流和分秒帧,提供了协作、审片和分享等各种功能:
* **支持 S3 和本地存储**:你可以把创意素材安全地存放在本地硬盘或者任意兼容 S3 的存储服务里,比如 阿里云 OSS 或 MinIO 等。
* **支持 S3、本地与冷归档存储**:你可以把创意素材安全地存放在本地硬盘或者任意兼容 S3 的存储服务里(如阿里云 OSS 或 MinIO 等),并支持配置独立的冷归档存储(本地 NAS 目录或 S3 归档存储类型)以卸载原始大文件,同时保留预览图和代理流随时可用。
* **帧级别标注和评论**:支持按帧进行精确反馈,同时支持直接在视频上进行标注,让团队成员能更精确地Get到你的想法。
* **安全的分享**:可以生成私密分享链接,同时还支持给分享的图片/视频添加自定义水印,并将水印配置保存为模板以便重复使用。方便给客户、同事和合作方查看。
* **细粒度权限控制**:支持按团队、项目设置角色权限,方便管理不同成员的访问范围。
+1
View File
@@ -97,6 +97,7 @@ apps/web/e2e/
| Image share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
| Video share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
| Owner views a file and it appears in recents | `tests/project/recents.spec.ts` |
| Owner archives a file to archive storage and restores it back to main storage | `tests/project/archive-restore.spec.ts` |
### file
| Test | File |
+9
View File
@@ -10,12 +10,16 @@ export default async function globalTeardown() {
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8')
let bucketName: string | undefined
let archiveRoot: string | undefined
content.split('\n').forEach((line) => {
const parts = line.split('=')
if (parts.length >= 2 && parts[0].trim() === 'S3_BUCKET') {
bucketName = parts.slice(1).join('=').trim()
}
if (parts.length >= 2 && parts[0].trim() === 'ARCHIVE_LOCAL_ROOT') {
archiveRoot = parts.slice(1).join('=').trim()
}
})
if (bucketName) {
@@ -26,6 +30,11 @@ export default async function globalTeardown() {
}
}
if (archiveRoot && fs.existsSync(archiveRoot)) {
console.log(`Cleaning up E2E archive storage root: ${archiveRoot}`)
fs.rmSync(archiveRoot, { recursive: true, force: true })
}
// Delete the temp .env.e2e file
fs.unlinkSync(envPath)
}
+9 -3
View File
@@ -13,8 +13,11 @@ async function start() {
// Generate a random S3 bucket name
const randomSuffix = randomBytes(4).toString('hex')
const bucketName = `shumai-e2e-${randomSuffix}`
const archiveRoot = path.resolve('data', `shumai-e2e-archive-${randomSuffix}`)
process.env.S3_BUCKET = bucketName
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
process.env.ARCHIVE_LOCAL_ROOT = archiveRoot
process.env.SHUMAI_SERVER_PORT = '5200'
process.env.BETTER_AUTH_URL = 'http://localhost:5200'
process.env.NODE_ENV = 'development'
@@ -22,9 +25,12 @@ async function start() {
process.env.ENABLE_EMBEDDING_AGENT = 'false'
// Write variables to .env.e2e file so the teardown can load them
const envContent = [`DATABASE_URL=${process.env.DATABASE_URL}`, `S3_BUCKET=${bucketName}`].join(
'\n',
)
const envContent = [
`DATABASE_URL=${process.env.DATABASE_URL}`,
`S3_BUCKET=${bucketName}`,
`ARCHIVE_STORAGE_BACKEND=local`,
`ARCHIVE_LOCAL_ROOT=${archiveRoot}`,
].join('\n')
fs.writeFileSync(path.resolve(currentDir, '.env.e2e'), envContent)
console.log(`E2E env file written. Starting Web App...`)
@@ -0,0 +1,65 @@
import { expect, test } from '../../fixtures'
import { fileCard } from '../../helpers/files'
test('owner archives a file to archive storage and restores it back to main storage', async ({
file,
prisma,
}) => {
const { page, projectId, fileName, fileId } = file
await page.goto(`/projects/${projectId}`)
const card = fileCard(page, fileName)
await expect(card).toBeVisible()
// 1. Archive via context menu + confirmation dialog
await card.click({ button: 'right' })
await page.getByTestId('context-menu-archive').click()
const confirmDialog = page.getByTestId('archive-confirm-dialog')
await expect(confirmDialog).toBeVisible()
await page.getByTestId('archive-confirm-submit').click()
// Wait for the DBOS archive workflow to finish and the card badge to settle to Archived
await expect(card.getByTestId('file-card-archived-badge')).toBeVisible({ timeout: 15000 })
const archivedAsset = await prisma.asset.findUniqueOrThrow({
where: { id: fileId },
include: { storageKey: true },
})
expect(archivedAsset.status).toBe('archived')
expect(archivedAsset.storageKey?.isArchived).toBe(true)
// 2. Open detail page and verify Archived header badge + disabled original download button
await card.dblclick()
await expect(page.getByTestId('detail-header-archived-badge')).toBeVisible()
await expect(page.getByTestId('default-viewer-download-button')).toBeDisabled()
// 3. Return to project file list and restore from archive
await page.goto(`/projects/${projectId}`)
await expect(card.getByTestId('file-card-archived-badge')).toBeVisible()
await card.click({ button: 'right' })
await page.getByTestId('context-menu-restore-archive').click()
await expect(confirmDialog).toBeVisible()
await page.getByTestId('archive-confirm-submit').click()
// Wait for the DBOS restore workflow to finish and the Archived badge to disappear
await expect(card.getByTestId('file-card-archived-badge')).not.toBeVisible({ timeout: 15000 })
await expect
.poll(
async () => {
const restored = await prisma.asset.findUnique({
where: { id: fileId },
include: { storageKey: true },
})
return {
status: restored?.status,
isArchived: restored?.storageKey?.isArchived,
}
},
{ timeout: 10000 },
)
.toEqual({ status: 'processed', isArchived: false })
})
+6 -2
View File
@@ -8,6 +8,7 @@ import index from '@shumai/webui/index.html'
import { initAgentWorkflows } from '@shumai/agent'
import { app } from '@shumai/api'
import { assetService } from '@shumai/core/src/asset/asset'
import { validateArchiveStorageConfig } from '@shumai/core/src/s3/archive-storage'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { initTranscodeWorkflows } from '@shumai/transcode'
import { workflowService } from '@shumai/workflow-core'
@@ -76,6 +77,7 @@ if (regenCmdIndex !== -1) {
}
async function run() {
validateArchiveStorageConfig()
// Initialize workflows and activities for local executor mode
initAgentWorkflows()
initTranscodeWorkflows()
@@ -99,13 +101,15 @@ async function run() {
}
}
let listenQueues: string[] = ['agent_queue', 'transcode_queue']
let listenQueues: string[] = ['agent_queue', 'transcode_queue', 'archive_queue']
if (workersOption === 'none') {
listenQueues = []
} else if (workersOption === 'agent' || workersOption === 'ai') {
listenQueues = ['agent_queue']
listenQueues = ['agent_queue', 'archive_queue']
} else if (workersOption === 'transcode') {
listenQueues = ['transcode_queue']
} else if (workersOption === 'archive') {
listenQueues = ['archive_queue']
}
workflowService.start(listenQueues)
+20 -1
View File
@@ -61,6 +61,24 @@ For example, if you deploy Shumai on a remote server at `http://123.456.7.8` and
- Set `SHUMAI_SERVER_PORT` to `3000`.
- Set `AWS_ENDPOINT_URL_S3` to `http://123.456.7.8:12345`.
### Archive Storage Config
Shumai supports configuring an optional **Archive Storage** tier (`local` NAS/directory or `s3` bucket/storage class) for moving original raw files while keeping proxies, previews, thumbnails, and metadata in main storage.
| Variable | Description | Example / Default |
| :------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------- |
| `ARCHIVE_STORAGE_BACKEND` | Archive storage type. Leave unset to disable archive storage, or set to `local` or `s3`. | Unset (disabled), `local`, or `s3` |
| `ARCHIVE_LOCAL_ROOT` | Required when `ARCHIVE_STORAGE_BACKEND=local`. Root directory (e.g., a mounted NAS folder) where archived original files are stored directly under `<ARCHIVE_LOCAL_ROOT>/<key>`. | `/mnt/nas/shumai-archive` |
| `ARCHIVE_AWS_ENDPOINT_URL_S3` | Optional custom S3 endpoint for archive storage when `ARCHIVE_STORAGE_BACKEND=s3` (independent of `AWS_ENDPOINT_URL_S3`). | `https://s3.us-east-1.amazonaws.com` |
| `ARCHIVE_S3_BUCKET` | Required when `ARCHIVE_STORAGE_BACKEND=s3`. Target S3 bucket for archived files (can be a dedicated bucket or the same bucket as `S3_BUCKET` with a cold storage class). | `shumai-archive` |
| `ARCHIVE_S3_ACCESS_KEY_ID` | Required when `ARCHIVE_STORAGE_BACKEND=s3`. S3 access key ID for archive storage. | `AKIA...` |
| `ARCHIVE_S3_SECRET_ACCESS_KEY` | Required when `ARCHIVE_STORAGE_BACKEND=s3`. S3 secret access key for archive storage. | `...` |
| `ARCHIVE_S3_REGION` | S3 region for archive storage when `ARCHIVE_STORAGE_BACKEND=s3`. | `auto` (default) |
| `ARCHIVE_S3_STORAGE_CLASS` | Optional S3 `StorageClass` header applied when archiving objects (accepts any standard or provider-specific class string; required and must not be `STANDARD` for same-bucket tiering). | `GLACIER_IR`, `GLACIER`, `DEEP_ARCHIVE`, `STANDARD_IA` |
| `ARCHIVE_S3_USE_RESTORE_OBJECT` | Controls whether S3 `RestoreObject` is called before reading archived objects (`auto`, `true`, or `false`). | `auto` (default) |
| `ARCHIVE_S3_RESTORE_DAYS` | Number of days a restored copy of a cold S3 object remains readable during restoration. | `1` (default) |
| `ARCHIVE_S3_RESTORE_TIER` | Optional S3 Glacier retrieval tier (`Expedited`, `Standard`, `Bulk`). Omitted when unset for S3-compatible providers that reject `GlacierJobParameters`. | Unset (default) |
---
## Workflow Config
@@ -69,8 +87,9 @@ Configures background worker execution, concurrency limits, and worker identity
| Variable | Description | Example / Default |
| :---------------------- | :-------------------------------------------------------------------------------------------------------------------------------- | :---------------- |
| `SHUMAI_WORKERS` | Queues listened to by the web server. Options: `all` (default), `none` (API/UI only), `agent` (or `ai`), `transcode`. | `all` (default) |
| `SHUMAI_WORKERS` | Queues listened to by the web server. Options: `all` (default), `none` (API/UI only), `agent` (or `ai`), `transcode`, `archive`. | `all` (default) |
| `CONCURRENCY_TRANSCODE` | Maximum concurrent media transcoding tasks executed by workers. | `1` (default) |
| `CONCURRENCY_ARCHIVE` | Maximum concurrent archive and restore tasks executed by workers. | `5` (default) |
| `CONCURRENCY_AGENT` | Maximum concurrent AI tasks executed by workers. Set to `1` when running local `embedding-server`. | `5` (default) |
| `SHUMAI_WORKER_ID` | Optional explicit instance ID for worker replicas in multi-node deployments (auto-derived from hostname and process ID if unset). | `worker-1` |
| `POD_NAME` | Kubernetes pod name, used to provide stable per-pod worker identity across StatefulSet restarts. | `transcode-pod-0` |
@@ -3,7 +3,7 @@ import * as path from 'path'
import { z } from 'zod'
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
import type { User } from '@shumai/db'
import { prisma, type User } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { storageBucket } from '@shumai/core/src/asset-read'
import { s3Service } from '@shumai/core/src/s3/s3'
@@ -54,6 +54,26 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
type: ResourceType.Asset,
id: owningAssetId,
})
const sk = await prisma.storageKey.findUnique({
where: { key },
include: {
assets: {
where: { isDeleted: false },
select: { status: true },
},
},
})
if (
sk &&
(sk.isArchived ||
sk.assets.some(
(a) => a.status === 'archiving' || a.status === 'archived' || a.status === 'restoring',
))
) {
throw new Error(
`Original file for storage key "${key}" is archived. Restore the asset first or download its proxy using assetIds with proxy: true.`,
)
}
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
const saved = await saveToSandbox(key, filename)
return {
@@ -67,6 +67,7 @@ describe('operation-backed agent tools', () => {
.map((t) => t.name)
.sort(),
).toEqual([
'archive_assets',
'copy_assets',
'create_comment',
'create_file',
@@ -87,6 +88,7 @@ describe('operation-backed agent tools', () => {
'remove_version',
'rename_asset',
'resolve_comment',
'restore_archived_assets',
'search_assets',
'update_asset_metadata',
])
+1
View File
@@ -28,6 +28,7 @@ describe('authn api', () => {
expect(await res.json()).toEqual({
initialized: true,
demoMode: false,
archiveStorageEnabled: false,
})
})
})
+2
View File
@@ -2,6 +2,7 @@ import { Hono } from 'hono'
import { teamService } from '@shumai/core/src/team/team'
import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth'
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
import { ulid } from 'ulid'
@@ -19,6 +20,7 @@ const route = app
return c.json({
initialized: info.initialized,
demoMode: info.demoMode,
archiveStorageEnabled: isArchiveStorageEnabled(),
})
})
.get('/me', async (c) => {
+62
View File
@@ -11,8 +11,10 @@ import { authMiddleware } from './middleware/auth'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import type { AssetInfo } from '@shumai/dtos'
import {
archiveAssetsOp,
renameAssetOp,
resolveCommentOp,
restoreArchivedAssetsOp,
runOperation,
updateAssetMetadataOp,
} from '@shumai/core/src/operations'
@@ -908,4 +910,64 @@ describe('file api', () => {
mockVariant.mockRestore()
})
})
describe('POST /files/archive and POST /files/restore-archive routes', () => {
const validUlid = '01ARZ3NDEKTSV4RRFFQ69G5FAV'
it('archives assets via archiveAssetsOp', async () => {
vi.mocked(runOperation).mockResolvedValueOnce({
archivedAssetIds: [validUlid],
taskIds: ['task-arch-1'],
skippedCount: 0,
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/files/archive', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: [validUlid] }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({
archivedAssetIds: [validUlid],
taskIds: ['task-arch-1'],
skippedCount: 0,
})
expect(runOperation).toHaveBeenCalledWith(
archiveAssetsOp,
{ userId: 'user1', via: 'api' },
{ assetIds: [validUlid] },
)
})
it('restores archived assets via restoreArchivedAssetsOp', async () => {
vi.mocked(runOperation).mockResolvedValueOnce({
restoredAssetIds: [validUlid],
taskIds: ['task-rest-1'],
skippedCount: 0,
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/files/restore-archive', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: [validUlid] }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({
restoredAssetIds: [validUlid],
taskIds: ['task-rest-1'],
skippedCount: 0,
})
expect(runOperation).toHaveBeenCalledWith(
restoreArchivedAssetsOp,
{ userId: 'user1', via: 'api' },
{ assetIds: [validUlid] },
)
})
})
})
+31 -1
View File
@@ -6,16 +6,20 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import {
archiveAssetsOp,
renameAssetOp,
resolveCommentOp,
restoreArchivedAssetsOp,
runOperation,
updateAssetMetadataOp,
} from '@shumai/core/src/operations'
import {
archiveAssetsRequestSchema,
createCommentRequestSchema,
deleteFilesRequestSchema,
batchGetFilesRequestSchema,
paginationParamsSchema,
restoreArchivedAssetsRequestSchema,
restoreFilesRequestSchema,
updateAssetMetadataRequestSchema,
updateAssetOrderRequestSchema,
@@ -343,6 +347,28 @@ const route = new Hono<{ Variables: { user: User } }>()
await assetService.restoreAssets(req.ids)
return c.body(null, 204)
})
.post('/files/archive', zValidator('json', archiveAssetsRequestSchema), async (c) => {
const req = c.req.valid('json')
const result = await runOperation(
archiveAssetsOp,
{ userId: c.get('user').id, via: 'api' },
{ assetIds: req.ids },
)
return c.json(result)
})
.post(
'/files/restore-archive',
zValidator('json', restoreArchivedAssetsRequestSchema),
async (c) => {
const req = c.req.valid('json')
const result = await runOperation(
restoreArchivedAssetsOp,
{ userId: c.get('user').id, via: 'api' },
{ assetIds: req.ids },
)
return c.json(result)
},
)
.post('/teams/:teamId/files', zValidator('form', uploadFileRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
@@ -425,7 +451,11 @@ const route = new Hono<{ Variables: { user: User } }>()
// 4. Generate download links
const files = await assetService.getDownloadLinks(req.ids)
return c.json({ files })
const skippedArchivedCount = files.skippedArchivedCount
return c.json({
files,
...(skippedArchivedCount !== undefined ? { skippedArchivedCount } : {}),
})
})
.post(
'/files/download-url',
+2
View File
@@ -53,6 +53,7 @@ describe('MCP server', () => {
const { tools } = await client.listTools()
expect(tools.map((t) => t.name).sort()).toEqual([
'archive_assets',
'complete_upload',
'copy_assets',
'create_comment',
@@ -74,6 +75,7 @@ describe('MCP server', () => {
'remove_version',
'rename_asset',
'resolve_comment',
'restore_archived_assets',
'search_assets',
'update_asset_metadata',
])
@@ -217,6 +217,51 @@ describe('download_asset Operation', () => {
})
})
it('rejects downloading original of an archived asset with 409, while allowing proxy: true when a proxy exists', async () => {
const clip = await createFile('archived.mov', {
key: 'files/up-arch/archived.mov',
media: {
duration: 5,
filesize: 512,
frames: 150,
finishedAt: '2026-01-01T00:00:00Z',
metadata: null,
original: null,
imageTranscodes: [],
proxyType: 'video',
videoTranscodes: [
{
resolution: '720p',
key: 'files/up-arch/archived-720p.mp4',
width: 1280,
height: 720,
},
],
},
})
await prisma.asset.update({
where: { id: clip.id },
data: { status: 'archived' },
})
// proxy: false is blocked with 409
await expect(
runOperation(downloadAssetOp, as(owner), { assetIds: [clip.id], proxy: false }),
).rejects.toMatchObject({ status: 409 })
// proxy: true succeeds using the MP4 proxy in main storage
const { files } = await runOperation(downloadAssetOp, as(owner), {
assetIds: [clip.id],
proxy: true,
})
expect(files).toHaveLength(1)
expect(files[0]).toMatchObject({
assetId: clip.id,
kind: 'proxy',
name: 'archived.mp4',
})
})
it.each([[[]], [Array.from({ length: 51 }, (_, i) => `a-${i}`)]])(
'rejects %# asset ID lists outside 1 to 50',
async (assetIds) => {
@@ -30,6 +30,9 @@ export function proxyKeyOf(media: PrismaJson.MediaInfo | null): string | undefin
if (media.proxyType === 'video' || media.videoTranscodes?.length || media.videoPreview?.key) {
return media.videoTranscodes?.[0]?.key || media.videoPreview?.key || undefined
}
if (media.pdfTranscode?.key && media.pdfTranscode.key !== media.original?.key) {
return media.pdfTranscode.key
}
return media.original?.key || undefined
}
@@ -66,6 +69,19 @@ export class AssetDownloadService {
})
}
const isOriginal = key === originalKey
const isArchived =
asset.status === 'archiving' ||
asset.status === 'archived' ||
asset.status === 'restoring' ||
Boolean(asset.storageKey?.isArchived)
if (isArchived && (!opts.proxy || isOriginal)) {
throw new HTTPException(409, {
message: opts.proxy
? `Asset ${assetId} ("${asset.name}") is archived and has no proxy file to download. Restore the asset first.`
: `Original file for asset ${assetId} ("${asset.name}") is archived. Restore the asset or request proxy: true to download its proxy.`,
})
}
const name = nameForKey(asset.name || 'file', key, isOriginal)
const bucket = storageBucket()
@@ -244,6 +244,60 @@ describe('AssetReadService', () => {
expect(s3Service.getObject).not.toHaveBeenCalled()
expect(outcome.status === 'ready' && outcome.result.text?.content).toBe('')
})
it('rejects reading raw text or native PDF pages when the original is archived, while allowing proxy.pdf', async () => {
const archivedText = await createFile('notes.md', {
mediaType: 'text/markdown',
key: 'raw/notes.md',
status: 'archived',
})
await expect(
assetReadService.read(
user(owner),
{ assetId: archivedText.id, docConfig: { mode: 'text' } },
now,
),
).rejects.toMatchObject({
status: 400,
message: expect.stringContaining('is archived in cold storage'),
})
const archivedNativePdf = await createFile('report.pdf', {
mediaType: 'application/pdf',
key: 'raw/report.pdf',
status: 'archived',
media: {
proxyType: 'pdf',
pdfTranscode: { key: 'raw/report.pdf', numPages: 3 },
} as unknown as PrismaJson.MediaInfo,
})
await expect(
assetReadService.read(
user(owner),
{ assetId: archivedNativePdf.id, docConfig: { mode: 'pages', startPage: 1, endPage: 1 } },
now,
),
).rejects.toMatchObject({
status: 400,
message: expect.stringContaining('is archived in cold storage'),
})
const archivedOfficeDoc = await createFile('deck.pptx', {
mediaType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
key: 'raw/deck.pptx',
status: 'archived',
media: {
proxyType: 'pdf',
pdfTranscode: { key: 'transcoded/deck/proxy.pdf', numPages: 3 },
} as unknown as PrismaJson.MediaInfo,
})
const officeOutcome = await assetReadService.read(
user(owner),
{ assetId: archivedOfficeDoc.id, docConfig: { mode: 'pages', startPage: 1, endPage: 1 } },
now,
)
expect(officeOutcome.status).toBe('pending')
})
})
describe('render tasks', () => {
@@ -55,6 +55,11 @@ function toReadable(asset: AssetRecord): ReadableAsset {
filenameLower: asset.name?.toLowerCase() || '',
storageKey: asset.storageKey?.key ?? null,
media: asset.media as PrismaJson.MediaInfo | null,
isArchived:
asset.status === 'archiving' ||
asset.status === 'archived' ||
asset.status === 'restoring' ||
Boolean(asset.storageKey?.isArchived),
}
}
@@ -107,9 +107,23 @@ export const documentReader: AssetReader<'document'> = {
`Asset "${asset.name}" is a binary PDF/document and cannot be read as raw text. Please call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: ... } to view its visual pages.`,
)
}
if (asset.isArchived) {
throw badRequest(
`Asset "${asset.name}" is archived in cold storage and cannot be read as raw text. Restore the asset first, or use docConfig: { mode: "pages", startPage: 1, endPage: ... } if it has a generated PDF proxy.`,
)
}
return
}
if (
asset.isArchived &&
(!asset.media?.pdfTranscode?.key || asset.media.pdfTranscode.key === asset.storageKey)
) {
throw badRequest(
`Asset "${asset.name}" is a native PDF whose original file is archived in cold storage. Restore the asset first to render its pages.`,
)
}
if (startPage === null || endPage === null) {
throw badRequest('startPage and endPage are required when docConfig mode is "pages".')
}
@@ -1,6 +1,6 @@
import { WorkflowTaskType } from '@shumai/db'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import type { AssetReader } from '../types'
import { badRequest, type AssetReader } from '../types'
/** Images (including PSD): the web proxy, or a copy with the annotation drawn on top. */
export const imageReader: AssetReader<'image'> = {
@@ -16,7 +16,13 @@ export const imageReader: AssetReader<'image'> = {
validate() {},
async plan(asset, _options, { annotation }) {
const key = asset.media?.imageTranscodes?.[0]?.key || asset.storageKey
const proxyKey = asset.media?.imageTranscodes?.[0]?.key
if (!proxyKey && asset.isArchived) {
throw badRequest(
`Asset "${asset.name}" is archived in cold storage and has no web image proxy. Restore the asset first.`,
)
}
const key = proxyKey || asset.storageKey
if (!key) {
throw new Error('No media content found for this asset.')
}
+2
View File
@@ -15,6 +15,8 @@ export interface ReadableAsset {
filenameLower: string
storageKey: string | null
media: PrismaJson.MediaInfo | null
/** True when the original raw file is archived, archiving, or restoring. */
isArchived?: boolean
}
export interface ReadAnnotation {
@@ -0,0 +1,420 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import {
AssetStatus,
AssetType,
prisma,
WorkflowTaskStatus,
WorkflowTaskType,
type User,
} from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { projectService } from '@shumai/core/src/project/project'
import { assetService } from './asset'
import { searchService } from '../search/search'
import { resetArchiveStorageServiceForTests, getArchiveStorageService } from '../s3/archive-storage'
describe('AssetService Archive & Restore', () => {
setupTestDbHooks()
const archiveRoot = path.join(process.cwd(), 'data-test-asset-archive')
let originalEnv: NodeJS.ProcessEnv
let owner: User
let teamId: string
let projectId: string
let rootFolderId: string
beforeEach(async () => {
originalEnv = { ...process.env }
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
process.env.ARCHIVE_LOCAL_ROOT = archiveRoot
resetArchiveStorageServiceForTests()
if (fs.existsSync(archiveRoot)) {
fs.rmSync(archiveRoot, { recursive: true, force: true })
}
owner = await prisma.user.create({
data: { name: 'Archive Owner', email: 'archive-owner@test.com', password: 'pw' },
})
const team = await prisma.team.create({ data: { name: 'Archive Team' } })
teamId = team.id
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
const project = await projectService.createProject(owner, { teamId, name: 'Archive Project' })
projectId = project.id
rootFolderId = project.rootFolder!
})
afterEach(() => {
process.env = originalEnv
resetArchiveStorageServiceForTests()
if (fs.existsSync(archiveRoot)) {
fs.rmSync(archiveRoot, { recursive: true, force: true })
}
})
async function createProcessedFile(params: {
name: string
parentId?: string
key: string
media?: Partial<PrismaJson.MediaInfo>
isArchived?: boolean
status?: AssetStatus
}) {
const asset = await assetService.createAsset({
name: params.name,
type: 'file',
parentId: params.parentId ?? rootFolderId,
projectId,
key: params.key,
sizeByte: 1024,
contentType: 'video/mp4',
creatorId: owner.id,
})
if (params.isArchived) {
await prisma.storageKey.update({
where: { key: params.key },
data: { isArchived: true },
})
}
const fullMedia: PrismaJson.MediaInfo | undefined = params.media
? {
duration: 0,
filesize: 1024,
frames: 0,
finishedAt: '2026-01-01T00:00:00Z',
metadata: null,
original: null,
imageTranscodes: [],
videoTranscodes: [],
...params.media,
}
: undefined
await prisma.asset.update({
where: { id: asset.id },
data: {
status: params.status ?? (params.isArchived ? AssetStatus.archived : AssetStatus.processed),
...(fullMedia ? { media: fullMedia } : {}),
},
})
return prisma.asset.findUniqueOrThrow({
where: { id: asset.id },
include: { storageKey: true },
})
}
it('rejects archive and restore when ARCHIVE_STORAGE_BACKEND is not configured', async () => {
delete process.env.ARCHIVE_STORAGE_BACKEND
resetArchiveStorageServiceForTests()
const file = await createProcessedFile({
name: 'clip.mp4',
key: 'files/01TEST/clip.mp4',
})
await expect(assetService.archiveAssets([file.id])).rejects.toMatchObject({
status: 400,
message: 'Archive storage is not configured',
})
await expect(assetService.restoreArchivedAssets([file.id])).rejects.toMatchObject({
status: 400,
message: 'Archive storage is not configured',
})
})
it('archives and restores standalone files, deduplicating shared StorageKey across copies and updating all copies', async () => {
const file = await createProcessedFile({
name: 'shared.mp4',
key: 'files/01SHARED/shared.mp4',
})
const subFolder = await assetService.createAsset({
name: 'Copies',
type: 'folder',
parentId: rootFolderId,
projectId,
creatorId: owner.id,
})
const [copiedId] = await assetService.copyAssets({
assetIds: [file.id],
newParentId: subFolder.id,
creatorId: owner.id,
withComments: false,
})
// Archive original -> both original and copy share the StorageKey, so both transition to 'archiving' with 1 WorkflowTask
const archiveRes = await assetService.archiveAssets([file.id, copiedId])
expect(archiveRes.archivedAssetIds.sort()).toEqual([file.id, copiedId].sort())
expect(archiveRes.taskIds).toHaveLength(1)
expect(archiveRes.skippedCount).toBe(0)
const updatedRows = await prisma.asset.findMany({
where: { id: { in: [file.id, copiedId] } },
})
expect(updatedRows.map((r) => r.status)).toEqual([AssetStatus.archiving, AssetStatus.archiving])
const task = await prisma.workflowTask.findUniqueOrThrow({
where: { id: archiveRes.taskIds[0] },
})
expect(task.type).toBe(WorkflowTaskType.archive_asset)
expect(task.payload?.archive?.storageKeyId).toBe(file.storageKeyId)
// Simulate workflow completion -> StorageKey.isArchived = true, Asset.status = 'archived'
await prisma.storageKey.update({
where: { id: file.storageKeyId! },
data: { isArchived: true },
})
await prisma.asset.updateMany({
where: { storageKeyId: file.storageKeyId! },
data: { status: AssetStatus.archived },
})
await prisma.workflowTask.update({
where: { id: task.id },
data: { status: WorkflowTaskStatus.completed },
})
// Restore from archive via the copy -> both transition to 'restoring' with 1 restore_asset task
const restoreRes = await assetService.restoreArchivedAssets([copiedId])
expect(restoreRes.restoredAssetIds.sort()).toEqual([file.id, copiedId].sort())
expect(restoreRes.taskIds).toHaveLength(1)
const restoringRows = await prisma.asset.findMany({
where: { id: { in: [file.id, copiedId] } },
})
expect(restoringRows.map((r) => r.status)).toEqual([
AssetStatus.restoring,
AssetStatus.restoring,
])
})
it('recursively archives and restores folders and version stacks without mutating folder or version_stack DB status', async () => {
const folder = await assetService.createAsset({
name: 'Shoot Day 1',
type: 'folder',
parentId: rootFolderId,
projectId,
creatorId: owner.id,
})
const v1 = await createProcessedFile({
name: 'cut_v1.mp4',
parentId: folder.id,
key: 'files/01V1/cut_v1.mp4',
})
const v2 = await createProcessedFile({
name: 'cut_v2.mp4',
parentId: folder.id,
key: 'files/01V2/cut_v2.mp4',
})
// Stack v2 onto v1 to create a version_stack inside folder
await assetService.reparentAssets({
assetIds: [v2.id],
newParentId: v1.id,
creatorId: owner.id,
})
const v1Reloaded = await prisma.asset.findUniqueOrThrow({ where: { id: v1.id } })
const stackId = v1Reloaded.parentId!
const stackRowBefore = await prisma.asset.findUniqueOrThrow({ where: { id: stackId } })
expect(stackRowBefore.type).toBe(AssetType.version_stack)
expect(stackRowBefore.status).toBe(AssetStatus.uploaded)
// Archive the parent folder
const archiveRes = await assetService.archiveAssets([folder.id])
expect(archiveRes.archivedAssetIds.sort()).toEqual([v1.id, v2.id].sort())
expect(archiveRes.taskIds).toHaveLength(2)
// Verify folder and version_stack DB statuses remain 'uploaded'
const folderAfter = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
const stackAfter = await prisma.asset.findUniqueOrThrow({ where: { id: stackId } })
expect(folderAfter.status).toBe(AssetStatus.uploaded)
expect(stackAfter.status).toBe(AssetStatus.uploaded)
// Mark both versions as 'archived' and verify version_stack AssetInfo reflects latestVersion status ('archived')
await prisma.storageKey.updateMany({
where: { id: { in: [v1.storageKeyId!, v2.storageKeyId!] } },
data: { isArchived: true },
})
await prisma.asset.updateMany({
where: { id: { in: [v1.id, v2.id] } },
data: { status: AssetStatus.archived },
})
const stackInfo = await assetService.getAsset({ assetId: stackId })
expect(stackInfo.status).toBe(AssetStatus.archived)
expect(stackInfo.versionStack?.versions.map((v) => v.status)).toEqual([
AssetStatus.archived,
AssetStatus.archived,
])
})
it('omits original.url and native PDF pdfTranscode.url when archived, while keeping Office proxy.pdf url', async () => {
const nativePdf = await createProcessedFile({
name: 'script.pdf',
key: 'files/01PDF/script.pdf',
isArchived: true,
media: {
proxyType: 'pdf',
original: { key: 'files/01PDF/script.pdf', filesizeInBytes: 1024, codec: '' },
pdfTranscode: { key: 'files/01PDF/script.pdf' },
videoTranscodes: [],
imageTranscodes: [],
},
})
const officeDoc = await createProcessedFile({
name: 'deck.pptx',
key: 'files/01PPTX/deck.pptx',
isArchived: true,
media: {
proxyType: 'pdf',
original: { key: 'files/01PPTX/deck.pptx', filesizeInBytes: 2048, codec: '' },
pdfTranscode: { key: 'files/01PPTX/proxy.pdf' },
videoTranscodes: [],
imageTranscodes: [],
},
})
const nativePdfInfo = await assetService.getAsset({ assetId: nativePdf.id })
expect(nativePdfInfo.media?.original?.key).toBe('files/01PDF/script.pdf')
expect(nativePdfInfo.media?.pdfTranscode?.url).toBeUndefined()
const officeDocInfo = await assetService.getAsset({ assetId: officeDoc.id })
expect(officeDocInfo.media?.original?.key).toBe('files/01PPTX/deck.pptx')
expect(officeDocInfo.media?.pdfTranscode?.url).toBeDefined()
})
it('blocks original file download via getDownloadUrl with 409 when archived, while allowing proxy keys, and skips archived files in getDownloadLinks', async () => {
const archivedVideo = await createProcessedFile({
name: 'archived.mp4',
key: 'files/01VID/archived.mp4',
isArchived: true,
media: {
proxyType: 'video',
original: { key: 'files/01VID/archived.mp4', filesizeInBytes: 1024, codec: 'h264' },
videoTranscodes: [
{
resolution: '720p',
key: 'files/01VID/archived-720p.mp4',
width: 1280,
height: 720,
},
],
imageTranscodes: [],
},
})
const hotVideo = await createProcessedFile({
name: 'hot.mp4',
key: 'files/01HOT/hot.mp4',
isArchived: false,
})
// Original key is blocked with 409
await expect(
assetService.getDownloadUrl(archivedVideo.id, 'files/01VID/archived.mp4'),
).rejects.toMatchObject({
status: 409,
})
// Proxy key in same asset folder is allowed
const proxyUrl = await assetService.getDownloadUrl(
archivedVideo.id,
'files/01VID/archived-720p.mp4',
)
expect(proxyUrl).toContain('archived-720p.mp4')
// Batch getDownloadLinks skips archivedVideo and returns hotVideo + skippedArchivedCount = 1
const links = await assetService.getDownloadLinks([archivedVideo.id, hotVideo.id])
expect(links).toHaveLength(1)
expect(links[0].id).toBe(hotVideo.id)
expect(links.skippedArchivedCount).toBe(1)
})
it('preserves archived status when restoring from Trash and when copying assets, and purges archive storage during GC', async () => {
const archivedFile = await createProcessedFile({
name: 'cold.mp4',
key: 'files/01COLD/cold.mp4',
isArchived: true,
})
// Write physical file into local archive storage
const archiveStorage = getArchiveStorageService()
await archiveStorage.uploadStream(
'files/01COLD/cold.mp4',
new ReadableStream({
start(c) {
c.enqueue(new TextEncoder().encode('cold bytes'))
c.close()
},
}),
10,
'video/mp4',
)
// Copy archived asset -> new copy has status 'archived'
const targetFolder = await assetService.createAsset({
name: 'Target',
type: 'folder',
parentId: rootFolderId,
projectId,
creatorId: owner.id,
})
const [copiedId] = await assetService.copyAssets({
assetIds: [archivedFile.id],
newParentId: targetFolder.id,
creatorId: owner.id,
withComments: false,
})
const copiedRow = await prisma.asset.findUniqueOrThrow({ where: { id: copiedId } })
expect(copiedRow.status).toBe(AssetStatus.archived)
// Delete and restore from Trash -> status returns to 'archived' (not 'processed')
await assetService.deleteAssets([archivedFile.id])
const trashedRow = await prisma.asset.findUniqueOrThrow({ where: { id: archivedFile.id } })
expect(trashedRow.status).toBe(AssetStatus.trashed)
await assetService.restoreAssets([archivedFile.id])
const restoredFromTrash = await prisma.asset.findUniqueOrThrow({
where: { id: archivedFile.id },
})
expect(restoredFromTrash.status).toBe(AssetStatus.archived)
// Filter via SearchService with isArchived condition
const archivedSearch = await searchService.search(rootFolderId, {
operator: 'AND',
conditions: [{ field: 'isArchived', operator: 'eq', value: true }],
recursively: true,
isSemantic: false,
})
expect(archivedSearch.data.map((d) => d.id).sort()).toEqual([archivedFile.id, copiedId].sort())
const unarchivedSearch = await searchService.search(rootFolderId, {
operator: 'AND',
conditions: [{ field: 'isArchived', operator: 'eq', value: false }],
recursively: true,
isSemantic: false,
})
expect(unarchivedSearch.data.map((d) => d.id)).toEqual([])
// Purge both assets and run GC -> file is deleted from archive storage too
await assetService.deleteAssets([archivedFile.id, copiedId])
await prisma.storageKey.update({
where: { id: archivedFile.storageKeyId! },
data: { createdAt: new Date(Date.now() - 60_000) },
})
await assetService.emptyTrash(projectId)
await expect(archiveStorage.headObject('files/01COLD/cold.mp4')).rejects.toThrow(/NoSuchKey/)
const skAfter = await prisma.storageKey.findUnique({
where: { id: archivedFile.storageKeyId! },
})
expect(skAfter).toBeNull()
})
})
+520 -26
View File
@@ -1,6 +1,7 @@
import { cancelWorkflowTask, prisma } from '@shumai/db'
import {
AncestorFolder,
ArchiveAssetsResponse,
AssetInfo,
AttachmentInfo,
ChildPreview,
@@ -14,6 +15,7 @@ import {
ListChildrenRequest,
PreviewInfo,
ReparentAssetsRequest,
RestoreArchivedAssetsResponse,
UpdateAssetNameRequest,
UpdateAssetOrderRequest,
AssetUserInfo,
@@ -42,6 +44,10 @@ import { HTTPException } from 'hono/http-exception'
import { logger } from '@shumai/core/src/logger'
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
getArchiveStorageService,
isArchiveStorageEnabled,
} from '@shumai/core/src/s3/archive-storage'
import {
ensureJpegInStorage,
getJpegKeyForWebp,
@@ -409,7 +415,7 @@ export class AssetService {
const assetsToCopy = await tx.asset.findMany({
where: { id: { in: req.assetIds } },
include: { project: { include: { team: true } } },
include: { project: { include: { team: true } }, storageKey: true },
})
if (assetsToCopy.length !== req.assetIds.length) {
@@ -488,6 +494,17 @@ export class AssetService {
creatorId?: string,
withComments: boolean = false,
): Promise<Asset> {
if (asset.status === AssetStatus.archiving || asset.status === AssetStatus.restoring) {
throw new HTTPException(409, {
message: 'Cannot copy an asset while it is being archived or restored',
})
}
const copiedStatus =
asset.type === AssetType.file && asset.storageKey?.isArchived
? AssetStatus.archived
: asset.status
const newAsset = await tx.asset.create({
data: {
name: asset.name,
@@ -496,7 +513,7 @@ export class AssetService {
mediaType: asset.mediaType,
fileCount: asset.fileCount,
sizeByte: asset.sizeByte,
status: asset.status,
status: copiedStatus,
transcodeTaskId: asset.transcodeTaskId,
media: asset.media || undefined,
isDeleted: asset.isDeleted,
@@ -515,9 +532,10 @@ export class AssetService {
await this.copyComments(tx, asset.id, newAsset.id, projectId, creatorId)
}
if (asset.type === AssetType.folder) {
if (asset.type === AssetType.folder || asset.type === AssetType.version_stack) {
const children = await tx.asset.findMany({
where: { parentId: asset.id },
include: { storageKey: true },
orderBy: { sortIndex: 'asc' },
})
for (const child of children) {
@@ -1605,7 +1623,9 @@ export class AssetService {
// 1. Find storage keys with no associated assets and older than 24 hours
// using FOR UPDATE SKIP LOCKED to ensure multiple servers don't pick up the same keys.
const lockedKeys = await this.prismaClient.$queryRaw<{ id: string; key: string }[]>`
const lockedKeys = await this.prismaClient.$queryRaw<
{ id: string; key: string; isArchived: boolean }[]
>`
WITH to_purge AS (
SELECT id FROM storage_keys sk
WHERE NOT EXISTS (SELECT 1 FROM assets a WHERE a.storage_key_id = sk.id)
@@ -1616,17 +1636,30 @@ export class AssetService {
)
UPDATE storage_keys SET status = 'purging', updated_at = NOW()
WHERE id IN (SELECT id FROM to_purge)
RETURNING id, key;
RETURNING id, key, is_archived AS "isArchived";
`
if (lockedKeys.length === 0) return
let physicalFilesDeleted = 0
let purgedCount = 0
const archiveEnabled = isArchiveStorageEnabled()
for (const sk of lockedKeys) {
try {
// Physically delete from S3
if (sk.isArchived && !archiveEnabled) {
logger.warn(
{ storageKeyId: sk.id, key: sk.key },
'Skipping purge of archived storage key because archive storage is not configured',
)
await this.prismaClient.storageKey.update({
where: { id: sk.id },
data: { status: 'active' },
})
continue
}
// Physically delete proxies (and unarchived original) from main storage
const parts = sk.key.split('/')
if (parts.length > 2) {
const prefix = parts.slice(0, parts.length - 1).join('/') + '/'
@@ -1637,6 +1670,15 @@ export class AssetService {
physicalFilesDeleted += count
}
// Also delete original raw file from archive storage when archive storage is separate
if (archiveEnabled) {
const archiveStorage = getArchiveStorageService()
if (!archiveStorage.isSameS3Target) {
const archiveDeleted = await archiveStorage.deleteObject(sk.key)
physicalFilesDeleted += archiveDeleted
}
}
// Delete from database
await this.prismaClient.storageKey.delete({
where: { id: sk.id },
@@ -1663,7 +1705,7 @@ export class AssetService {
await this.prismaClient.$transaction(async (tx) => {
const a = await tx.asset.findUnique({
where: { id },
include: { project: { include: { team: true } } },
include: { project: { include: { team: true } }, storageKey: true },
})
if (!a) throw new Error('Asset not found')
if (!a.parentId) throw new Error('Asset has no parent')
@@ -1687,7 +1729,25 @@ export class AssetService {
if (descendantIds.length > 0) {
await tx.asset.updateMany({
where: { id: { in: descendantIds } },
data: { isDeleted: false },
data: { isDeleted: false, deletedAt: null },
})
await tx.asset.updateMany({
where: {
id: { in: descendantIds },
type: AssetType.file,
status: AssetStatus.trashed,
storageKey: { isArchived: true },
},
data: { status: AssetStatus.archived },
})
await tx.asset.updateMany({
where: {
id: { in: descendantIds },
type: AssetType.file,
status: AssetStatus.trashed,
storageKey: { isArchived: false },
},
data: { status: AssetStatus.processed },
})
}
@@ -1724,6 +1784,16 @@ export class AssetService {
}
}
const activeArchiveTask = await tx.workflowTask.findFirst({
where: {
assetId: a.id,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
type: {
in: [WorkflowTaskType.archive_asset, WorkflowTaskType.restore_asset],
},
},
})
const activeTask = await tx.workflowTask.findFirst({
where: {
assetId: a.id,
@@ -1743,11 +1813,22 @@ export class AssetService {
},
})
let restoredStatus: AssetStatus = AssetStatus.processed
if (activeArchiveTask?.type === WorkflowTaskType.archive_asset) {
restoredStatus = AssetStatus.archiving
} else if (activeArchiveTask?.type === WorkflowTaskType.restore_asset) {
restoredStatus = AssetStatus.restoring
} else if (activeTask) {
restoredStatus = AssetStatus.processing
} else if (a.type === AssetType.file && a.storageKey?.isArchived) {
restoredStatus = AssetStatus.archived
}
await tx.asset.update({
where: { id: a.id },
data: {
isDeleted: false,
status: activeTask ? AssetStatus.processing : AssetStatus.processed,
status: restoredStatus,
deletedAt: null,
},
})
@@ -2352,6 +2433,7 @@ export class AssetService {
current: i === 0,
id: v.id,
name: v.name,
status: v.status,
previewUrl: preview?.thumbnailUrl || null,
createdAt: v.createdAt.toISOString(),
creator: v.creator
@@ -2445,7 +2527,15 @@ export class AssetService {
}
}
let media = latestVersion.media as PrismaJson.MediaInfo | null
const isOriginalUnavailable =
latestVersion.status === AssetStatus.archiving ||
latestVersion.status === AssetStatus.archived ||
latestVersion.status === AssetStatus.restoring ||
Boolean(latestVersion.storageKey?.isArchived)
let media = latestVersion.media
? (structuredClone(latestVersion.media) as PrismaJson.MediaInfo)
: null
if (media && media.videoPreview?.key) {
media.videoPreview.url = await s3Service.presign(
process.env.S3_BUCKET || 'shumai',
@@ -2454,11 +2544,15 @@ export class AssetService {
)
}
if (media && media.pdfTranscode?.key) {
media.pdfTranscode.url = await s3Service.presign(
process.env.S3_BUCKET || 'shumai',
media.pdfTranscode.key,
'GET',
)
if (isOriginalUnavailable && media.pdfTranscode.key === latestVersion.storageKey?.key) {
delete media.pdfTranscode.url
} else {
media.pdfTranscode.url = await s3Service.presign(
process.env.S3_BUCKET || 'shumai',
media.pdfTranscode.key,
'GET',
)
}
}
if (media && media.isHls && media.hls?.key) {
media.hls.url = `/api/files/${latestVersion.id}/m3u8/master.m3u8`
@@ -2523,6 +2617,7 @@ export class AssetService {
id: string
version: number
name: string
status: AssetStatus
previewUrl: string | null
createdAt: string
creator: { id: string; name: string | null; image?: string | null } | null
@@ -2546,6 +2641,7 @@ export class AssetService {
id: v.id,
version: versions.length - i,
name: v.name,
status: v.status,
previewUrl: preview?.thumbnailUrl || null,
createdAt: v.createdAt.toISOString(),
creator: v.creator
@@ -2605,7 +2701,9 @@ export class AssetService {
return Array.from(projectIds)
}
async getDownloadLinks(ids: string[]): Promise<Array<{ id: string; name: string; url: string }>> {
async getDownloadLinks(
ids: string[],
): Promise<Array<{ id: string; name: string; url: string }> & { skippedArchivedCount?: number }> {
if (ids.length === 0) return []
// Resolve starting IDs (dereference top-level symlinks)
@@ -2632,6 +2730,7 @@ export class AssetService {
id: string
name: string
type: string
status: string
parentId: string | null
storageKeyId: string | null
sortIndex: string | null
@@ -2639,16 +2738,16 @@ export class AssetService {
}>
>`
WITH RECURSIVE descendant AS (
SELECT id, name, type, parent_id, storage_key_id, sort_index, target_id, is_deleted
SELECT id, name, type, status::text AS status, parent_id, storage_key_id, sort_index, target_id, is_deleted
FROM assets
WHERE id IN (${Prisma.join(startingIds)}) AND is_deleted = false
UNION ALL
SELECT a.id, a.name, a.type, a.parent_id, a.storage_key_id, a.sort_index, a.target_id, a.is_deleted
SELECT a.id, a.name, a.type, a.status::text AS status, a.parent_id, a.storage_key_id, a.sort_index, a.target_id, a.is_deleted
FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
WHERE a.is_deleted = false
)
SELECT id, name, type, parent_id AS "parentId", storage_key_id AS "storageKeyId", sort_index AS "sortIndex", target_id AS "targetId" FROM descendant;
SELECT id, name, type, status, parent_id AS "parentId", storage_key_id AS "storageKeyId", sort_index AS "sortIndex", target_id AS "targetId" FROM descendant;
`
// Find any symlink in the descendants and resolve its target.
@@ -2657,6 +2756,7 @@ export class AssetService {
id: string
name: string
type: string
status: string
parentId: string | null
storageKeyId: string | null
sortIndex: string | null
@@ -2673,6 +2773,7 @@ export class AssetService {
id: t.id,
name: t.name,
type: t.type,
status: t.status,
parentId: t.parentId,
storageKeyId: t.storageKeyId,
sortIndex: t.sortIndex,
@@ -2737,16 +2838,29 @@ export class AssetService {
const storageKeys = await this.prismaClient.storageKey.findMany({
where: { id: { in: storageKeyIds } },
})
const storageKeyMap = new Map(storageKeys.map((k) => [k.id, k.key]))
const storageKeyMap = new Map(storageKeys.map((k) => [k.id, k]))
let skippedArchivedCount = 0
const downloadLinks = await Promise.all(
deduplicatedFiles.map(async (file) => {
const key = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null
if (!key) return null
const sk = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null
if (!sk?.key) return null
const isArchivedOrTransitioning =
file.status === AssetStatus.archiving ||
file.status === AssetStatus.archived ||
file.status === AssetStatus.restoring ||
sk.isArchived
if (isArchivedOrTransitioning) {
skippedArchivedCount++
return null
}
const url = await s3Service.presign(
process.env.S3_BUCKET || 'shumai',
key,
sk.key,
'GET',
true,
file.name,
@@ -2760,7 +2874,17 @@ export class AssetService {
}),
)
return downloadLinks.filter((link): link is { id: string; name: string; url: string } => !!link)
const filteredLinks = downloadLinks.filter(
(link): link is { id: string; name: string; url: string } => !!link,
) as Array<{ id: string; name: string; url: string }> & { skippedArchivedCount?: number }
Object.defineProperty(filteredLinks, 'skippedArchivedCount', {
value: skippedArchivedCount,
enumerable: false,
configurable: true,
})
return filteredLinks
}
/**
@@ -2772,7 +2896,13 @@ export class AssetService {
const targetAssetId = await this.resolveLatestVersionId(assetId)
const asset = await this.prismaClient.asset.findUnique({
where: { id: targetAssetId },
select: { id: true, name: true, parentId: true, storageKey: { select: { key: true } } },
select: {
id: true,
name: true,
status: true,
parentId: true,
storageKey: { select: { key: true, isArchived: true } },
},
})
if (!asset?.storageKey?.key) {
@@ -2786,6 +2916,8 @@ export class AssetService {
let storageKey = asset.storageKey.key
let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
let targetName = asset.name
let targetStatus = asset.status
let targetIsArchived = asset.storageKey.isArchived
if (!key.startsWith(assetDir) && asset.parentId) {
// Check if requested key belongs to another version in the same version stack
@@ -2795,11 +2927,17 @@ export class AssetService {
isDeleted: false,
storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } },
},
select: { name: true, storageKey: { select: { key: true } } },
select: {
name: true,
status: true,
storageKey: { select: { key: true, isArchived: true } },
},
})
if (sibling?.storageKey?.key) {
storageKey = sibling.storageKey.key
assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
targetStatus = sibling.status
targetIsArchived = sibling.storageKey.isArchived
if (sibling.name) {
targetName = sibling.name
}
@@ -2810,6 +2948,19 @@ export class AssetService {
throw new Error('Key does not belong to this asset')
}
if (key === storageKey) {
if (
targetStatus === AssetStatus.archiving ||
targetStatus === AssetStatus.archived ||
targetStatus === AssetStatus.restoring ||
targetIsArchived
) {
throw new HTTPException(409, {
message: 'Original file is archived. Restore the asset to download the original file.',
})
}
}
let downloadFilename: string | undefined
if (key === storageKey) {
downloadFilename = targetName ?? undefined
@@ -2841,6 +2992,349 @@ export class AssetService {
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true, downloadFilename)
}
private async resolveCandidateFileAssetsForArchiveOrRestore(assetIds: string[]) {
if (assetIds.length === 0) return []
const topAssets = await this.prismaClient.asset.findMany({
where: { id: { in: assetIds }, isDeleted: false },
select: { id: true, type: true, targetId: true },
})
const foundIds = new Set(topAssets.map((a) => a.id))
const uniqueRequested = Array.from(new Set(assetIds))
if (foundIds.size !== uniqueRequested.length) {
throw new HTTPException(404, { message: 'Asset not found' })
}
const startingIds = topAssets.map((a) =>
a.type === AssetType.symlink && a.targetId ? a.targetId : a.id,
)
const expandIdsRecursively = async (rootIds: string[]) => {
if (rootIds.length === 0) return []
return this.prismaClient.$queryRaw<
Array<{
id: string
type: string
targetId: string | null
}>
>`
WITH RECURSIVE descendant AS (
SELECT id, type::text AS type, target_id, is_deleted
FROM assets
WHERE id IN (${Prisma.join(rootIds)}) AND is_deleted = false
UNION ALL
SELECT a.id, a.type::text AS type, a.target_id, a.is_deleted
FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
WHERE a.is_deleted = false
)
SELECT id, type, target_id AS "targetId" FROM descendant;
`
}
const firstPass = await expandIdsRecursively(startingIds)
const nestedSymlinkTargets = firstPass
.filter((r) => r.type === AssetType.symlink && r.targetId)
.map((r) => r.targetId!)
const secondPass =
nestedSymlinkTargets.length > 0 ? await expandIdsRecursively(nestedSymlinkTargets) : []
const fileIds = Array.from(
new Set(
[...firstPass, ...secondPass].filter((r) => r.type === AssetType.file).map((r) => r.id),
),
)
if (fileIds.length === 0) {
return []
}
return this.prismaClient.asset.findMany({
where: {
id: { in: fileIds },
isDeleted: false,
type: AssetType.file,
status: {
notIn: [AssetStatus.trashed, AssetStatus.pending_purge],
},
},
include: {
storageKey: true,
project: { select: { id: true, teamId: true } },
},
orderBy: { id: 'asc' },
})
}
async archiveAssets(assetIds: string[]): Promise<ArchiveAssetsResponse> {
if (!isArchiveStorageEnabled()) {
throw new HTTPException(400, { message: 'Archive storage is not configured' })
}
if (assetIds.length === 0) {
return { archivedAssetIds: [], taskIds: [], skippedCount: 0 }
}
const candidateFiles = await this.resolveCandidateFileAssetsForArchiveOrRestore(assetIds)
if (candidateFiles.length === 0) {
return { archivedAssetIds: [], taskIds: [], skippedCount: 0 }
}
// Check active transcode/watermark tasks on candidate files
const activeTasks = await this.prismaClient.workflowTask.findMany({
where: {
assetId: { in: candidateFiles.map((f) => f.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,
],
},
},
select: { assetId: true },
})
const busyAssetIds = new Set(activeTasks.map((t) => t.assetId))
const eligibleByStorageKey = new Map<string, typeof candidateFiles>()
let skippedCount = 0
let alreadyArchivedCount = 0
let invalidStateCount = 0
let busyCount = 0
for (const file of candidateFiles) {
if (!file.storageKeyId || !file.storageKey || !file.projectId || !file.project?.teamId) {
skippedCount++
continue
}
if (
file.status === AssetStatus.archiving ||
file.status === AssetStatus.archived ||
file.storageKey.isArchived
) {
skippedCount++
alreadyArchivedCount++
continue
}
if (busyAssetIds.has(file.id)) {
skippedCount++
busyCount++
continue
}
if (file.status !== AssetStatus.processed) {
skippedCount++
invalidStateCount++
continue
}
const list = eligibleByStorageKey.get(file.storageKeyId) || []
list.push(file)
eligibleByStorageKey.set(file.storageKeyId, list)
}
if (eligibleByStorageKey.size === 0) {
if (alreadyArchivedCount === 0 && busyCount > 0) {
throw new HTTPException(409, {
message: 'Cannot archive asset while a workflow task is in progress',
})
}
if (alreadyArchivedCount === 0 && invalidStateCount > 0) {
throw new HTTPException(409, {
message: 'Only processed assets can be archived',
})
}
return { archivedAssetIds: [], taskIds: [], skippedCount }
}
const archivedAssetIdsSet = new Set<string>()
const taskIds: string[] = []
for (const [storageKeyId, filesForKey] of eligibleByStorageKey.entries()) {
const primaryFile = filesForKey[0]
await this.prismaClient.$transaction(async (tx) => {
const sharedAssets = await tx.asset.findMany({
where: {
storageKeyId,
isDeleted: false,
type: AssetType.file,
status: {
notIn: [AssetStatus.trashed, AssetStatus.pending_purge],
},
},
select: { id: true },
})
const sharedAssetIds = sharedAssets.map((a) => a.id)
await tx.asset.updateMany({
where: { id: { in: sharedAssetIds } },
data: { status: AssetStatus.archiving },
})
for (const id of sharedAssetIds) {
archivedAssetIdsSet.add(id)
}
const existingTask = await tx.workflowTask.findFirst({
where: {
assetId: { in: sharedAssetIds },
type: WorkflowTaskType.archive_asset,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
select: { id: true },
})
if (existingTask) {
taskIds.push(existingTask.id)
} else {
const createdTask = await tx.workflowTask.create({
data: {
assetId: primaryFile.id,
type: WorkflowTaskType.archive_asset,
status: WorkflowTaskStatus.pending,
teamId: primaryFile.project!.teamId,
projectId: primaryFile.projectId!,
payload: {
projectId: primaryFile.projectId!,
archive: { storageKeyId },
},
},
})
taskIds.push(createdTask.id)
}
})
}
return {
archivedAssetIds: Array.from(archivedAssetIdsSet),
taskIds,
skippedCount,
}
}
async restoreArchivedAssets(assetIds: string[]): Promise<RestoreArchivedAssetsResponse> {
if (!isArchiveStorageEnabled()) {
throw new HTTPException(400, { message: 'Archive storage is not configured' })
}
if (assetIds.length === 0) {
return { restoredAssetIds: [], taskIds: [], skippedCount: 0 }
}
const candidateFiles = await this.resolveCandidateFileAssetsForArchiveOrRestore(assetIds)
if (candidateFiles.length === 0) {
return { restoredAssetIds: [], taskIds: [], skippedCount: 0 }
}
const eligibleByStorageKey = new Map<string, typeof candidateFiles>()
let skippedCount = 0
let alreadyRestoringOrHotCount = 0
let currentlyArchivingCount = 0
for (const file of candidateFiles) {
if (!file.storageKeyId || !file.storageKey || !file.projectId || !file.project?.teamId) {
skippedCount++
continue
}
if (file.status === AssetStatus.archiving) {
skippedCount++
currentlyArchivingCount++
continue
}
if (file.status === AssetStatus.restoring) {
skippedCount++
alreadyRestoringOrHotCount++
continue
}
if (file.status !== AssetStatus.archived && !file.storageKey.isArchived) {
skippedCount++
alreadyRestoringOrHotCount++
continue
}
const list = eligibleByStorageKey.get(file.storageKeyId) || []
list.push(file)
eligibleByStorageKey.set(file.storageKeyId, list)
}
if (eligibleByStorageKey.size === 0) {
if (alreadyRestoringOrHotCount === 0 && currentlyArchivingCount > 0) {
throw new HTTPException(409, {
message: 'Cannot restore asset while it is currently archiving',
})
}
return { restoredAssetIds: [], taskIds: [], skippedCount }
}
const restoredAssetIdsSet = new Set<string>()
const taskIds: string[] = []
for (const [storageKeyId, filesForKey] of eligibleByStorageKey.entries()) {
const primaryFile = filesForKey[0]
await this.prismaClient.$transaction(async (tx) => {
const sharedAssets = await tx.asset.findMany({
where: {
storageKeyId,
isDeleted: false,
type: AssetType.file,
status: {
notIn: [AssetStatus.trashed, AssetStatus.pending_purge],
},
},
select: { id: true },
})
const sharedAssetIds = sharedAssets.map((a) => a.id)
await tx.asset.updateMany({
where: { id: { in: sharedAssetIds } },
data: { status: AssetStatus.restoring },
})
for (const id of sharedAssetIds) {
restoredAssetIdsSet.add(id)
}
const existingTask = await tx.workflowTask.findFirst({
where: {
assetId: { in: sharedAssetIds },
type: WorkflowTaskType.restore_asset,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
select: { id: true },
})
if (existingTask) {
taskIds.push(existingTask.id)
} else {
const createdTask = await tx.workflowTask.create({
data: {
assetId: primaryFile.id,
type: WorkflowTaskType.restore_asset,
status: WorkflowTaskStatus.pending,
teamId: primaryFile.project!.teamId,
projectId: primaryFile.projectId!,
payload: {
projectId: primaryFile.projectId!,
archive: { storageKeyId },
},
},
})
taskIds.push(createdTask.id)
}
})
}
return {
restoredAssetIds: Array.from(restoredAssetIdsSet),
taskIds,
skippedCount,
}
}
async toPreviewInfo(
asset: Asset | AssetWithIncludes,
previewFormat?: PreviewFormat,
@@ -0,0 +1,183 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import { AssetStatus, prisma, type User } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { AuditAction } from '@shumai/dtos'
import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset'
import { resetArchiveStorageServiceForTests } from '@shumai/core/src/s3/archive-storage'
import {
archiveAssetsOp,
restoreArchivedAssetsOp,
runOperation,
type OperationContext,
} from './index'
describe('archive_assets and restore_archived_assets Operations', () => {
setupTestDbHooks()
const archiveRoot = path.join(process.cwd(), 'data-test-ops-archive')
let originalEnv: NodeJS.ProcessEnv
let owner: User
let editor: User
let reviewer: User
let outsider: User
let teamId: string
let projectId: string
let rootFolderId: string
const as = (user: User, via: OperationContext['via'] = 'cli'): OperationContext => ({
userId: user.id,
via,
})
beforeEach(async () => {
originalEnv = { ...process.env }
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
process.env.ARCHIVE_LOCAL_ROOT = archiveRoot
resetArchiveStorageServiceForTests()
owner = await prisma.user.create({
data: { name: 'Owner', email: 'arch-ops-owner@test.com', password: 'pw' },
})
editor = await prisma.user.create({
data: { name: 'Editor', email: 'arch-ops-editor@test.com', password: 'pw' },
})
reviewer = await prisma.user.create({
data: { name: 'Reviewer', email: 'arch-ops-reviewer@test.com', password: 'pw' },
})
outsider = await prisma.user.create({
data: { name: 'Outsider', email: 'arch-ops-outsider@test.com', password: 'pw' },
})
const team = await prisma.team.create({ data: { name: 'Arch Ops Team' } })
teamId = team.id
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
await prisma.teamMember.create({ data: { teamId, userId: editor.id, role: 'editor' } })
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
const project = await projectService.createProject(owner, { teamId, name: 'Arch Ops Project' })
projectId = project.id
rootFolderId = project.rootFolder!
})
afterEach(() => {
process.env = originalEnv
resetArchiveStorageServiceForTests()
if (fs.existsSync(archiveRoot)) {
fs.rmSync(archiveRoot, { recursive: true, force: true })
}
})
it('allows editor and owner to archive and restore assets and records audit entries', async () => {
const file = await assetService.createAsset({
name: 'take1.mov',
type: 'file',
parentId: rootFolderId,
projectId,
key: 'files/01OP/take1.mov',
sizeByte: 4096,
contentType: 'video/quicktime',
creatorId: owner.id,
})
await prisma.asset.update({
where: { id: file.id },
data: { status: AssetStatus.processed },
})
const archiveOut = await runOperation(archiveAssetsOp, as(editor, 'api'), {
assetIds: [file.id],
})
expect(archiveOut.archivedAssetIds).toEqual([file.id])
expect(archiveOut.taskIds).toHaveLength(1)
expect(archiveOut.skippedCount).toBe(0)
const archiveAudit = await prisma.auditLog.findMany({
where: { action: AuditAction.asset_archive },
})
expect(archiveAudit).toHaveLength(1)
expect(archiveAudit[0]).toMatchObject({
teamId,
projectId,
userId: editor.id,
itemId: file.id,
via: 'api',
})
// Transition to archived state to test restore_archived_assets
await prisma.storageKey.update({
where: { key: 'files/01OP/take1.mov' },
data: { isArchived: true },
})
await prisma.asset.update({
where: { id: file.id },
data: { status: AssetStatus.archived },
})
const restoreOut = await runOperation(restoreArchivedAssetsOp, as(owner, 'mcp'), {
assetIds: [file.id],
})
expect(restoreOut.restoredAssetIds).toEqual([file.id])
expect(restoreOut.taskIds).toHaveLength(1)
const restoreAudit = await prisma.auditLog.findMany({
where: { action: AuditAction.asset_restore_archive },
})
expect(restoreAudit).toHaveLength(1)
expect(restoreAudit[0]).toMatchObject({
teamId,
projectId,
userId: owner.id,
itemId: file.id,
via: 'mcp',
})
})
it('denies reviewer and outsider with 403 and causes no side effects or audit entries', async () => {
const file = await assetService.createAsset({
name: 'protected.mov',
type: 'file',
parentId: rootFolderId,
projectId,
key: 'files/01PROT/protected.mov',
sizeByte: 2048,
contentType: 'video/quicktime',
creatorId: owner.id,
})
await prisma.asset.update({
where: { id: file.id },
data: { status: AssetStatus.processed },
})
for (const user of [reviewer, outsider]) {
await expect(
runOperation(archiveAssetsOp, as(user), { assetIds: [file.id] }),
).rejects.toMatchObject({ status: 403 })
}
const row = await prisma.asset.findUniqueOrThrow({ where: { id: file.id } })
expect(row.status).toBe(AssetStatus.processed)
expect(await prisma.auditLog.count({ where: { action: AuditAction.asset_archive } })).toBe(0)
await prisma.storageKey.update({
where: { key: 'files/01PROT/protected.mov' },
data: { isArchived: true },
})
await prisma.asset.update({
where: { id: file.id },
data: { status: AssetStatus.archived },
})
for (const user of [reviewer, outsider]) {
await expect(
runOperation(restoreArchivedAssetsOp, as(user), { assetIds: [file.id] }),
).rejects.toMatchObject({ status: 403 })
}
const archivedRow = await prisma.asset.findUniqueOrThrow({ where: { id: file.id } })
expect(archivedRow.status).toBe(AssetStatus.archived)
expect(
await prisma.auditLog.count({ where: { action: AuditAction.asset_restore_archive } }),
).toBe(0)
})
})
@@ -0,0 +1,23 @@
import { archiveAssets } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
export const archiveAssetsOp = implementOperation(archiveAssets, {
authz: (input) =>
input.assetIds.map((id) => ({
permission: Permission.Edit,
type: ResourceType.Asset,
id,
})),
execute: async (input) => {
return assetService.archiveAssets(input.assetIds)
},
audit: (input) =>
input.assetIds.map((assetId) => ({
action: AuditAction.asset_archive,
itemId: assetId,
contextAssetId: assetId,
})),
})
@@ -0,0 +1,23 @@
import { restoreArchivedAssets } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
export const restoreArchivedAssetsOp = implementOperation(restoreArchivedAssets, {
authz: (input) =>
input.assetIds.map((id) => ({
permission: Permission.Edit,
type: ResourceType.Asset,
id,
})),
execute: async (input) => {
return assetService.restoreArchivedAssets(input.assetIds)
},
audit: (input) =>
input.assetIds.map((assetId) => ({
action: AuditAction.asset_restore_archive,
itemId: assetId,
contextAssetId: assetId,
})),
})
+2
View File
@@ -10,6 +10,7 @@ export {
} from './implement'
export { runOperation } from './run'
export { getOperation, getOperationsForSurface, operations } from './registry'
export { archiveAssetsOp } from './asset/archive-assets'
export { copyAssetsOp } from './asset/copy-assets'
export { createFolderOp } from './asset/create-folder'
export { deleteAssetOp } from './asset/delete-asset'
@@ -24,6 +25,7 @@ export {
waitBudgetMs,
} from './asset/read-asset'
export { renameAssetOp } from './asset/rename-asset'
export { restoreArchivedAssetsOp } from './asset/restore-archived-assets'
export { searchAssetsOp } from './asset/search-assets'
export { createCommentOp } from './comment/create-comment'
export { listCommentsOp } from './comment/list-comments'
+4
View File
@@ -1,4 +1,5 @@
import type { OperationName, Surface } from '@shumai/operations'
import { archiveAssetsOp } from './asset/archive-assets'
import { copyAssetsOp } from './asset/copy-assets'
import { createFolderOp } from './asset/create-folder'
import { deleteAssetOp } from './asset/delete-asset'
@@ -8,6 +9,7 @@ import { listAssetsOp } from './asset/list-assets'
import { moveAssetsOp } from './asset/move-assets'
import { getAssetRenderOp, readAssetOp } from './asset/read-asset'
import { renameAssetOp } from './asset/rename-asset'
import { restoreArchivedAssetsOp } from './asset/restore-archived-assets'
import { searchAssetsOp } from './asset/search-assets'
import { createCommentOp } from './comment/create-comment'
import { listCommentsOp } from './comment/list-comments'
@@ -49,6 +51,8 @@ export const operations = defineRegistry([
moveAssetsOp,
copyAssetsOp,
deleteAssetOp,
archiveAssetsOp,
restoreArchivedAssetsOp,
readAssetOp,
getAssetRenderOp,
downloadAssetOp,
@@ -0,0 +1,545 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import {
PutObjectCommand,
HeadObjectCommand,
CopyObjectCommand,
CreateMultipartUploadCommand,
UploadPartCommand,
UploadPartCopyCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand,
RestoreObjectCommand,
} from '@aws-sdk/client-s3'
import {
getArchiveStorageConfig,
isArchiveStorageEnabled,
isColdStorageRestoreError,
LocalArchiveStorageService,
parseRestoreHeaderStatus,
resetArchiveStorageServiceForTests,
S3ArchiveStorageService,
} from './archive-storage'
import { uploadStreamToS3Client } from './s3'
const s3ClientConstructorSpy = vi.fn()
const s3SendSpy = vi.fn()
vi.mock('@aws-sdk/client-s3', async (importOriginal) => {
const actual = await importOriginal<typeof import('@aws-sdk/client-s3')>()
return {
...actual,
S3Client: class {
constructor(params: unknown) {
s3ClientConstructorSpy(params)
}
send = s3SendSpy
},
}
})
function makeWebStream(chunks: Array<string | Uint8Array>): ReadableStream<Uint8Array> {
return new ReadableStream<Uint8Array>({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk)
}
controller.close()
},
})
}
async function readAllBytes(stream: ReadableStream<Uint8Array>): Promise<Buffer> {
const reader = stream.getReader()
const parts: Uint8Array[] = []
while (true) {
const { done, value } = await reader.read()
if (done) break
if (value) parts.push(value)
}
return Buffer.concat(parts)
}
describe('Archive Storage', () => {
let originalEnv: NodeJS.ProcessEnv
beforeEach(() => {
originalEnv = { ...process.env }
vi.clearAllMocks()
resetArchiveStorageServiceForTests()
delete process.env.ARCHIVE_STORAGE_BACKEND
delete process.env.ARCHIVE_LOCAL_ROOT
delete process.env.ARCHIVE_S3_BUCKET
delete process.env.ARCHIVE_AWS_ENDPOINT_URL_S3
delete process.env.ARCHIVE_S3_REGION
delete process.env.ARCHIVE_S3_ACCESS_KEY_ID
delete process.env.ARCHIVE_S3_SECRET_ACCESS_KEY
delete process.env.ARCHIVE_S3_FORCE_PATH_STYLE
delete process.env.ARCHIVE_S3_STORAGE_CLASS
delete process.env.ARCHIVE_S3_USE_RESTORE_OBJECT
delete process.env.ARCHIVE_S3_RESTORE_DAYS
delete process.env.ARCHIVE_S3_RESTORE_TIER
})
afterEach(() => {
process.env = originalEnv
resetArchiveStorageServiceForTests()
})
describe('Environment configuration & validation', () => {
it('is disabled when ARCHIVE_STORAGE_BACKEND is unset or empty', () => {
expect(isArchiveStorageEnabled()).toBe(false)
expect(getArchiveStorageConfig()).toEqual({ enabled: false })
process.env.ARCHIVE_STORAGE_BACKEND = ' '
expect(isArchiveStorageEnabled()).toBe(false)
expect(getArchiveStorageConfig()).toEqual({ enabled: false })
})
it('rejects unsupported ARCHIVE_STORAGE_BACKEND values', () => {
process.env.ARCHIVE_STORAGE_BACKEND = 'ftp'
expect(() => getArchiveStorageConfig()).toThrow(/Invalid ARCHIVE_STORAGE_BACKEND/)
})
it('requires ARCHIVE_LOCAL_ROOT for local archive backend and rejects overlap with main local storage', () => {
process.env.STORAGE_BACKEND = 'local'
process.env.S3_BUCKET = 'shumai'
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
expect(() => getArchiveStorageConfig()).toThrow(/ARCHIVE_LOCAL_ROOT is required/)
process.env.ARCHIVE_LOCAL_ROOT = 'data/shumai'
expect(() => getArchiveStorageConfig()).toThrow(/must not overlap/)
process.env.ARCHIVE_LOCAL_ROOT = 'data/shumai/subdir'
expect(() => getArchiveStorageConfig()).toThrow(/must not overlap/)
process.env.ARCHIVE_LOCAL_ROOT = 'data'
expect(() => getArchiveStorageConfig()).toThrow(/must not overlap/)
process.env.ARCHIVE_LOCAL_ROOT = 'data-archive'
const cfg = getArchiveStorageConfig()
expect(cfg).toEqual({
enabled: true,
backend: 'local',
localRoot: path.resolve('data-archive'),
isSameS3Target: false,
})
})
it('never falls back to main S3_* environment variables when ARCHIVE_STORAGE_BACKEND is s3', () => {
process.env.STORAGE_BACKEND = 's3'
process.env.S3_BUCKET = 'main-bucket'
process.env.S3_ACCESS_KEY_ID = 'main-key'
process.env.S3_SECRET_ACCESS_KEY = 'main-secret'
process.env.AWS_ENDPOINT_URL_S3 = 'http://main-s3:9000'
process.env.ARCHIVE_STORAGE_BACKEND = 's3'
expect(() => getArchiveStorageConfig()).toThrow(/ARCHIVE_S3_BUCKET is required/)
process.env.ARCHIVE_S3_BUCKET = 'archive-bucket'
expect(() => getArchiveStorageConfig()).toThrow(/ARCHIVE_S3_ACCESS_KEY_ID is required/)
process.env.ARCHIVE_S3_ACCESS_KEY_ID = 'archive-key'
expect(() => getArchiveStorageConfig()).toThrow(/ARCHIVE_S3_SECRET_ACCESS_KEY is required/)
process.env.ARCHIVE_S3_SECRET_ACCESS_KEY = 'archive-secret'
const cfg = getArchiveStorageConfig()
expect(cfg).toMatchObject({
enabled: true,
backend: 's3',
bucket: 'archive-bucket',
endpoint: undefined,
accessKeyId: 'archive-key',
secretAccessKey: 'archive-secret',
isSameS3Target: false,
})
})
it('detects same-bucket S3 configuration and requires a non-STANDARD ARCHIVE_S3_STORAGE_CLASS', () => {
process.env.STORAGE_BACKEND = 's3'
process.env.S3_BUCKET = 'shared-bucket'
process.env.AWS_ENDPOINT_URL_S3 = 'https://s3.example.com/'
process.env.ARCHIVE_STORAGE_BACKEND = 's3'
process.env.ARCHIVE_S3_BUCKET = 'shared-bucket'
process.env.ARCHIVE_AWS_ENDPOINT_URL_S3 = 'https://s3.example.com'
process.env.ARCHIVE_S3_ACCESS_KEY_ID = 'ak'
process.env.ARCHIVE_S3_SECRET_ACCESS_KEY = 'sk'
expect(() => getArchiveStorageConfig()).toThrow(/ARCHIVE_S3_STORAGE_CLASS must be set/)
process.env.ARCHIVE_S3_STORAGE_CLASS = 'standard'
expect(() => getArchiveStorageConfig()).toThrow(/ARCHIVE_S3_STORAGE_CLASS must be set/)
process.env.ARCHIVE_S3_STORAGE_CLASS = 'GLACIER_IR'
const cfg = getArchiveStorageConfig()
expect(cfg).toMatchObject({
enabled: true,
backend: 's3',
bucket: 'shared-bucket',
storageClass: 'GLACIER_IR',
isSameS3Target: true,
})
})
})
describe('LocalArchiveStorageService', () => {
const testRoot = path.join(process.cwd(), 'data-test-archive-local')
beforeEach(() => {
if (fs.existsSync(testRoot)) {
fs.rmSync(testRoot, { recursive: true, force: true })
}
})
afterEach(() => {
if (fs.existsSync(testRoot)) {
fs.rmSync(testRoot, { recursive: true, force: true })
}
})
it('stores files directly under <ARCHIVE_LOCAL_ROOT>/<key> without a bucket subfolder and cleans up empty parent folders on delete', async () => {
const localArchive = new LocalArchiveStorageService(testRoot)
const key = 'files/01M5P70NR77MCJRHDZK989S3H2/sample.mp4'
const payload = 'raw video bytes content'
await localArchive.uploadStream(key, makeWebStream([payload]), payload.length, 'video/mp4')
const expectedDiskPath = path.join(
testRoot,
'files',
'01M5P70NR77MCJRHDZK989S3H2',
'sample.mp4',
)
expect(fs.existsSync(expectedDiskPath)).toBe(true)
const head = await localArchive.headObject(key)
expect(head.size).toBe(payload.length)
expect(head.key).toBe(key)
const { stream, contentLength } = await localArchive.getObjectStream(key)
expect(contentLength).toBe(payload.length)
const readBack = await readAllBytes(stream)
expect(readBack.toString('utf8')).toBe(payload)
const restoreStatus = await localArchive.checkOrInitiateObjectRestore(key)
expect(restoreStatus).toEqual({ status: 'ready' })
const deleted = await localArchive.deleteObject(key)
expect(deleted).toBe(1)
expect(fs.existsSync(expectedDiskPath)).toBe(false)
// Empty <root>/files/<ulid> directory should also be cleaned up
expect(fs.existsSync(path.dirname(expectedDiskPath))).toBe(false)
})
it('prevents path traversal outside ARCHIVE_LOCAL_ROOT', async () => {
const localArchive = new LocalArchiveStorageService(testRoot)
await expect(
localArchive.uploadStream('../escape.txt', makeWebStream(['bad']), 3),
).rejects.toThrow(/path traversal/)
})
})
describe('S3ArchiveStorageService', () => {
const baseS3Config = {
enabled: true as const,
backend: 's3' as const,
bucket: 'archive-bucket',
endpoint: 'http://archive-s3:9000',
region: 'us-east-1',
accessKeyId: 'archive-ak',
secretAccessKey: 'archive-sk',
forcePathStyle: true,
storageClass: 'GLACIER_IR',
useRestoreObject: 'auto' as const,
restoreDays: 3,
restoreTier: undefined,
isSameS3Target: false,
}
it('uploads small streams via PutObjectCommand with configured arbitrary StorageClass', async () => {
s3SendSpy.mockResolvedValueOnce({})
const service = new S3ArchiveStorageService({
...baseS3Config,
storageClass: 'ColdArchive',
})
await service.uploadStream(
'files/01ABC/video.mp4',
makeWebStream(['hello archive']),
13,
'video/mp4',
)
expect(s3SendSpy).toHaveBeenCalledTimes(1)
const cmd = s3SendSpy.mock.calls[0][0]
expect(cmd).toBeInstanceOf(PutObjectCommand)
expect(cmd.input).toMatchObject({
Bucket: 'archive-bucket',
Key: 'files/01ABC/video.mp4',
ContentLength: 13,
ContentType: 'video/mp4',
StorageClass: 'ColdArchive',
})
})
it('streams large uploads via multipart upload and aborts on part failure', async () => {
// Test multipart helper with custom thresholds (singlePutMaxBytes = 10, partSizeBytes = 5)
const fakeClient = { send: s3SendSpy } as unknown as import('@aws-sdk/client-s3').S3Client
s3SendSpy
.mockResolvedValueOnce({ UploadId: 'mp-1' }) // CreateMultipartUpload
// eslint-disable-next-line @typescript-eslint/naming-convention
.mockResolvedValueOnce({ ETag: '"etag-1"' }) // Part 1
// eslint-disable-next-line @typescript-eslint/naming-convention
.mockResolvedValueOnce({ ETag: '"etag-2"' }) // Part 2
// eslint-disable-next-line @typescript-eslint/naming-convention
.mockResolvedValueOnce({ ETag: '"etag-3"' }) // Part 3
.mockResolvedValueOnce({}) // CompleteMultipartUpload
await uploadStreamToS3Client(
fakeClient,
{
bucket: 'archive-bucket',
key: 'files/01ABC/large.bin',
stream: makeWebStream(['01234', '56789', 'ab']),
contentLength: 12,
contentType: 'application/octet-stream',
storageClass: 'DEEP_ARCHIVE',
},
5,
10,
)
expect(s3SendSpy).toHaveBeenCalledTimes(5)
expect(s3SendSpy.mock.calls[0][0]).toBeInstanceOf(CreateMultipartUploadCommand)
expect(s3SendSpy.mock.calls[0][0].input).toMatchObject({
Bucket: 'archive-bucket',
Key: 'files/01ABC/large.bin',
StorageClass: 'DEEP_ARCHIVE',
})
expect(s3SendSpy.mock.calls[1][0]).toBeInstanceOf(UploadPartCommand)
expect(s3SendSpy.mock.calls[2][0]).toBeInstanceOf(UploadPartCommand)
expect(s3SendSpy.mock.calls[3][0]).toBeInstanceOf(UploadPartCommand)
expect(s3SendSpy.mock.calls[4][0]).toBeInstanceOf(CompleteMultipartUploadCommand)
expect(s3SendSpy.mock.calls[4][0].input.MultipartUpload.Parts).toEqual([
// eslint-disable-next-line @typescript-eslint/naming-convention
{ ETag: '"etag-1"', PartNumber: 1 },
// eslint-disable-next-line @typescript-eslint/naming-convention
{ ETag: '"etag-2"', PartNumber: 2 },
// eslint-disable-next-line @typescript-eslint/naming-convention
{ ETag: '"etag-3"', PartNumber: 3 },
])
// Verify abort on failure
s3SendSpy.mockReset()
s3SendSpy
.mockResolvedValueOnce({ UploadId: 'mp-fail' })
.mockRejectedValueOnce(new Error('Part upload failed'))
.mockResolvedValueOnce({}) // AbortMultipartUpload
await expect(
uploadStreamToS3Client(
fakeClient,
{
bucket: 'archive-bucket',
key: 'files/01ABC/large.bin',
stream: makeWebStream(['0123456789ab']),
contentLength: 12,
},
5,
10,
),
).rejects.toThrow('Part upload failed')
expect(s3SendSpy.mock.calls[2][0]).toBeInstanceOf(AbortMultipartUploadCommand)
expect(s3SendSpy.mock.calls[2][0].input).toMatchObject({
Bucket: 'archive-bucket',
Key: 'files/01ABC/large.bin',
UploadId: 'mp-fail',
})
})
it('handles checkOrInitiateObjectRestore in auto mode for synchronous vs asynchronous cold storage classes', async () => {
// 1. GLACIER_IR is immediately readable -> ready without calling RestoreObjectCommand
s3SendSpy.mockResolvedValueOnce({
ContentLength: 100,
StorageClass: 'GLACIER_IR',
})
const glacierIrService = new S3ArchiveStorageService({
...baseS3Config,
storageClass: 'GLACIER_IR',
})
expect(await glacierIrService.checkOrInitiateObjectRestore('files/1/a.mp4')).toEqual({
status: 'ready',
})
expect(s3SendSpy).toHaveBeenCalledTimes(1)
expect(s3SendSpy.mock.calls[0][0]).toBeInstanceOf(HeadObjectCommand)
// 2. GLACIER with no Restore header -> sends RestoreObjectCommand without GlacierJobParameters by default
s3SendSpy.mockReset()
s3SendSpy
.mockResolvedValueOnce({
ContentLength: 100,
StorageClass: 'GLACIER',
})
.mockResolvedValueOnce({})
const glacierService = new S3ArchiveStorageService({
...baseS3Config,
storageClass: 'GLACIER',
})
expect(await glacierService.checkOrInitiateObjectRestore('files/1/a.mp4')).toEqual({
status: 'restoring',
})
expect(s3SendSpy).toHaveBeenCalledTimes(2)
expect(s3SendSpy.mock.calls[1][0]).toBeInstanceOf(RestoreObjectCommand)
expect(s3SendSpy.mock.calls[1][0].input).toEqual({
Bucket: 'archive-bucket',
Key: 'files/1/a.mp4',
RestoreRequest: {
Days: 3,
},
})
// 3. When ARCHIVE_S3_RESTORE_TIER is explicitly set, includes GlacierJobParameters
s3SendSpy.mockReset()
s3SendSpy
.mockResolvedValueOnce({
ContentLength: 100,
StorageClass: 'DEEP_ARCHIVE',
})
.mockResolvedValueOnce({})
const tieredService = new S3ArchiveStorageService({
...baseS3Config,
storageClass: 'DEEP_ARCHIVE',
restoreTier: 'Standard',
})
expect(await tieredService.checkOrInitiateObjectRestore('files/1/a.mp4')).toEqual({
status: 'restoring',
})
expect(s3SendSpy.mock.calls[1][0].input).toEqual({
Bucket: 'archive-bucket',
Key: 'files/1/a.mp4',
RestoreRequest: {
Days: 3,
GlacierJobParameters: { Tier: 'Standard' },
},
})
// 4. Ongoing restore header -> returns 'restoring' without re-sending RestoreObject
s3SendSpy.mockReset()
s3SendSpy.mockResolvedValueOnce({
ContentLength: 100,
StorageClass: 'GLACIER',
Restore: 'ongoing-request="true"',
})
expect(await glacierService.checkOrInitiateObjectRestore('files/1/a.mp4')).toEqual({
status: 'restoring',
})
expect(s3SendSpy).toHaveBeenCalledTimes(1)
// 5. Completed restore header -> returns 'ready'
s3SendSpy.mockReset()
s3SendSpy.mockResolvedValueOnce({
ContentLength: 100,
StorageClass: 'GLACIER',
Restore: 'ongoing-request="false", expiry-date="Wed, 04 Nov 2026 00:00:00 GMT"',
})
expect(await glacierService.checkOrInitiateObjectRestore('files/1/a.mp4')).toEqual({
status: 'ready',
})
// 6. RestoreAlreadyInProgress (409) is treated as idempotent success
s3SendSpy.mockReset()
const conflictErr = Object.assign(new Error('RestoreAlreadyInProgress'), {
name: 'RestoreAlreadyInProgress',
$metadata: { httpStatusCode: 409 },
})
s3SendSpy
.mockResolvedValueOnce({
ContentLength: 100,
StorageClass: 'GLACIER',
})
.mockRejectedValueOnce(conflictErr)
expect(await glacierService.checkOrInitiateObjectRestore('files/1/a.mp4')).toEqual({
status: 'restoring',
})
})
it('rewrites StorageClass in-place via single CopyObject or multipart UploadPartCopy', async () => {
const service = new S3ArchiveStorageService(
{
...baseS3Config,
isSameS3Target: true,
},
{ singleCopyMaxBytes: 100, multipartCopyPartBytes: 60 },
)
// Single CopyObject (<= 100 bytes)
s3SendSpy.mockResolvedValueOnce({})
await service.rewriteObjectStorageClassInPlace(
'files/01ABC/my video #1.mp4',
'GLACIER_IR',
80,
'video/mp4',
)
expect(s3SendSpy).toHaveBeenCalledTimes(1)
expect(s3SendSpy.mock.calls[0][0]).toBeInstanceOf(CopyObjectCommand)
expect(s3SendSpy.mock.calls[0][0].input).toEqual({
Bucket: 'archive-bucket',
Key: 'files/01ABC/my video #1.mp4',
CopySource: 'archive-bucket/files/01ABC/my%20video%20%231.mp4',
StorageClass: 'GLACIER_IR',
MetadataDirective: 'COPY',
ContentType: 'video/mp4',
})
// Multipart UploadPartCopy (> 100 bytes: 130 bytes across 60-byte parts -> 0-59, 60-119, 120-129)
s3SendSpy.mockReset()
s3SendSpy
.mockResolvedValueOnce({ UploadId: 'copy-mp-1' })
// eslint-disable-next-line @typescript-eslint/naming-convention
.mockResolvedValueOnce({ CopyPartResult: { ETag: '"p1"' } })
// eslint-disable-next-line @typescript-eslint/naming-convention
.mockResolvedValueOnce({ CopyPartResult: { ETag: '"p2"' } })
// eslint-disable-next-line @typescript-eslint/naming-convention
.mockResolvedValueOnce({ CopyPartResult: { ETag: '"p3"' } })
.mockResolvedValueOnce({})
await service.rewriteObjectStorageClassInPlace(
'files/01ABC/large.mp4',
'STANDARD',
130,
'video/mp4',
)
expect(s3SendSpy).toHaveBeenCalledTimes(5)
expect(s3SendSpy.mock.calls[0][0]).toBeInstanceOf(CreateMultipartUploadCommand)
expect(s3SendSpy.mock.calls[1][0]).toBeInstanceOf(UploadPartCopyCommand)
expect(s3SendSpy.mock.calls[1][0].input.CopySourceRange).toBe('bytes=0-59')
expect(s3SendSpy.mock.calls[2][0].input.CopySourceRange).toBe('bytes=60-119')
expect(s3SendSpy.mock.calls[3][0].input.CopySourceRange).toBe('bytes=120-129')
expect(s3SendSpy.mock.calls[4][0]).toBeInstanceOf(CompleteMultipartUploadCommand)
})
it('detects cold storage restore errors and parses x-amz-restore headers accurately', () => {
expect(parseRestoreHeaderStatus(undefined)).toBe('none')
expect(parseRestoreHeaderStatus('ongoing-request="true"')).toBe('ongoing')
expect(
parseRestoreHeaderStatus(
'ongoing-request="false", expiry-date="Fri, 21 Dec 2026 00:00:00 GMT"',
),
).toBe('restored')
expect(isColdStorageRestoreError({ name: 'InvalidObjectState' })).toBe(true)
expect(isColdStorageRestoreError({ Code: 'RestoreAlreadyInProgress' })).toBe(true)
expect(
isColdStorageRestoreError(
new Error("The operation is not valid for the object's storage class"),
),
).toBe(true)
expect(isColdStorageRestoreError(new Error('NetworkingError'))).toBe(false)
})
})
})
+728
View File
@@ -0,0 +1,728 @@
import { ObjectInfo } from '@shumai/dtos'
import {
S3Client,
GetObjectCommand,
HeadObjectCommand,
DeleteObjectCommand,
CopyObjectCommand,
CreateMultipartUploadCommand,
UploadPartCopyCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand,
RestoreObjectCommand,
StorageClass,
Tier,
} from '@aws-sdk/client-s3'
import * as crypto from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
import { Readable } from 'stream'
import { pipeline } from 'stream/promises'
import { ulid } from 'ulid'
import { bodyToWebReadableStream, S3StreamObject, uploadStreamToS3Client } from './s3'
export type ArchiveStorageBackend = 'local' | 's3'
export type ArchiveRestoreObjectMode = 'auto' | 'true' | 'false'
export interface ArchiveObjectInfo extends ObjectInfo {
storageClass?: string
restoreHeader?: string
}
export interface ArchiveStorageConfigDisabled {
enabled: false
}
export interface ArchiveStorageConfigLocal {
enabled: true
backend: 'local'
localRoot: string
isSameS3Target: false
}
export interface ArchiveStorageConfigS3 {
enabled: true
backend: 's3'
bucket: string
endpoint?: string
region: string
accessKeyId: string
secretAccessKey: string
forcePathStyle: boolean
storageClass?: string
useRestoreObject: ArchiveRestoreObjectMode
restoreDays: number
restoreTier?: string
isSameS3Target: boolean
}
export type ArchiveStorageConfig =
ArchiveStorageConfigDisabled | ArchiveStorageConfigLocal | ArchiveStorageConfigS3
export interface ArchiveStorageService {
readonly backend: ArchiveStorageBackend
readonly isSameS3Target: boolean
readonly storageClass?: string
uploadStream: (
key: string,
stream: ReadableStream<Uint8Array>,
size: number,
contentType?: string,
) => Promise<void>
getObjectStream: (key: string) => Promise<S3StreamObject>
headObject: (key: string) => Promise<ArchiveObjectInfo>
deleteObject: (key: string) => Promise<number>
checkOrInitiateObjectRestore: (key: string) => Promise<{ status: 'ready' | 'restoring' }>
initiateObjectRestoreExplicitly: (key: string) => Promise<{ status: 'ready' | 'restoring' }>
rewriteObjectStorageClassInPlace: (
key: string,
targetStorageClass: string,
expectedSize: number,
contentType?: string,
) => Promise<void>
}
/**
* Storage classes across AWS S3 and S3-compatible providers that require asynchronous
* `RestoreObject` + `HeadObject` (`x-amz-restore`) polling before `GetObject` / `CopyObject`.
* Explicitly excludes `GLACIER_IR` (Glacier Instant Retrieval), which is synchronously readable.
*/
export const KNOWN_ASYNC_RESTORE_STORAGE_CLASSES = new Set([
'GLACIER',
'DEEP_ARCHIVE',
'ARCHIVE',
'COLDARCHIVE',
'COLD_ARCHIVE',
'DEEPCOLDARCHIVE',
'DEEP_COLD_ARCHIVE',
'COLD',
])
const SINGLE_COPY_MAX_BYTES = 5 * 1024 * 1024 * 1024 // 5 GB
const MULTIPART_COPY_PART_BYTES = 512 * 1024 * 1024 // 512 MB
function normalizeEndpointForComparison(endpoint?: string): string {
const trimmed = (endpoint || '').trim().toLowerCase().replace(/\/+$/, '')
return trimmed || 'https://s3.amazonaws.com'
}
function isSubPathOrEqual(candidatePath: string, targetPath: string): boolean {
const rel = path.relative(targetPath, candidatePath)
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
}
export function encodeCopySourceKey(bucket: string, key: string): string {
const encodedKey = key
.split('/')
.map((segment) => encodeURIComponent(segment))
.join('/')
return `${bucket}/${encodedKey}`
}
export function parseRestoreHeaderStatus(restoreHeader?: string): 'ongoing' | 'restored' | 'none' {
if (!restoreHeader) return 'none'
if (/ongoing-request\s*=\s*"true"/i.test(restoreHeader)) {
return 'ongoing'
}
if (/ongoing-request\s*=\s*"false"/i.test(restoreHeader)) {
return 'restored'
}
return 'none'
}
export function isColdStorageRestoreError(err: unknown): boolean {
if (!err || typeof err !== 'object') return false
const e = err as Record<string, unknown>
const code =
(typeof e.name === 'string' && e.name) ||
(typeof e.Code === 'string' && e.Code) ||
(typeof e.code === 'string' && e.code) ||
''
if (code === 'InvalidObjectState' || code === 'RestoreAlreadyInProgress') {
return true
}
const msg = typeof e.message === 'string' ? e.message : ''
return (
msg.includes('InvalidObjectState') ||
msg.includes('RestoreAlreadyInProgress') ||
msg.includes("operation is not valid for the object's storage class")
)
}
function isRestoreAlreadyInProgressError(err: unknown): boolean {
if (!err || typeof err !== 'object') return false
const e = err as Record<string, unknown>
const metadata = e.$metadata as { httpStatusCode?: number } | undefined
const code =
(typeof e.name === 'string' && e.name) ||
(typeof e.Code === 'string' && e.Code) ||
(typeof e.code === 'string' && e.code) ||
''
if (code === 'RestoreAlreadyInProgress' || metadata?.httpStatusCode === 409) {
return true
}
return typeof e.message === 'string' && e.message.includes('RestoreAlreadyInProgress')
}
export function getArchiveStorageConfig(): ArchiveStorageConfig {
const rawBackend = (process.env.ARCHIVE_STORAGE_BACKEND || '').trim()
if (!rawBackend) {
return { enabled: false }
}
if (rawBackend !== 'local' && rawBackend !== 's3') {
throw new Error(
`Invalid ARCHIVE_STORAGE_BACKEND "${rawBackend}". Expected "local", "s3", or empty.`,
)
}
if (rawBackend === 'local') {
const rawLocalRoot = (process.env.ARCHIVE_LOCAL_ROOT || '').trim()
if (!rawLocalRoot) {
throw new Error(
'ARCHIVE_LOCAL_ROOT is required when ARCHIVE_STORAGE_BACKEND is set to "local".',
)
}
const resolvedArchiveRoot = path.resolve(rawLocalRoot)
const mainBackend = (process.env.STORAGE_BACKEND || 'local').trim()
if (mainBackend !== 's3') {
const mainBaseDir = path.resolve('data')
const mainBucketDir = path.resolve('data', process.env.S3_BUCKET || 'shumai')
if (
resolvedArchiveRoot === mainBaseDir ||
isSubPathOrEqual(resolvedArchiveRoot, mainBucketDir) ||
isSubPathOrEqual(mainBucketDir, resolvedArchiveRoot)
) {
throw new Error(
`ARCHIVE_LOCAL_ROOT (${resolvedArchiveRoot}) must not overlap with main local storage (${mainBucketDir}).`,
)
}
}
return {
enabled: true,
backend: 'local',
localRoot: resolvedArchiveRoot,
isSameS3Target: false,
}
}
// S3 backend — never fall back to main S3_* environment variables
const bucket = (process.env.ARCHIVE_S3_BUCKET || '').trim()
if (!bucket) {
throw new Error('ARCHIVE_S3_BUCKET is required when ARCHIVE_STORAGE_BACKEND is set to "s3".')
}
const accessKeyId = (process.env.ARCHIVE_S3_ACCESS_KEY_ID || '').trim()
if (!accessKeyId) {
throw new Error(
'ARCHIVE_S3_ACCESS_KEY_ID is required when ARCHIVE_STORAGE_BACKEND is set to "s3".',
)
}
const secretAccessKey = (process.env.ARCHIVE_S3_SECRET_ACCESS_KEY || '').trim()
if (!secretAccessKey) {
throw new Error(
'ARCHIVE_S3_SECRET_ACCESS_KEY is required when ARCHIVE_STORAGE_BACKEND is set to "s3".',
)
}
const endpoint = (process.env.ARCHIVE_AWS_ENDPOINT_URL_S3 || '').trim() || undefined
const region = (process.env.ARCHIVE_S3_REGION || '').trim() || 'auto'
const forcePathStyleRaw = (process.env.ARCHIVE_S3_FORCE_PATH_STYLE || 'true').trim().toLowerCase()
const forcePathStyle = forcePathStyleRaw !== 'false' && forcePathStyleRaw !== '0'
const storageClass = (process.env.ARCHIVE_S3_STORAGE_CLASS || '').trim() || undefined
const useRestoreObjectRaw = (process.env.ARCHIVE_S3_USE_RESTORE_OBJECT || 'auto')
.trim()
.toLowerCase()
if (
useRestoreObjectRaw !== 'auto' &&
useRestoreObjectRaw !== 'true' &&
useRestoreObjectRaw !== 'false'
) {
throw new Error(
`Invalid ARCHIVE_S3_USE_RESTORE_OBJECT "${useRestoreObjectRaw}". Expected "auto", "true", or "false".`,
)
}
const restoreDaysRaw = (process.env.ARCHIVE_S3_RESTORE_DAYS || '1').trim()
const restoreDays = Number.parseInt(restoreDaysRaw, 10)
if (!Number.isFinite(restoreDays) || restoreDays < 1) {
throw new Error(
`Invalid ARCHIVE_S3_RESTORE_DAYS "${restoreDaysRaw}". Expected a positive integer.`,
)
}
const restoreTier = (process.env.ARCHIVE_S3_RESTORE_TIER || '').trim() || undefined
const mainBackend = (process.env.STORAGE_BACKEND || 'local').trim()
const mainBucket = (process.env.S3_BUCKET || 'shumai').trim()
const mainEndpoint = (process.env.AWS_ENDPOINT_URL_S3 || '').trim() || undefined
const isSameS3Target =
mainBackend === 's3' &&
mainBucket === bucket &&
normalizeEndpointForComparison(mainEndpoint) === normalizeEndpointForComparison(endpoint)
if (isSameS3Target) {
if (!storageClass || storageClass.toUpperCase() === 'STANDARD') {
throw new Error(
'When ARCHIVE_S3_BUCKET and endpoint match main S3 storage, ARCHIVE_S3_STORAGE_CLASS must be set to a non-STANDARD storage class.',
)
}
}
return {
enabled: true,
backend: 's3',
bucket,
endpoint,
region,
accessKeyId,
secretAccessKey,
forcePathStyle,
storageClass,
useRestoreObject: useRestoreObjectRaw,
restoreDays,
restoreTier,
isSameS3Target,
}
}
export function isArchiveStorageEnabled(): boolean {
const rawBackend = (process.env.ARCHIVE_STORAGE_BACKEND || '').trim()
return rawBackend === 'local' || rawBackend === 's3'
}
export function validateArchiveStorageConfig(): ArchiveStorageConfig {
return getArchiveStorageConfig()
}
export class LocalArchiveStorageService implements ArchiveStorageService {
readonly backend = 'local' as const
readonly isSameS3Target = false
readonly storageClass = undefined
private readonly rootPath: string
constructor(rootPath: string) {
this.rootPath = path.resolve(rootPath)
if (!fs.existsSync(this.rootPath)) {
fs.mkdirSync(this.rootPath, { recursive: true })
}
}
private getFilePath(key: string): string {
const normalizedKey = key.replace(/^\/+/, '')
if (!normalizedKey) {
throw new Error('Invalid archive key: key cannot be empty')
}
const filePath = path.resolve(this.rootPath, normalizedKey)
if (!isSubPathOrEqual(filePath, this.rootPath) || filePath === this.rootPath) {
throw new Error('Invalid archive path: potential path traversal detected')
}
return filePath
}
async uploadStream(
key: string,
stream: ReadableStream<Uint8Array>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_size: number,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_contentType?: string,
): Promise<void> {
const filePath = this.getFilePath(key)
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const tempPath = `${filePath}.tmp-${ulid()}`
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nodeStream = Readable.fromWeb(stream as any)
await pipeline(nodeStream, fs.createWriteStream(tempPath))
await fs.promises.rename(tempPath, filePath)
} catch (err) {
await fs.promises.unlink(tempPath).catch(() => {})
throw err
}
}
async getObjectStream(key: string): Promise<S3StreamObject> {
const filePath = this.getFilePath(key)
try {
const stats = await fs.promises.stat(filePath)
const nodeStream = fs.createReadStream(filePath)
return {
stream: Readable.toWeb(nodeStream) as unknown as ReadableStream<Uint8Array>,
contentLength: stats.size,
contentType: Bun.file(filePath).type || 'application/octet-stream',
}
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error('NoSuchKey: The specified key does not exist.', { cause: e })
}
throw e
}
}
async headObject(key: string): Promise<ArchiveObjectInfo> {
const filePath = this.getFilePath(key)
try {
const stats = await fs.promises.stat(filePath)
const hash = crypto
.createHash('md5')
.update(filePath + stats.mtimeMs)
.digest('hex')
return {
key,
size: stats.size,
lastModified: stats.mtime,
contentType: Bun.file(key).type || 'application/octet-stream',
eTag: `"${hash}"`,
}
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error('NoSuchKey: The specified key does not exist.', { cause: e })
}
throw e
}
}
async deleteObject(key: string): Promise<number> {
const filePath = this.getFilePath(key)
try {
await fs.promises.unlink(filePath)
// Best-effort cleanup of empty parent folder (e.g. `<root>/files/<ulid>`)
const parentDir = path.dirname(filePath)
if (parentDir !== this.rootPath && isSubPathOrEqual(parentDir, this.rootPath)) {
const remaining = await fs.promises.readdir(parentDir).catch(() => ['non-empty'])
if (remaining.length === 0) {
await fs.promises.rmdir(parentDir).catch(() => {})
}
}
return 1
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
return 0
}
throw e
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async checkOrInitiateObjectRestore(_key: string): Promise<{ status: 'ready' | 'restoring' }> {
return { status: 'ready' }
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async initiateObjectRestoreExplicitly(_key: string): Promise<{ status: 'ready' | 'restoring' }> {
return { status: 'ready' }
}
async rewriteObjectStorageClassInPlace(): Promise<void> {
throw new Error('rewriteObjectStorageClassInPlace is only supported for S3 archive storage.')
}
}
export class S3ArchiveStorageService implements ArchiveStorageService {
readonly backend = 's3' as const
readonly isSameS3Target: boolean
readonly storageClass?: string
private readonly client: S3Client
private readonly bucket: string
private readonly useRestoreObject: ArchiveRestoreObjectMode
private readonly restoreDays: number
private readonly restoreTier?: string
private readonly singleCopyMaxBytes: number
private readonly multipartCopyPartBytes: number
constructor(
config: ArchiveStorageConfigS3,
options?: { singleCopyMaxBytes?: number; multipartCopyPartBytes?: number },
) {
this.bucket = config.bucket
this.isSameS3Target = config.isSameS3Target
this.storageClass = config.storageClass
this.useRestoreObject = config.useRestoreObject
this.restoreDays = config.restoreDays
this.restoreTier = config.restoreTier
this.singleCopyMaxBytes = options?.singleCopyMaxBytes ?? SINGLE_COPY_MAX_BYTES
this.multipartCopyPartBytes = options?.multipartCopyPartBytes ?? MULTIPART_COPY_PART_BYTES
this.client = new S3Client({
region: config.region,
...(config.endpoint ? { endpoint: config.endpoint } : {}),
credentials: {
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
},
forcePathStyle: config.forcePathStyle,
requestChecksumCalculation: 'WHEN_REQUIRED',
responseChecksumValidation: 'WHEN_REQUIRED',
})
}
async uploadStream(
key: string,
stream: ReadableStream<Uint8Array>,
size: number,
contentType?: string,
): Promise<void> {
await uploadStreamToS3Client(this.client, {
bucket: this.bucket,
key,
stream,
contentLength: size,
contentType,
storageClass: this.storageClass,
})
}
async getObjectStream(key: string): Promise<S3StreamObject> {
const res = await this.client.send(new GetObjectCommand({ Bucket: this.bucket, Key: key }))
return {
stream: bodyToWebReadableStream(res.Body),
contentLength: res.ContentLength,
contentType: res.ContentType || Bun.file(key).type || 'application/octet-stream',
}
}
async headObject(key: string): Promise<ArchiveObjectInfo> {
try {
const res = await this.client.send(new HeadObjectCommand({ Bucket: this.bucket, Key: key }))
return {
key,
size: res.ContentLength ?? 0,
lastModified: res.LastModified ?? new Date(),
contentType: res.ContentType || 'application/octet-stream',
eTag: res.ETag || '',
storageClass: res.StorageClass,
restoreHeader: res.Restore,
}
} catch (err: unknown) {
throw new Error('NoSuchKey: The specified key does not exist.', { cause: err })
}
}
async deleteObject(key: string): Promise<number> {
try {
await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: key }))
return 1
} catch {
return 0
}
}
private async sendRestoreObjectRequest(key: string): Promise<void> {
try {
await this.client.send(
new RestoreObjectCommand({
Bucket: this.bucket,
Key: key,
/* eslint-disable @typescript-eslint/naming-convention */
RestoreRequest: {
Days: this.restoreDays,
...(this.restoreTier
? { GlacierJobParameters: { Tier: this.restoreTier as Tier } }
: {}),
},
/* eslint-enable @typescript-eslint/naming-convention */
}),
)
} catch (err: unknown) {
if (isRestoreAlreadyInProgressError(err)) {
return
}
throw err
}
}
async checkOrInitiateObjectRestore(key: string): Promise<{ status: 'ready' | 'restoring' }> {
if (this.useRestoreObject === 'false') {
return { status: 'ready' }
}
const head = await this.headObject(key)
const restoreState = parseRestoreHeaderStatus(head.restoreHeader)
if (restoreState === 'restored') {
return { status: 'ready' }
}
if (restoreState === 'ongoing') {
return { status: 'restoring' }
}
const effectiveStorageClass = (head.storageClass || this.storageClass || '').toUpperCase()
const requiresRestore =
this.useRestoreObject === 'true' ||
(this.useRestoreObject === 'auto' &&
KNOWN_ASYNC_RESTORE_STORAGE_CLASSES.has(effectiveStorageClass))
if (!requiresRestore) {
return { status: 'ready' }
}
await this.sendRestoreObjectRequest(key)
return { status: 'restoring' }
}
async initiateObjectRestoreExplicitly(key: string): Promise<{ status: 'ready' | 'restoring' }> {
if (this.useRestoreObject === 'false') {
throw new Error(
'Object is in a cold storage class requiring RestoreObject, but ARCHIVE_S3_USE_RESTORE_OBJECT is set to "false".',
)
}
const head = await this.headObject(key)
const restoreState = parseRestoreHeaderStatus(head.restoreHeader)
if (restoreState === 'restored') {
return { status: 'ready' }
}
if (restoreState === 'ongoing') {
return { status: 'restoring' }
}
await this.sendRestoreObjectRequest(key)
return { status: 'restoring' }
}
async rewriteObjectStorageClassInPlace(
key: string,
targetStorageClass: string,
expectedSize: number,
contentType?: string,
): Promise<void> {
const copySource = encodeCopySourceKey(this.bucket, key)
const s3StorageClass = targetStorageClass as StorageClass
if (expectedSize <= this.singleCopyMaxBytes) {
await this.client.send(
new CopyObjectCommand({
Bucket: this.bucket,
Key: key,
CopySource: copySource,
// eslint-disable-next-line @typescript-eslint/naming-convention
StorageClass: s3StorageClass,
// eslint-disable-next-line @typescript-eslint/naming-convention
MetadataDirective: 'COPY',
...(contentType ? { ContentType: contentType } : {}),
}),
)
return
}
const createRes = await this.client.send(
new CreateMultipartUploadCommand({
Bucket: this.bucket,
Key: key,
// eslint-disable-next-line @typescript-eslint/naming-convention
StorageClass: s3StorageClass,
...(contentType ? { ContentType: contentType } : {}),
}),
)
const uploadId = createRes.UploadId
if (!uploadId) {
throw new Error(`Failed to initiate multipart copy for ${this.bucket}/${key}`)
}
// eslint-disable-next-line @typescript-eslint/naming-convention
const completedParts: Array<{ ETag?: string; PartNumber: number }> = []
let partNumber = 1
let offset = 0
try {
while (offset < expectedSize) {
const end = Math.min(offset + this.multipartCopyPartBytes - 1, expectedSize - 1)
const currentPartNumber = partNumber++
const copyPartRes = await this.client.send(
new UploadPartCopyCommand({
Bucket: this.bucket,
Key: key,
UploadId: uploadId,
PartNumber: currentPartNumber,
CopySource: copySource,
// eslint-disable-next-line @typescript-eslint/naming-convention
CopySourceRange: `bytes=${offset}-${end}`,
}),
)
completedParts.push({
// eslint-disable-next-line @typescript-eslint/naming-convention
ETag: copyPartRes.CopyPartResult?.ETag,
PartNumber: currentPartNumber,
})
offset = end + 1
}
await this.client.send(
new CompleteMultipartUploadCommand({
Bucket: this.bucket,
Key: key,
UploadId: uploadId,
/* eslint-disable @typescript-eslint/naming-convention */
MultipartUpload: {
Parts: completedParts,
},
/* eslint-enable @typescript-eslint/naming-convention */
}),
)
} catch (err) {
await this.client
.send(
new AbortMultipartUploadCommand({
Bucket: this.bucket,
Key: key,
UploadId: uploadId,
}),
)
.catch(() => {})
throw err
}
}
}
let cachedService: ArchiveStorageService | null = null
let cachedConfigSignature: string | null = null
function getEnvSignature(): string {
return JSON.stringify({
b: process.env.ARCHIVE_STORAGE_BACKEND,
lr: process.env.ARCHIVE_LOCAL_ROOT,
sb: process.env.ARCHIVE_S3_BUCKET,
se: process.env.ARCHIVE_AWS_ENDPOINT_URL_S3,
sr: process.env.ARCHIVE_S3_REGION,
ak: process.env.ARCHIVE_S3_ACCESS_KEY_ID,
sk: process.env.ARCHIVE_S3_SECRET_ACCESS_KEY,
fp: process.env.ARCHIVE_S3_FORCE_PATH_STYLE,
sc: process.env.ARCHIVE_S3_STORAGE_CLASS,
ro: process.env.ARCHIVE_S3_USE_RESTORE_OBJECT,
rd: process.env.ARCHIVE_S3_RESTORE_DAYS,
rt: process.env.ARCHIVE_S3_RESTORE_TIER,
mb: process.env.STORAGE_BACKEND,
msb: process.env.S3_BUCKET,
mse: process.env.AWS_ENDPOINT_URL_S3,
})
}
export function getArchiveStorageService(): ArchiveStorageService {
const sig = getEnvSignature()
if (cachedService && cachedConfigSignature === sig) {
return cachedService
}
const config = getArchiveStorageConfig()
if (!config.enabled) {
throw new Error('Archive storage is not enabled (ARCHIVE_STORAGE_BACKEND is not configured).')
}
cachedService =
config.backend === 'local'
? new LocalArchiveStorageService(config.localRoot)
: new S3ArchiveStorageService(config)
cachedConfigSignature = sig
return cachedService
}
export function resetArchiveStorageServiceForTests(): void {
cachedService = null
cachedConfigSignature = null
}
+242
View File
@@ -14,6 +14,7 @@ import {
ListPartsCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand,
StorageClass,
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import * as crypto from 'crypto'
@@ -82,6 +83,196 @@ export interface S3Object {
contentType: string
}
export interface S3StreamObject {
stream: ReadableStream<Uint8Array>
contentLength?: number
contentType?: string
}
export interface UploadStreamParams {
bucket: string
key: string
stream: ReadableStream<Uint8Array>
contentLength?: number
contentType?: string
storageClass?: string
}
const SINGLE_PUT_MAX_BYTES = 64 * 1024 * 1024 // 64 MB
const MULTIPART_PART_SIZE_BYTES = 16 * 1024 * 1024 // 16 MB
export function bodyToWebReadableStream(body: unknown): ReadableStream<Uint8Array> {
if (!body) {
throw new Error('NoSuchKey: The specified key returned an empty body.')
}
if (
typeof body === 'object' &&
'transformToWebStream' in body &&
typeof (body as { transformToWebStream: unknown }).transformToWebStream === 'function'
) {
return (
body as { transformToWebStream: () => ReadableStream<Uint8Array> }
).transformToWebStream()
}
if (typeof body === 'object' && 'getReader' in body) {
return body as ReadableStream<Uint8Array>
}
// Convert Node.js Readable or AsyncIterable to Web ReadableStream
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nodeReadable = 'pipe' in (body as any) ? (body as Readable) : Readable.from(body as any)
return Readable.toWeb(nodeReadable) as unknown as ReadableStream<Uint8Array>
}
export async function uploadStreamToS3Client(
client: S3Client,
params: UploadStreamParams,
partSizeBytes: number = MULTIPART_PART_SIZE_BYTES,
singlePutMaxBytes: number = SINGLE_PUT_MAX_BYTES,
): Promise<void> {
const { bucket, key, stream, contentLength, contentType, storageClass } = params
// AWS SDK v3 StorageClass is an open string union at runtime; cast safely for arbitrary S3-compatible classes
const s3StorageClass = storageClass ? (storageClass as StorageClass) : undefined
if (contentLength !== undefined && contentLength <= singlePutMaxBytes) {
if (contentLength === 0) {
await stream.cancel().catch(() => {})
await client.send(
new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: Buffer.alloc(0),
ContentLength: 0,
ContentType: contentType,
// eslint-disable-next-line @typescript-eslint/naming-convention
StorageClass: s3StorageClass,
}),
)
return
}
// Convert Web ReadableStream to Node stream without buffering into memory
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nodeStream = Readable.fromWeb(stream as any)
await client.send(
new PutObjectCommand({
Bucket: bucket,
Key: key,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Body: nodeStream as any,
ContentLength: contentLength,
ContentType: contentType,
// eslint-disable-next-line @typescript-eslint/naming-convention
StorageClass: s3StorageClass,
}),
)
return
}
// Multipart streaming upload for > 64 MB or unknown contentLength
const createRes = await client.send(
new CreateMultipartUploadCommand({
Bucket: bucket,
Key: key,
ContentType: contentType,
// eslint-disable-next-line @typescript-eslint/naming-convention
StorageClass: s3StorageClass,
}),
)
const uploadId = createRes.UploadId
if (!uploadId) {
throw new Error(`Failed to initiate multipart upload for ${bucket}/${key}`)
}
const reader = stream.getReader()
// eslint-disable-next-line @typescript-eslint/naming-convention
const completedParts: Array<{ ETag?: string; PartNumber: number }> = []
let partNumber = 1
const pendingChunks: Uint8Array[] = []
let pendingLength = 0
const flushPart = async (sizeToFlush: number) => {
const partBuffer = Buffer.allocUnsafe(sizeToFlush)
let offset = 0
while (offset < sizeToFlush && pendingChunks.length > 0) {
const chunk = pendingChunks[0]
const remaining = sizeToFlush - offset
if (chunk.byteLength <= remaining) {
partBuffer.set(chunk, offset)
offset += chunk.byteLength
pendingLength -= chunk.byteLength
pendingChunks.shift()
} else {
partBuffer.set(chunk.subarray(0, remaining), offset)
pendingChunks[0] = chunk.subarray(remaining)
offset += remaining
pendingLength -= remaining
}
}
const currentPartNumber = partNumber++
const partRes = await client.send(
new UploadPartCommand({
Bucket: bucket,
Key: key,
UploadId: uploadId,
PartNumber: currentPartNumber,
Body: partBuffer,
ContentLength: partBuffer.byteLength,
}),
)
completedParts.push({
// eslint-disable-next-line @typescript-eslint/naming-convention
ETag: partRes.ETag,
PartNumber: currentPartNumber,
})
}
try {
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
if (value && value.byteLength > 0) {
pendingChunks.push(value)
pendingLength += value.byteLength
while (pendingLength >= partSizeBytes) {
await flushPart(partSizeBytes)
}
}
}
if (pendingLength > 0 || completedParts.length === 0) {
await flushPart(pendingLength)
}
await client.send(
new CompleteMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: uploadId,
/* eslint-disable @typescript-eslint/naming-convention */
MultipartUpload: {
Parts: completedParts,
},
/* eslint-enable @typescript-eslint/naming-convention */
}),
)
} catch (err) {
await reader.cancel().catch(() => {})
await client
.send(
new AbortMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: uploadId,
}),
)
.catch(() => {})
throw err
} finally {
reader.releaseLock()
}
}
export interface S3Service {
getObjectSize: (bucket: string, key: string) => Promise<number>
putObject: (
@@ -92,6 +283,8 @@ export interface S3Service {
contentType?: string,
) => Promise<void>
getObject: (bucket: string, key: string) => Promise<S3Object>
getObjectStream: (bucket: string, key: string) => Promise<S3StreamObject>
uploadStream: (params: UploadStreamParams) => Promise<void>
copyObject: (
sourceBucket: string,
sourceKey: string,
@@ -225,6 +418,19 @@ export class S3StorageService implements S3Service {
}
}
async getObjectStream(bucket: string, key: string): Promise<S3StreamObject> {
const res = await this.client.send(new GetObjectCommand({ Bucket: bucket, Key: key }))
return {
stream: bodyToWebReadableStream(res.Body),
contentLength: res.ContentLength,
contentType: res.ContentType || Bun.file(key).type || 'application/octet-stream',
}
}
async uploadStream(params: UploadStreamParams): Promise<void> {
await uploadStreamToS3Client(this.client, params)
}
async copyObject(
sourceBucket: string,
sourceKey: string,
@@ -583,6 +789,42 @@ export class LocalStorageService implements S3Service {
}
}
async getObjectStream(bucket: string, key: string): Promise<S3StreamObject> {
const filePath = this.getFilePath(bucket, key)
try {
const stats = await fs.promises.stat(filePath)
const nodeStream = fs.createReadStream(filePath)
return {
stream: Readable.toWeb(nodeStream) as unknown as ReadableStream<Uint8Array>,
contentLength: stats.size,
contentType: Bun.file(filePath).type || 'application/octet-stream',
}
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error(`NoSuchKey: The specified key does not exist.`, { cause: e })
}
throw e
}
}
async uploadStream(params: UploadStreamParams): Promise<void> {
const filePath = this.getFilePath(params.bucket, params.key)
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const tempPath = `${filePath}.tmp-${ulid()}`
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nodeStream = Readable.fromWeb(params.stream as any)
await pipeline(nodeStream, fs.createWriteStream(tempPath))
await fs.promises.rename(tempPath, filePath)
} catch (err) {
await fs.promises.unlink(tempPath).catch(() => {})
throw err
}
}
async copyObject(
sourceBucket: string,
sourceKey: string,
@@ -57,7 +57,7 @@ export class EmbeddingService {
const candidateAssets = await prisma.asset.findMany({
where: {
isDeleted: false,
status: 'processed',
status: { in: ['processed', 'archived'] },
type: { in: ['file', 'version_stack'] },
project: { teamId: { in: activeTeamIds } },
},
@@ -285,6 +285,42 @@ export class SqlQueryBuilder {
}
}
if (field === 'isArchived' || field === 'is_archived') {
if (operator !== 'eq' && operator !== 'neq') {
throw new Error(`Unsupported operator for isArchived field: ${operator}`)
}
const rawBool = value === true || value === 'true' || value === 1 || value === '1'
const wantArchived = operator === 'neq' ? !rawBool : rawBool
if (wantArchived) {
return Prisma.sql`(
(a."type" = 'file'::"AssetType" AND a."status" = 'archived'::"AssetStatus")
OR (
a."type" = 'version_stack'::"AssetType"
AND (
SELECT v."status" FROM assets v
WHERE v."parent_id" = a."id" AND v."is_deleted" = false
ORDER BY v."sort_index" ASC LIMIT 1
) = 'archived'::"AssetStatus"
)
)`
}
return Prisma.sql`(
(a."type" = 'file'::"AssetType" AND a."status" != 'archived'::"AssetStatus")
OR (
a."type" = 'version_stack'::"AssetType"
AND COALESCE(
(
SELECT v."status"::text FROM assets v
WHERE v."parent_id" = a."id" AND v."is_deleted" = false
ORDER BY v."sort_index" ASC LIMIT 1
),
''
) != 'archived'
)
OR a."type" NOT IN ('file'::"AssetType", 'version_stack'::"AssetType")
)`
}
if (
field === 'createdAt' ||
field === 'updatedAt' ||
+37 -9
View File
@@ -300,15 +300,43 @@ export class WorkflowTaskService {
}
if (task.assetId) {
await tx.$executeRaw`
UPDATE "assets"
SET
"status" = 'failed'::"AssetStatus",
"media" = COALESCE("media", '{}'::jsonb) || jsonb_build_object('error', ${errorMsg}::text)
WHERE "id" = ${task.assetId}
AND "is_deleted" = false
AND "status" != 'processed'::"AssetStatus"
`
if (task.type === 'archive_asset' || task.type === 'restore_asset') {
const payload = task.payload as PrismaJson.WorkflowTaskPayload | null
let storageKeyId = payload?.archive?.storageKeyId
if (!storageKeyId) {
const targetAsset = await tx.asset.findUnique({
where: { id: task.assetId },
select: { storageKeyId: true },
})
storageKeyId = targetAsset?.storageKeyId ?? undefined
}
if (storageKeyId) {
const sk = await tx.storageKey.findUnique({
where: { id: storageKeyId },
select: { isArchived: true },
})
const fallbackStatus = sk?.isArchived ? 'archived' : 'processed'
await tx.asset.updateMany({
where: {
storageKeyId,
isDeleted: false,
type: 'file',
status: { in: ['archiving', 'restoring'] },
},
data: { status: fallbackStatus },
})
}
} else {
await tx.$executeRaw`
UPDATE "assets"
SET
"status" = 'failed'::"AssetStatus",
"media" = COALESCE("media", '{}'::jsonb) || jsonb_build_object('error', ${errorMsg}::text)
WHERE "id" = ${task.assetId}
AND "is_deleted" = false
AND "status" NOT IN ('processed'::"AssetStatus", 'archived'::"AssetStatus", 'archiving'::"AssetStatus", 'restoring'::"AssetStatus")
`
}
}
return await tx.workflowTask.findUniqueOrThrow({
@@ -0,0 +1,25 @@
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AssetStatus" ADD VALUE 'archiving';
ALTER TYPE "AssetStatus" ADD VALUE 'archived';
ALTER TYPE "AssetStatus" ADD VALUE 'restoring';
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "WorkflowTaskType" ADD VALUE 'archive_asset';
ALTER TYPE "WorkflowTaskType" ADD VALUE 'restore_asset';
-- AlterTable
ALTER TABLE "storage_keys" ADD COLUMN "is_archived" BOOLEAN NOT NULL DEFAULT false;
+12 -6
View File
@@ -40,6 +40,9 @@ enum AssetStatus {
uploaded
processing
processed
archiving
archived
restoring
failed
trashed
pending_purge
@@ -128,6 +131,8 @@ enum WorkflowTaskType {
query_embedding_for_search
agent_tool_call // @deprecated: Agent tools now execute directly in-process via Core services
kanban_agent_run
archive_asset
restore_asset
}
enum WorkflowTaskStatus {
@@ -606,12 +611,13 @@ model Asset {
}
model StorageKey {
id String @id @default(ulid())
key String @unique
status StorageKeyStatus @default(active)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assets Asset[]
id String @id @default(ulid())
key String @unique
status StorageKeyStatus @default(active)
isArchived Boolean @default(false) @map("is_archived")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assets Asset[]
@@map("storage_keys")
}
+6 -1
View File
@@ -36,6 +36,9 @@ export const AssetStatus = {
uploaded: 'uploaded',
processing: 'processing',
processed: 'processed',
archiving: 'archiving',
archived: 'archived',
restoring: 'restoring',
failed: 'failed',
trashed: 'trashed',
pending_purge: 'pending_purge'
@@ -156,7 +159,9 @@ export const WorkflowTaskType = {
ai_embedding: 'ai_embedding',
query_embedding_for_search: 'query_embedding_for_search',
agent_tool_call: 'agent_tool_call',
kanban_agent_run: 'kanban_agent_run'
kanban_agent_run: 'kanban_agent_run',
archive_asset: 'archive_asset',
restore_asset: 'restore_asset'
} as const
export type WorkflowTaskType = (typeof WorkflowTaskType)[keyof typeof WorkflowTaskType]
File diff suppressed because one or more lines are too long
@@ -5201,6 +5201,7 @@ export const StorageKeyScalarFieldEnum = {
id: 'id',
key: 'key',
status: 'status',
isArchived: 'isArchived',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
@@ -375,6 +375,7 @@ export const StorageKeyScalarFieldEnum = {
id: 'id',
key: 'key',
status: 'status',
isArchived: 'isArchived',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
+33 -1
View File
@@ -30,6 +30,7 @@ export type StorageKeyMinAggregateOutputType = {
id: string | null
key: string | null
status: $Enums.StorageKeyStatus | null
isArchived: boolean | null
createdAt: Date | null
updatedAt: Date | null
}
@@ -38,6 +39,7 @@ export type StorageKeyMaxAggregateOutputType = {
id: string | null
key: string | null
status: $Enums.StorageKeyStatus | null
isArchived: boolean | null
createdAt: Date | null
updatedAt: Date | null
}
@@ -46,6 +48,7 @@ export type StorageKeyCountAggregateOutputType = {
id: number
key: number
status: number
isArchived: number
createdAt: number
updatedAt: number
_all: number
@@ -56,6 +59,7 @@ export type StorageKeyMinAggregateInputType = {
id?: true
key?: true
status?: true
isArchived?: true
createdAt?: true
updatedAt?: true
}
@@ -64,6 +68,7 @@ export type StorageKeyMaxAggregateInputType = {
id?: true
key?: true
status?: true
isArchived?: true
createdAt?: true
updatedAt?: true
}
@@ -72,6 +77,7 @@ export type StorageKeyCountAggregateInputType = {
id?: true
key?: true
status?: true
isArchived?: true
createdAt?: true
updatedAt?: true
_all?: true
@@ -153,6 +159,7 @@ export type StorageKeyGroupByOutputType = {
id: string
key: string
status: $Enums.StorageKeyStatus
isArchived: boolean
createdAt: Date
updatedAt: Date
_count: StorageKeyCountAggregateOutputType | null
@@ -182,6 +189,7 @@ export type StorageKeyWhereInput = {
id?: Prisma.StringFilter<"StorageKey"> | string
key?: Prisma.StringFilter<"StorageKey"> | string
status?: Prisma.EnumStorageKeyStatusFilter<"StorageKey"> | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolFilter<"StorageKey"> | boolean
createdAt?: Prisma.DateTimeFilter<"StorageKey"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"StorageKey"> | Date | string
assets?: Prisma.AssetListRelationFilter
@@ -191,6 +199,7 @@ export type StorageKeyOrderByWithRelationInput = {
id?: Prisma.SortOrder
key?: Prisma.SortOrder
status?: Prisma.SortOrder
isArchived?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
assets?: Prisma.AssetOrderByRelationAggregateInput
@@ -203,6 +212,7 @@ export type StorageKeyWhereUniqueInput = Prisma.AtLeast<{
OR?: Prisma.StorageKeyWhereInput[]
NOT?: Prisma.StorageKeyWhereInput | Prisma.StorageKeyWhereInput[]
status?: Prisma.EnumStorageKeyStatusFilter<"StorageKey"> | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolFilter<"StorageKey"> | boolean
createdAt?: Prisma.DateTimeFilter<"StorageKey"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"StorageKey"> | Date | string
assets?: Prisma.AssetListRelationFilter
@@ -212,6 +222,7 @@ export type StorageKeyOrderByWithAggregationInput = {
id?: Prisma.SortOrder
key?: Prisma.SortOrder
status?: Prisma.SortOrder
isArchived?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
_count?: Prisma.StorageKeyCountOrderByAggregateInput
@@ -226,6 +237,7 @@ export type StorageKeyScalarWhereWithAggregatesInput = {
id?: Prisma.StringWithAggregatesFilter<"StorageKey"> | string
key?: Prisma.StringWithAggregatesFilter<"StorageKey"> | string
status?: Prisma.EnumStorageKeyStatusWithAggregatesFilter<"StorageKey"> | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolWithAggregatesFilter<"StorageKey"> | boolean
createdAt?: Prisma.DateTimeWithAggregatesFilter<"StorageKey"> | Date | string
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"StorageKey"> | Date | string
}
@@ -234,6 +246,7 @@ export type StorageKeyCreateInput = {
id?: string
key: string
status?: $Enums.StorageKeyStatus
isArchived?: boolean
createdAt?: Date | string
updatedAt?: Date | string
assets?: Prisma.AssetCreateNestedManyWithoutStorageKeyInput
@@ -243,6 +256,7 @@ export type StorageKeyUncheckedCreateInput = {
id?: string
key: string
status?: $Enums.StorageKeyStatus
isArchived?: boolean
createdAt?: Date | string
updatedAt?: Date | string
assets?: Prisma.AssetUncheckedCreateNestedManyWithoutStorageKeyInput
@@ -252,6 +266,7 @@ export type StorageKeyUpdateInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
key?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumStorageKeyStatusFieldUpdateOperationsInput | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolFieldUpdateOperationsInput | boolean
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assets?: Prisma.AssetUpdateManyWithoutStorageKeyNestedInput
@@ -261,6 +276,7 @@ export type StorageKeyUncheckedUpdateInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
key?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumStorageKeyStatusFieldUpdateOperationsInput | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolFieldUpdateOperationsInput | boolean
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assets?: Prisma.AssetUncheckedUpdateManyWithoutStorageKeyNestedInput
@@ -270,6 +286,7 @@ export type StorageKeyCreateManyInput = {
id?: string
key: string
status?: $Enums.StorageKeyStatus
isArchived?: boolean
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -278,6 +295,7 @@ export type StorageKeyUpdateManyMutationInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
key?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumStorageKeyStatusFieldUpdateOperationsInput | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolFieldUpdateOperationsInput | boolean
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -286,6 +304,7 @@ export type StorageKeyUncheckedUpdateManyInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
key?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumStorageKeyStatusFieldUpdateOperationsInput | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolFieldUpdateOperationsInput | boolean
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -299,6 +318,7 @@ export type StorageKeyCountOrderByAggregateInput = {
id?: Prisma.SortOrder
key?: Prisma.SortOrder
status?: Prisma.SortOrder
isArchived?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -307,6 +327,7 @@ export type StorageKeyMaxOrderByAggregateInput = {
id?: Prisma.SortOrder
key?: Prisma.SortOrder
status?: Prisma.SortOrder
isArchived?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -315,6 +336,7 @@ export type StorageKeyMinOrderByAggregateInput = {
id?: Prisma.SortOrder
key?: Prisma.SortOrder
status?: Prisma.SortOrder
isArchived?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -343,6 +365,7 @@ export type StorageKeyCreateWithoutAssetsInput = {
id?: string
key: string
status?: $Enums.StorageKeyStatus
isArchived?: boolean
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -351,6 +374,7 @@ export type StorageKeyUncheckedCreateWithoutAssetsInput = {
id?: string
key: string
status?: $Enums.StorageKeyStatus
isArchived?: boolean
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -375,6 +399,7 @@ export type StorageKeyUpdateWithoutAssetsInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
key?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumStorageKeyStatusFieldUpdateOperationsInput | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolFieldUpdateOperationsInput | boolean
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -383,6 +408,7 @@ export type StorageKeyUncheckedUpdateWithoutAssetsInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
key?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumStorageKeyStatusFieldUpdateOperationsInput | $Enums.StorageKeyStatus
isArchived?: Prisma.BoolFieldUpdateOperationsInput | boolean
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -422,6 +448,7 @@ export type StorageKeySelect<ExtArgs extends runtime.Types.Extensions.InternalAr
id?: boolean
key?: boolean
status?: boolean
isArchived?: boolean
createdAt?: boolean
updatedAt?: boolean
assets?: boolean | Prisma.StorageKey$assetsArgs<ExtArgs>
@@ -432,6 +459,7 @@ export type StorageKeySelectCreateManyAndReturn<ExtArgs extends runtime.Types.Ex
id?: boolean
key?: boolean
status?: boolean
isArchived?: boolean
createdAt?: boolean
updatedAt?: boolean
}, ExtArgs["result"]["storageKey"]>
@@ -440,6 +468,7 @@ export type StorageKeySelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Ex
id?: boolean
key?: boolean
status?: boolean
isArchived?: boolean
createdAt?: boolean
updatedAt?: boolean
}, ExtArgs["result"]["storageKey"]>
@@ -448,11 +477,12 @@ export type StorageKeySelectScalar = {
id?: boolean
key?: boolean
status?: boolean
isArchived?: boolean
createdAt?: boolean
updatedAt?: boolean
}
export type StorageKeyOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "key" | "status" | "createdAt" | "updatedAt", ExtArgs["result"]["storageKey"]>
export type StorageKeyOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "key" | "status" | "isArchived" | "createdAt" | "updatedAt", ExtArgs["result"]["storageKey"]>
export type StorageKeyInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
assets?: boolean | Prisma.StorageKey$assetsArgs<ExtArgs>
_count?: boolean | Prisma.StorageKeyCountOutputTypeDefaultArgs<ExtArgs>
@@ -469,6 +499,7 @@ export type $StorageKeyPayload<ExtArgs extends runtime.Types.Extensions.Internal
id: string
key: string
status: $Enums.StorageKeyStatus
isArchived: boolean
createdAt: Date
updatedAt: Date
}, ExtArgs["result"]["storageKey"]>
@@ -898,6 +929,7 @@ export interface StorageKeyFieldRefs {
readonly id: Prisma.FieldRef<"StorageKey", 'String'>
readonly key: Prisma.FieldRef<"StorageKey", 'String'>
readonly status: Prisma.FieldRef<"StorageKey", 'StorageKeyStatus'>
readonly isArchived: Prisma.FieldRef<"StorageKey", 'Boolean'>
readonly createdAt: Prisma.FieldRef<"StorageKey", 'DateTime'>
readonly updatedAt: Prisma.FieldRef<"StorageKey", 'DateTime'>
}
+3
View File
@@ -362,6 +362,9 @@ declare global {
/** Render that produced this result, if any (set by the read_asset pipeline). */
assetRead?: AssetReadRequest
watermark?: WatermarkTaskPayload
archive?: {
storageKeyId: string
}
recoveryAttempts?: number
}
+26
View File
@@ -158,6 +158,7 @@ export const assetInfoSchema = z.object({
current: z.boolean(),
id: z.string(),
name: z.string().optional().nullable(),
status: z.string().optional().nullable(),
previewUrl: z.string().optional().nullable(),
createdAt: z.string().optional().nullable(),
creator: z
@@ -395,9 +396,34 @@ export type DownloadLinkItem = z.infer<typeof downloadLinkItemSchema>
export const getDownloadLinksResponseSchema = z.object({
files: z.array(downloadLinkItemSchema),
skippedArchivedCount: z.number().optional(),
})
export type GetDownloadLinksResponse = z.infer<typeof getDownloadLinksResponseSchema>
export const archiveAssetsRequestSchema = z.object({
ids: z.array(z.string().min(1)).min(1),
})
export type ArchiveAssetsRequest = z.infer<typeof archiveAssetsRequestSchema>
export const archiveAssetsResponseSchema = z.object({
archivedAssetIds: z.array(z.string()),
taskIds: z.array(z.string()),
skippedCount: z.number(),
})
export type ArchiveAssetsResponse = z.infer<typeof archiveAssetsResponseSchema>
export const restoreArchivedAssetsRequestSchema = z.object({
ids: z.array(z.string().min(1)).min(1),
})
export type RestoreArchivedAssetsRequest = z.infer<typeof restoreArchivedAssetsRequestSchema>
export const restoreArchivedAssetsResponseSchema = z.object({
restoredAssetIds: z.array(z.string()),
taskIds: z.array(z.string()),
skippedCount: z.number(),
})
export type RestoreArchivedAssetsResponse = z.infer<typeof restoreArchivedAssetsResponseSchema>
export const commentExportFormatSchema = z.enum([
'fcp-fiojson',
'media-composer-xml',
+2
View File
@@ -22,6 +22,8 @@ export enum AuditAction {
folder_delete = 'folder_delete',
asset_reparent = 'asset_reparent',
asset_copy = 'asset_copy',
asset_archive = 'asset_archive',
asset_restore_archive = 'asset_restore_archive',
version_stack_create = 'version_stack_create',
version_stack_update = 'version_stack_update',
share_create = 'share_create',
+1
View File
@@ -32,6 +32,7 @@ export const stackVersionInfoSchema = z.object({
id: z.string(),
version: z.number(),
name: z.string().optional().nullable(),
status: z.string().optional().nullable(),
previewUrl: z.string().optional().nullable(),
createdAt: z.string().optional().nullable(),
creator: z
+189
View File
@@ -0,0 +1,189 @@
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import { AssetStatus, prisma, WorkflowTaskStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { workflowService, TaskQueueArchive } from '@shumai/workflow-core'
import { initTranscodeWorkflows } from '@shumai/transcode'
import { assetService } from '@shumai/core/src/asset/asset'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
getArchiveStorageService,
resetArchiveStorageServiceForTests,
} from '@shumai/core/src/s3/archive-storage'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
describe('Workflow E2E - archiveAssetWorkflow & restoreAssetWorkflow', () => {
setupTestDbHooks()
const bucket = 'shumai-e2e-test-bucket-archive'
let archiveRootDir: string
beforeAll(async () => {
archiveRootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-e2e-archive-'))
process.env.S3_BUCKET = bucket
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
process.env.ARCHIVE_LOCAL_ROOT = archiveRootDir
resetArchiveStorageServiceForTests()
initTranscodeWorkflows()
await workflowService.startWorkers(TaskQueueArchive)
})
afterAll(async () => {
await workflowService.shutdownWorkers()
workflowService.close()
vi.restoreAllMocks()
resetArchiveStorageServiceForTests()
delete process.env.ARCHIVE_STORAGE_BACKEND
delete process.env.ARCHIVE_LOCAL_ROOT
try {
await s3Service.deletePrefix(bucket, '')
} catch {
// ignore cleanup errors
}
if (archiveRootDir && fs.existsSync(archiveRootDir)) {
fs.rmSync(archiveRootDir, { recursive: true, force: true })
}
})
async function waitForTaskCompletion(taskId: string, timeoutMs = 15000) {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
const task = await prisma.workflowTask.findUnique({ where: { id: taskId } })
if (task?.status === WorkflowTaskStatus.completed) return task
if (task?.status === WorkflowTaskStatus.failed) {
throw new Error(`Workflow task ${taskId} failed: ${JSON.stringify(task.output)}`)
}
await new Promise((r) => setTimeout(r, 150))
}
throw new Error(`Timed out waiting for workflow task ${taskId}`)
}
it('archives an asset and its shared-StorageKey copy via DBOS workflow, keeps proxy in main storage, and restores back to main storage', async () => {
const team = await prisma.team.create({
data: { name: 'E2E Archive Team' },
})
const rootFolder = await prisma.asset.create({
data: { name: 'root', type: 'root', status: 'uploaded' },
})
const project = await prisma.project.create({
data: { name: 'E2E Archive Project', teamId: team.id, rootFolderId: rootFolder.id },
})
await prisma.asset.update({
where: { id: rootFolder.id },
data: { projectId: project.id },
})
const originalKey = 'files/e2e-arch-1/master.mp4'
const proxyKey = 'files/e2e-arch-1/proxy-720p.mp4'
const originalBytes = Buffer.from('original-raw-video-bytes-for-e2e-archive-workflow')
const proxyBytes = Buffer.from('proxy-720p-video-bytes')
await s3Service.putObject(bucket, originalKey, originalBytes, originalBytes.length, 'video/mp4')
await s3Service.putObject(bucket, proxyKey, proxyBytes, proxyBytes.length, 'video/mp4')
const storageKey = await prisma.storageKey.create({
data: { key: originalKey, isArchived: false },
})
const asset1 = await prisma.asset.create({
data: {
name: 'master.mp4',
type: 'file',
mediaType: 'video/mp4',
status: AssetStatus.processed,
sizeByte: BigInt(originalBytes.length),
projectId: project.id,
parentId: rootFolder.id,
storageKeyId: storageKey.id,
media: {
duration: 5,
filesize: originalBytes.length,
frames: 150,
finishedAt: new Date().toISOString(),
proxyType: 'video',
imageTranscodes: [],
videoTranscodes: [
{
key: proxyKey,
width: 1280,
height: 720,
resolution: '720p',
},
],
metadata: null,
original: {
key: originalKey,
filesizeInBytes: originalBytes.length,
codec: 'h264',
},
},
},
})
const asset2Copy = await prisma.asset.create({
data: {
name: 'master-copy.mp4',
type: 'file',
mediaType: 'video/mp4',
status: AssetStatus.processed,
sizeByte: BigInt(originalBytes.length),
projectId: project.id,
parentId: rootFolder.id,
storageKeyId: storageKey.id,
},
})
// 1. Trigger archive via assetService.archiveAssets
const archiveRes = await assetService.archiveAssets([asset1.id])
expect(archiveRes.archivedAssetIds.sort()).toEqual([asset1.id, asset2Copy.id].sort())
expect(archiveRes.taskIds).toHaveLength(1)
await waitForTaskCompletion(archiveRes.taskIds[0])
// Verify original moved to archive storage and removed from main storage
const archiveStorage = getArchiveStorageService()!
const archivedHead = await archiveStorage.headObject(originalKey)
expect(archivedHead.size).toBe(originalBytes.length)
await expect(s3Service.headObject(bucket, originalKey)).rejects.toThrow('NoSuchKey')
// Verify proxy remains intact in main storage
const proxyHead = await s3Service.headObject(bucket, proxyKey)
expect(proxyHead.size).toBe(proxyBytes.length)
// Verify DB states for StorageKey and both Asset rows
const skAfterArchive = await prisma.storageKey.findUniqueOrThrow({
where: { id: storageKey.id },
})
expect(skAfterArchive.isArchived).toBe(true)
const a1AfterArchive = await prisma.asset.findUniqueOrThrow({ where: { id: asset1.id } })
const a2AfterArchive = await prisma.asset.findUniqueOrThrow({ where: { id: asset2Copy.id } })
expect(a1AfterArchive.status).toBe(AssetStatus.archived)
expect(a2AfterArchive.status).toBe(AssetStatus.archived)
// 2. Trigger restore via assetService.restoreArchivedAssets
const restoreRes = await assetService.restoreArchivedAssets([asset2Copy.id])
expect(restoreRes.restoredAssetIds.sort()).toEqual([asset1.id, asset2Copy.id].sort())
expect(restoreRes.taskIds).toHaveLength(1)
await waitForTaskCompletion(restoreRes.taskIds[0])
// Verify original moved back to main storage and removed from archive storage
const restoredMainHead = await s3Service.headObject(bucket, originalKey)
expect(restoredMainHead.size).toBe(originalBytes.length)
await expect(archiveStorage.headObject(originalKey)).rejects.toThrow('NoSuchKey')
// Verify DB states after restore
const skAfterRestore = await prisma.storageKey.findUniqueOrThrow({
where: { id: storageKey.id },
})
expect(skAfterRestore.isArchived).toBe(false)
const a1AfterRestore = await prisma.asset.findUniqueOrThrow({ where: { id: asset1.id } })
const a2AfterRestore = await prisma.asset.findUniqueOrThrow({ where: { id: asset2Copy.id } })
expect(a1AfterRestore.status).toBe(AssetStatus.processed)
expect(a2AfterRestore.status).toBe(AssetStatus.processed)
})
})
@@ -0,0 +1,36 @@
import { z } from 'zod'
import { defineOperation } from '../define'
export const archiveAssets = defineOperation({
name: 'archive_assets',
title: 'Archive Assets',
description:
'Move the original raw file(s) of one or more assets (files, version stacks, or folders) to ' +
'cold archive storage. All transcoded proxies, previews, and thumbnails remain in main ' +
'storage so assets stay viewable, while original raw file downloads are disabled until restored.',
input: z.object({
assetIds: z
.array(z.string().min(1))
.min(1)
.describe(
'The IDs of the assets (files, version stacks, or folders) to archive. Archiving a folder or version stack archives all eligible files inside it.',
),
}),
output: z.object({
archivedAssetIds: z.array(z.string()).describe('IDs of the file assets queued for archiving.'),
taskIds: z.array(z.string()).describe('IDs of the archive workflow tasks created.'),
skippedCount: z
.number()
.describe(
'Number of candidate files skipped (e.g. already archived or currently archiving).',
),
}),
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: false, destructive: false, idempotent: true },
cli: {
command: ['archive'],
positional: ['assetIds'],
format: (output) =>
`Queued ${output.archivedAssetIds.length} asset(s) for archiving (${output.skippedCount} skipped)`,
},
})
@@ -0,0 +1,36 @@
import { z } from 'zod'
import { defineOperation } from '../define'
export const restoreArchivedAssets = defineOperation({
name: 'restore_archived_assets',
title: 'Restore Archived Assets',
description:
'Restore the original raw file(s) of one or more archived assets (files, version stacks, or ' +
'folders) from cold archive storage back to main storage.',
input: z.object({
assetIds: z
.array(z.string().min(1))
.min(1)
.describe(
'The IDs of the archived assets (files, version stacks, or folders) to restore back to main storage.',
),
}),
output: z.object({
restoredAssetIds: z
.array(z.string())
.describe('IDs of the file assets queued for restoration.'),
taskIds: z.array(z.string()).describe('IDs of the restore workflow tasks created.'),
skippedCount: z
.number()
.describe('Number of candidate files skipped (e.g. not archived or already restoring).'),
}),
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: false, destructive: false, idempotent: true },
cli: {
command: ['unarchive'],
aliases: ['restore-archive'],
positional: ['assetIds'],
format: (output) =>
`Queued ${output.restoredAssetIds.length} asset(s) for restoration from archive (${output.skippedCount} skipped)`,
},
})
@@ -28,7 +28,7 @@ const conditionSchema = z.object({
.min(1)
.describe(
'Metadata field key from list_metadata_fields (e.g. "status"), or one of "name", ' +
'"sizeByte", "createdAt", "updatedAt".',
'"sizeByte", "createdAt", "updatedAt", "isArchived".',
),
operator: z
.enum(SEARCH_CONDITION_OPERATORS)
+2
View File
@@ -2,6 +2,7 @@ export * from './define'
export * from './schemas'
export * from './registry'
export { dropNullOptionals } from './null-optionals'
export { archiveAssets } from './asset/archive-assets'
export { copyAssets } from './asset/copy-assets'
export { createFolder } from './asset/create-folder'
export { deleteAsset } from './asset/delete-asset'
@@ -9,6 +10,7 @@ export { getFolderInstructions } from './asset/get-folder-instructions'
export { listAssets } from './asset/list-assets'
export { moveAssets } from './asset/move-assets'
export { renameAsset } from './asset/rename-asset'
export { restoreArchivedAssets } from './asset/restore-archived-assets'
export * from './asset/search-assets'
export * from './asset/read-asset'
export * from './asset/download-asset'
+4
View File
@@ -17,6 +17,7 @@ describe('operation registry', () => {
it('contains the asset, project, comment, metadata, version, and upload operations', () => {
expect(operationDefinitions.map((d) => d.name).sort()).toEqual([
'archive_assets',
'complete_upload',
'copy_assets',
'create_comment',
@@ -38,6 +39,7 @@ describe('operation registry', () => {
'remove_version',
'rename_asset',
'resolve_comment',
'restore_archived_assets',
'search_assets',
'update_asset_metadata',
])
@@ -128,6 +130,8 @@ describe('operation registry', () => {
['move_assets', ['move', 'mv']],
['copy_assets', ['copy', 'cp']],
['delete_asset', ['delete', 'rm']],
['archive_assets', ['archive']],
['restore_archived_assets', ['unarchive', 'restore-archive']],
['read_asset', ['read']],
['get_asset_render', ['render']],
['download_asset', ['download']],
+4
View File
@@ -1,3 +1,4 @@
import { archiveAssets } from './asset/archive-assets'
import { copyAssets } from './asset/copy-assets'
import { createFolder } from './asset/create-folder'
import { deleteAsset } from './asset/delete-asset'
@@ -7,6 +8,7 @@ import { listAssets } from './asset/list-assets'
import { moveAssets } from './asset/move-assets'
import { getAssetRender, readAsset } from './asset/read-asset'
import { renameAsset } from './asset/rename-asset'
import { restoreArchivedAssets } from './asset/restore-archived-assets'
import { searchAssets } from './asset/search-assets'
import { createComment } from './comment/create-comment'
import { listComments } from './comment/list-comments'
@@ -35,6 +37,8 @@ export const operationDefinitions = [
moveAssets,
copyAssets,
deleteAsset,
archiveAssets,
restoreArchivedAssets,
readAsset,
getAssetRender,
downloadAsset,
@@ -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),
)
})
})
})
+32 -9
View File
@@ -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!))
+7
View File
@@ -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,
@@ -0,0 +1,56 @@
import { m } from '@/ui/paraglide/messages.js'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
export interface ArchiveConfirmDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
mode: 'archive' | 'restore'
onConfirm: () => void
isPending?: boolean
}
export function ArchiveConfirmDialog({
open,
onOpenChange,
mode,
onConfirm,
isPending = false,
}: ArchiveConfirmDialogProps) {
const isArchive = mode === 'archive'
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent data-testid="archive-confirm-dialog">
<AlertDialogHeader>
<AlertDialogTitle>
{isArchive ? m.archive_confirm_title() : m.restore_archive_confirm_title()}
</AlertDialogTitle>
<AlertDialogDescription>
{isArchive ? m.archive_confirm_description() : m.restore_archive_confirm_description()}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isPending}>{m.cancel()}</AlertDialogCancel>
<AlertDialogAction
data-testid="archive-confirm-submit"
disabled={isPending}
onClick={(e) => {
e.preventDefault()
onConfirm()
}}
>
{isArchive ? m.archive() : m.restore_from_archive()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}
+106 -6
View File
@@ -33,6 +33,7 @@ import type { AncestorFolder } from '@shumai/dtos'
import { Link, useNavigate } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import {
Archive,
Bot,
Check,
ChevronDown,
@@ -41,6 +42,7 @@ import {
History,
LayoutGrid,
List,
Loader2,
Menu,
SquareKanban,
} from 'lucide-react'
@@ -49,6 +51,7 @@ import { useDualSidebarStore } from '@/ui/stores/dual-sidebar'
import { ManageVersionsDialog } from './manage-versions-dialog'
import { AssetLinkedTasksDialog } from './kanban/asset-linked-tasks-dialog'
import { getVideoResolutionLabel } from '@/ui/lib/media'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
interface BreadcrumbNavProps {
teamId: string
@@ -60,6 +63,7 @@ interface BreadcrumbNavProps {
name?: string
type: 'file' | 'folder'
version?: number
status?: string
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
}
isRootFolder: boolean
@@ -78,6 +82,8 @@ interface BreadcrumbNavProps {
onFolderClick?: (folderId: string) => void
onRename?: () => void
onDelete?: () => void
onArchive?: () => void
onRestoreArchive?: () => void
fileId?: string
downloadInfo?: {
originalKey?: string
@@ -93,6 +99,7 @@ interface BreadcrumbNavProps {
id: string
version: number
name?: string | null
status?: string | null
previewUrl?: string | null
creator?: { id: string; name: string | null } | null
agent?: { id: string; name: string } | null
@@ -122,6 +129,8 @@ export function BreadcrumbNav({
onFolderClick,
onRename,
onDelete,
onArchive,
onRestoreArchive,
fileId,
shareId,
allowDownload = true,
@@ -133,6 +142,7 @@ export function BreadcrumbNav({
}: BreadcrumbNavProps) {
const navigate = useNavigate()
const { canEdit } = usePermissions(projectId)
const { archiveStorageEnabled } = useArchiveConfig()
const { openMobileMenu } = useDualSidebarStore()
const [isManageVersionsOpen, setIsManageVersionsOpen] = useState(false)
const [isLinkedTasksOpen, setIsLinkedTasksOpen] = useState(false)
@@ -210,6 +220,10 @@ export function BreadcrumbNav({
const isAudio = currentAsset.proxyType === 'audio'
const hasVideoTranscodes = !isAudio && (downloadInfo?.videoTranscodes?.length ?? 0) > 0
const isOriginalUnavailable =
currentAsset.status === 'archived' ||
currentAsset.status === 'archiving' ||
currentAsset.status === 'restoring'
const hasTerminal = Boolean(customTerminalBreadcrumb || (!isRootFolder && !compareMode))
@@ -264,6 +278,36 @@ export function BreadcrumbNav({
v{currentAsset.version}
</Badge>
)}
{currentAsset.status === 'archived' && (
<Badge
variant="secondary"
data-testid="detail-header-archived-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Archive className="h-3 w-3" />
<span>{m.archived_status()}</span>
</Badge>
)}
{currentAsset.status === 'archiving' && (
<Badge
variant="secondary"
data-testid="detail-header-archiving-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Loader2 className="h-3 w-3 animate-spin" />
<span>{m.archiving_status()}</span>
</Badge>
)}
{currentAsset.status === 'restoring' && (
<Badge
variant="secondary"
data-testid="detail-header-restoring-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Loader2 className="h-3 w-3 animate-spin" />
<span>{m.restoring_status()}</span>
</Badge>
)}
<DropdownMenuTrigger
asChild
onClick={(e) => e.stopPropagation()}
@@ -306,7 +350,13 @@ export function BreadcrumbNav({
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleDownload(downloadInfo.originalKey!)}
disabled={isOriginalUnavailable}
title={
isOriginalUnavailable ? m.original_archived_tooltip() : undefined
}
onClick={() =>
!isOriginalUnavailable && handleDownload(downloadInfo.originalKey!)
}
className="flex items-center justify-between"
>
<span>Original</span>
@@ -322,9 +372,12 @@ export function BreadcrumbNav({
) : (
<DropdownMenuItem
onClick={() =>
downloadInfo?.originalKey && handleDownload(downloadInfo.originalKey)
downloadInfo?.originalKey &&
!isOriginalUnavailable &&
handleDownload(downloadInfo.originalKey)
}
disabled={!downloadInfo?.originalKey}
disabled={!downloadInfo?.originalKey || isOriginalUnavailable}
title={isOriginalUnavailable ? m.original_archived_tooltip() : undefined}
>
{m.download()}
</DropdownMenuItem>
@@ -332,6 +385,27 @@ export function BreadcrumbNav({
{canEdit && onRename && (
<DropdownMenuItem onClick={onRename}>{m.rename()}</DropdownMenuItem>
)}
{canEdit &&
archiveStorageEnabled &&
!isPublic &&
(!currentAsset.status || currentAsset.status === 'processed') &&
onArchive && (
<DropdownMenuItem data-testid="detail-header-archive-action" onClick={onArchive}>
{m.archive()}
</DropdownMenuItem>
)}
{canEdit &&
archiveStorageEnabled &&
!isPublic &&
currentAsset.status === 'archived' &&
onRestoreArchive && (
<DropdownMenuItem
data-testid="detail-header-restore-archive-action"
onClick={onRestoreArchive}
>
{m.restore_from_archive()}
</DropdownMenuItem>
)}
{canEdit && onDelete && (
<DropdownMenuItem
onClick={onDelete}
@@ -387,9 +461,35 @@ export function BreadcrumbNav({
</div>
<div className="flex flex-col flex-1 min-w-0 text-left">
<span className="truncate text-sm font-semibold text-foreground">
{v.name}
</span>
<div className="flex items-center gap-1.5 min-w-0">
<span className="truncate text-sm font-semibold text-foreground">
{v.name}
</span>
{v.status === 'archived' && (
<Badge
variant="secondary"
className="gap-0.5 px-1 py-0 text-[10px] shrink-0"
>
{m.archived_status()}
</Badge>
)}
{v.status === 'archiving' && (
<Badge
variant="secondary"
className="gap-0.5 px-1 py-0 text-[10px] shrink-0"
>
{m.archiving_status()}
</Badge>
)}
{v.status === 'restoring' && (
<Badge
variant="secondary"
className="gap-0.5 px-1 py-0 text-[10px] shrink-0"
>
{m.restoring_status()}
</Badge>
)}
</div>
<span className="truncate text-xs text-muted-foreground flex items-center gap-1">
{v.agent ? (
<>
@@ -115,7 +115,12 @@ export function CompareControlBar({
onZoomOut={onZoomOut}
onFit={onFit}
onDownload={() => onDownload()}
canDownload={!!activeAsset?.media?.original?.key}
canDownload={
!!activeAsset?.media?.original?.key &&
activeAsset.status !== 'archived' &&
activeAsset.status !== 'archiving' &&
activeAsset.status !== 'restoring'
}
fullscreen={{ isFullScreen, onToggle: onToggleFullScreen }}
allowDownload={allowDownload}
/>
@@ -266,6 +266,16 @@ export function WorkflowTasksDashboard({ teamId }: WorkflowTasksDashboardProps)
</Badge>
)
}
if (type === 'archive_asset' || type === 'restore_asset') {
return (
<Badge
variant="outline"
className="bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20 font-mono text-xs"
>
{type}
</Badge>
)
}
return (
<Badge variant="secondary" className="font-mono text-xs">
{type}
@@ -11,6 +11,8 @@ import {
ContextMenuPortal,
} from '@/ui/components/ui/context-menu'
import {
Archive,
ArchiveRestore,
Download,
Edit,
FolderPlus,
@@ -33,6 +35,9 @@ interface FileBrowserContextMenuProps {
onDownload: (items: AssetInfo[]) => void
onCopyNameAndDownloadLink?: (items: AssetInfo[]) => void
onRestore: (items: AssetInfo[]) => void
onArchive?: (items: AssetInfo[]) => void
onRestoreArchive?: (items: AssetInfo[]) => void
archiveStorageEnabled?: boolean
onNewFolder: (name: string) => void
onUploadFile: () => void
onUploadFolder: () => void
@@ -61,6 +66,9 @@ export function FileBrowserContextMenu({
onDownload,
onCopyNameAndDownloadLink,
onRestore,
onArchive,
onRestoreArchive,
archiveStorageEnabled = false,
onNewFolder,
onUploadFile,
onUploadFolder,
@@ -117,6 +125,36 @@ export function FileBrowserContextMenu({
onRestore(itemsToRestore)
}
const canArchiveSelection = itemsToModify.some((i) => {
if (i.type === 'folder') return true
if (i.type === 'version_stack') {
return (
i.status === 'processed' ||
(i.versionStack?.versions.some((v) => !v.status || v.status === 'processed') ?? false)
)
}
return i.status === 'processed'
})
const canRestoreArchiveSelection = itemsToModify.some((i) => {
if (i.type === 'folder') return true
if (i.type === 'version_stack') {
return (
i.status === 'archived' ||
(i.versionStack?.versions.some((v) => v.status === 'archived') ?? false)
)
}
return i.status === 'archived'
})
const isDownloadUnavailable =
itemsToModify.length > 0 &&
itemsToModify.every(
(i) =>
i.type === 'file' &&
(i.status === 'archived' || i.status === 'archiving' || i.status === 'restoring'),
)
if (isRecents) {
return null
}
@@ -196,11 +234,11 @@ export function FileBrowserContextMenu({
e.preventDefault()
}}
>
<ContextMenuItem onSelect={handleDownload}>
<ContextMenuItem onSelect={handleDownload} disabled={isDownloadUnavailable}>
<Download className="mr-2 h-4 w-4" />
<span>{m.download()}</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink}>
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink} disabled={isDownloadUnavailable}>
<Copy className="mr-2 h-4 w-4" />
<span>{m.copy_name_and_download_link()}</span>
</ContextMenuItem>
@@ -216,6 +254,24 @@ export function FileBrowserContextMenu({
<span>{m.copy_to()}</span>
</ContextMenuItem>
)}
{canEdit && archiveStorageEnabled && canArchiveSelection && (
<ContextMenuItem
data-testid="context-menu-archive"
onSelect={() => onArchive?.(itemsToModify)}
>
<Archive className="mr-2 h-4 w-4" />
<span>{m.archive()}</span>
</ContextMenuItem>
)}
{canEdit && archiveStorageEnabled && canRestoreArchiveSelection && (
<ContextMenuItem
data-testid="context-menu-restore-archive"
onSelect={() => onRestoreArchive?.(itemsToModify)}
>
<ArchiveRestore className="mr-2 h-4 w-4" />
<span>{m.restore_from_archive()}</span>
</ContextMenuItem>
)}
{canEdit && (
<ContextMenuItem onSelect={handleDelete} className="text-destructive">
<Trash2 className="mr-2 h-4 w-4" />
@@ -270,11 +326,11 @@ export function FileBrowserContextMenu({
<span>{m.rename()}</span>
</ContextMenuItem>
)}
<ContextMenuItem onSelect={handleDownload}>
<ContextMenuItem onSelect={handleDownload} disabled={isDownloadUnavailable}>
<Download className="mr-2 h-4 w-4" />
<span>{m.download()}</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink}>
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink} disabled={isDownloadUnavailable}>
<Copy className="mr-2 h-4 w-4" />
<span>{m.copy_name_and_download_link()}</span>
</ContextMenuItem>
@@ -306,6 +362,25 @@ export function FileBrowserContextMenu({
</ContextMenuItem>
)}
{canEdit && archiveStorageEnabled && canArchiveSelection && (
<ContextMenuItem
data-testid="context-menu-archive"
onSelect={() => onArchive?.(itemsToModify)}
>
<Archive className="mr-2 h-4 w-4" />
<span>{m.archive()}</span>
</ContextMenuItem>
)}
{canEdit && archiveStorageEnabled && canRestoreArchiveSelection && (
<ContextMenuItem
data-testid="context-menu-restore-archive"
onSelect={() => onRestoreArchive?.(itemsToModify)}
>
<ArchiveRestore className="mr-2 h-4 w-4" />
<span>{m.restore_from_archive()}</span>
</ContextMenuItem>
)}
{item.type === 'folder' && onOpenAgentsMd && (
<ContextMenuItem onSelect={() => onOpenAgentsMd(item)}>
<FileText className="mr-2 h-4 w-4" />
@@ -58,6 +58,8 @@ import { FileBrowserListView } from './list-view'
import { FileBrowserToolbar } from './toolbar'
import { useFileActions } from './use-file-actions'
import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { ArchiveConfirmDialog } from '../archive-confirm-dialog'
interface FileBrowserProps {
teamId: string
@@ -484,6 +486,8 @@ export function FileBrowser({
handleRestore,
handleDownload,
handleCopyNameAndDownloadLink,
handleArchive,
handleRestoreArchive,
handleAction,
onRenameSubmit,
isDeleteDialogOpen,
@@ -493,7 +497,13 @@ export function FileBrowser({
setIsDownloadDialogOpen,
isLoadingLinks,
resolvedFiles,
skippedArchivedCount,
startDownload,
archiveConfirmState,
setArchiveConfirmState,
confirmArchiveOrRestore,
isArchiving,
isRestoringArchive,
} = useFileActions({
teamId,
projectId,
@@ -504,6 +514,7 @@ export function FileBrowser({
isPublic,
shareId,
})
const { archiveStorageEnabled } = useArchiveConfig()
const [isEmptyTrashDialogOpen, setIsEmptyTrashDialogOpen] = useState(false)
const { mutate: emptyTrash, isPending: isEmptyingTrash } = useMutation({
@@ -758,7 +769,10 @@ export function FileBrowser({
}
return
}
handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item)
handleAction(
action as 'rename' | 'delete' | 'download' | 'restore' | 'archive' | 'restore-archive',
item,
)
},
isRecentlyDeleted,
isRecents,
@@ -767,6 +781,7 @@ export function FileBrowser({
allowDownload,
fields: displayedFields,
canEdit,
archiveStorageEnabled,
isExternalDragging,
externalOverFolderId,
setExternalOverFolderId,
@@ -1172,6 +1187,9 @@ export function FileBrowser({
setMoveCopyMode('copy')
}}
onRestore={handleRestore}
onArchive={handleArchive}
onRestoreArchive={handleRestoreArchive}
archiveStorageEnabled={archiveStorageEnabled}
isRecentlyDeleted={isRecentlyDeleted}
isRecents={isRecents}
shareLinks={shareLinksData?.data ?? []}
@@ -1296,6 +1314,14 @@ export function FileBrowser({
<span className="font-semibold text-foreground">{resolvedFiles.length}</span>{' '}
file(s).
</div>
{skippedArchivedCount > 0 && (
<div
data-testid="download-skipped-archived-notice"
className="text-sm text-amber-600 dark:text-amber-400"
>
{m.download_skipped_archived_notice({ count: skippedArchivedCount })}
</div>
)}
<div className="flex items-start gap-3 p-3 text-sm rounded-lg bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-900/30">
<AlertTriangle className="h-5 w-5 shrink-0 mt-0.5" />
<div>
@@ -1356,6 +1382,14 @@ export function FileBrowser({
sharePassword={sharePassword}
isPublic={isPublic}
/>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
mode={archiveConfirmState.mode}
onConfirm={confirmArchiveOrRestore}
isPending={isArchiving || isRestoringArchive}
/>
</>
)
}
@@ -683,4 +683,93 @@ describe('FileCard', () => {
expect(screen.getByDisplayValue('42')).toBeTruthy()
expect(onSelect).not.toHaveBeenCalled()
})
it('renders Archived, Archiving, and Restoring badges and Archive / Restore menu actions when archiveStorageEnabled is true', () => {
const onAction = vi.fn()
const archivedItem: AssetInfo = {
...fileItem,
status: 'archived',
} as AssetInfo
const { rerender } = render(
<QueryClientProvider client={queryClient}>
<FileCard
item={archivedItem}
isSelected={false}
isChecked={false}
isEditing={false}
onSelect={vi.fn()}
onDoubleClick={vi.fn()}
onContextMenu={vi.fn()}
onDragStart={vi.fn()}
onDrop={vi.fn()}
onRename={vi.fn()}
onFinishEditing={vi.fn()}
onSaveField={vi.fn()}
onAction={onAction}
fields={[]}
canEdit={true}
archiveStorageEnabled={true}
/>
</QueryClientProvider>,
)
expect(screen.getByTestId('file-card-archived-badge')).toBeTruthy()
const moreBtn = screen.getByRole('button', { name: '' })
fireEvent.keyDown(moreBtn, { key: 'ArrowDown', code: 'ArrowDown' })
const restoreItem = screen.getByTestId('file-card-restore-archive-action')
expect(restoreItem).toBeTruthy()
fireEvent.click(restoreItem)
expect(onAction).toHaveBeenCalledWith('restore-archive', archivedItem)
rerender(
<QueryClientProvider client={queryClient}>
<FileCard
item={{ ...fileItem, status: 'archiving' } as AssetInfo}
isSelected={false}
isChecked={false}
isEditing={false}
onSelect={vi.fn()}
onDoubleClick={vi.fn()}
onContextMenu={vi.fn()}
onDragStart={vi.fn()}
onDrop={vi.fn()}
onRename={vi.fn()}
onFinishEditing={vi.fn()}
onSaveField={vi.fn()}
onAction={onAction}
fields={[]}
canEdit={true}
archiveStorageEnabled={true}
/>
</QueryClientProvider>,
)
expect(screen.getByTestId('file-card-archiving-badge')).toBeTruthy()
rerender(
<QueryClientProvider client={queryClient}>
<FileCard
item={{ ...fileItem, status: 'restoring' } as AssetInfo}
isSelected={false}
isChecked={false}
isEditing={false}
onSelect={vi.fn()}
onDoubleClick={vi.fn()}
onContextMenu={vi.fn()}
onDragStart={vi.fn()}
onDrop={vi.fn()}
onRename={vi.fn()}
onFinishEditing={vi.fn()}
onSaveField={vi.fn()}
onAction={onAction}
fields={[]}
canEdit={true}
archiveStorageEnabled={true}
/>
</QueryClientProvider>,
)
expect(screen.getByTestId('file-card-restoring-badge')).toBeTruthy()
})
})
@@ -29,11 +29,14 @@ import { useUploadStore } from '@/ui/stores/upload'
import { useDraggable, useDroppable } from '@dnd-kit/react'
import {
AlertCircle,
Archive,
ArchiveRestore,
Clock,
Download,
Edit,
History,
Layers,
Loader2,
MessageCircleMore,
MoreHorizontal,
Trash2,
@@ -64,7 +67,15 @@ interface FileCardProps {
dragState?: DragState
disabled?: boolean
onAction?: (
action: 'rename' | 'delete' | 'download' | 'restore' | 'remove-from-share' | 'manage-versions',
action:
| 'rename'
| 'delete'
| 'download'
| 'restore'
| 'remove-from-share'
| 'manage-versions'
| 'archive'
| 'restore-archive',
item: AssetInfo,
) => void
isRecentlyDeleted?: boolean
@@ -73,6 +84,7 @@ interface FileCardProps {
fields?: MetadataFieldInfo[]
isShareView?: boolean
canEdit?: boolean
archiveStorageEnabled?: boolean
/** When false, hides the download action. Defaults to true. */
allowDownload?: boolean
hideCheckbox?: boolean
@@ -104,6 +116,7 @@ export function FileCard({
fields = [],
isShareView,
canEdit = true,
archiveStorageEnabled = false,
allowDownload = true,
hideCheckbox = false,
hideActions = false,
@@ -133,11 +146,23 @@ export function FileCard({
})
const displayItem = useMemo(() => {
if (item.status === 'processed' || item.status === 'error' || item.status === 'failed') {
if (
item.status === 'processed' ||
item.status === 'archived' ||
item.status === 'error' ||
item.status === 'failed'
) {
return item
}
if (item.status === 'archiving' && polledItem?.status === 'processed') {
return item
}
if (item.status === 'restoring' && polledItem?.status === 'archived') {
return item
}
if (
polledItem?.status === 'processed' ||
polledItem?.status === 'archived' ||
polledItem?.status === 'error' ||
polledItem?.status === 'failed'
) {
@@ -301,6 +326,21 @@ export function FileCard({
}
const failedErrorMessage = displayItem.media?.error || m.processing_failed()
const isOriginalUnavailable =
displayItem.status === 'archived' ||
displayItem.status === 'archiving' ||
displayItem.status === 'restoring'
const canArchiveItem =
displayItem.type === 'version_stack'
? displayItem.status === 'processed' ||
(displayItem.versionStack?.versions.some((v) => !v.status || v.status === 'processed') ??
false)
: displayItem.status === 'processed'
const canRestoreArchiveItem =
displayItem.type === 'version_stack'
? displayItem.status === 'archived' ||
(displayItem.versionStack?.versions.some((v) => v.status === 'archived') ?? false)
: displayItem.status === 'archived'
const previewBadges =
daysLeft !== null ||
@@ -381,6 +421,33 @@ export function FileCard({
displayItem.versionStack.versions.length}
</Badge>
)}
{displayItem.status === 'archived' && (
<span
data-testid="file-card-archived-badge"
className="flex select-none items-center gap-1 rounded bg-black/60 px-1.5 py-0.5 text-xs font-medium text-white shadow-sm"
>
<Archive className="h-3 w-3" />
<span>{m.archived_status()}</span>
</span>
)}
{displayItem.status === 'archiving' && (
<span
data-testid="file-card-archiving-badge"
className="flex select-none items-center gap-1 rounded bg-black/60 px-1.5 py-0.5 text-xs font-medium text-white shadow-sm"
>
<Loader2 className="h-3 w-3 animate-spin" />
<span>{m.archiving_status()}</span>
</span>
)}
{displayItem.status === 'restoring' && (
<span
data-testid="file-card-restoring-badge"
className="flex select-none items-center gap-1 rounded bg-black/60 px-1.5 py-0.5 text-xs font-medium text-white shadow-sm"
>
<Loader2 className="h-3 w-3 animate-spin" />
<span>{m.restoring_status()}</span>
</span>
)}
{isFailed && (
<TooltipProvider delayDuration={100}>
<Tooltip>
@@ -557,6 +624,7 @@ export function FileCard({
<>
{allowDownload && (
<DropdownMenuItem
disabled={displayItem.type !== 'version_stack' && isOriginalUnavailable}
onClick={(e) => {
e.stopPropagation()
onAction?.('download', item)
@@ -615,6 +683,7 @@ export function FileCard({
)}
{allowDownload && (
<DropdownMenuItem
disabled={displayItem.type !== 'version_stack' && isOriginalUnavailable}
onClick={(e) => {
e.stopPropagation()
onAction?.('download', item)
@@ -624,6 +693,30 @@ export function FileCard({
<span>{m.download()}</span>
</DropdownMenuItem>
)}
{canEdit && archiveStorageEnabled && canArchiveItem && (
<DropdownMenuItem
data-testid="file-card-archive-action"
onClick={(e) => {
e.stopPropagation()
onAction?.('archive', item)
}}
>
<Archive className="mr-2 h-4 w-4" />
<span>{m.archive()}</span>
</DropdownMenuItem>
)}
{canEdit && archiveStorageEnabled && canRestoreArchiveItem && (
<DropdownMenuItem
data-testid="file-card-restore-archive-action"
onClick={(e) => {
e.stopPropagation()
onAction?.('restore-archive', item)
}}
>
<ArchiveRestore className="mr-2 h-4 w-4" />
<span>{m.restore_from_archive()}</span>
</DropdownMenuItem>
)}
{canEdit && (
<>
<DropdownMenuSeparator />
@@ -4,7 +4,7 @@ import { m } from '@/ui/paraglide/messages.js'
import { useQuery } from '@tanstack/react-query'
import { useDraggable } from '@dnd-kit/react'
import { AlertCircle, File, Folder, MoreVertical, AudioLines } from 'lucide-react'
import { AlertCircle, Archive, AudioLines, File, Folder, Loader2, MoreVertical } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { cn } from '@/ui/lib/utils'
import { formatSize } from '@/ui/lib/format'
@@ -88,11 +88,23 @@ export function FileListItem({
})
const displayItem = useMemo(() => {
if (item.status === 'processed' || item.status === 'error' || item.status === 'failed') {
if (
item.status === 'processed' ||
item.status === 'archived' ||
item.status === 'error' ||
item.status === 'failed'
) {
return item
}
if (item.status === 'archiving' && polledItem?.status === 'processed') {
return item
}
if (item.status === 'restoring' && polledItem?.status === 'archived') {
return item
}
if (
polledItem?.status === 'processed' ||
polledItem?.status === 'archived' ||
polledItem?.status === 'error' ||
polledItem?.status === 'failed'
) {
@@ -316,6 +328,36 @@ export function FileListItem({
displayItem.versionStack.versions.length}
</Badge>
)}
{displayItem.status === 'archived' && (
<Badge
variant="secondary"
data-testid="file-list-item-archived-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Archive className="h-3 w-3" />
<span>{m.archived_status()}</span>
</Badge>
)}
{displayItem.status === 'archiving' && (
<Badge
variant="secondary"
data-testid="file-list-item-archiving-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Loader2 className="h-3 w-3 animate-spin" />
<span>{m.archiving_status()}</span>
</Badge>
)}
{displayItem.status === 'restoring' && (
<Badge
variant="secondary"
data-testid="file-list-item-restoring-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Loader2 className="h-3 w-3 animate-spin" />
<span>{m.restoring_status()}</span>
</Badge>
)}
</div>
</div>
<div
@@ -12,7 +12,16 @@ import { useDraggable, useDroppable } from '@dnd-kit/react'
import type { AssetInfo, ChildPreview } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import { getTrashDaysLeft } from '@/ui/lib/time'
import { Clock, Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
import {
Archive,
ArchiveRestore,
Clock,
Download,
Edit,
History,
MoreHorizontal,
Trash2,
} from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import type { DragState } from '../dnd-types'
import { FilePreview } from './file-preview'
@@ -34,13 +43,21 @@ interface FolderCardProps {
dragState?: DragState
disabled?: boolean
onAction?: (
action: 'rename' | 'delete' | 'download' | 'restore' | 'remove-from-share',
action:
| 'rename'
| 'delete'
| 'download'
| 'restore'
| 'remove-from-share'
| 'archive'
| 'restore-archive',
item: AssetInfo,
) => void
isRecentlyDeleted?: boolean
isRecents?: boolean
selectedCount?: number
canEdit?: boolean
archiveStorageEnabled?: boolean
isShareView?: boolean
isExternalDragging?: boolean
externalOverFolderId?: string | null
@@ -127,6 +144,7 @@ export function FolderCard({
isRecents,
selectedCount,
canEdit = true,
archiveStorageEnabled = false,
isShareView,
isExternalDragging,
externalOverFolderId,
@@ -455,6 +473,30 @@ export function FolderCard({
<span>{m.download()}</span>
</DropdownMenuItem>
)}
{canEdit && archiveStorageEnabled && (
<>
<DropdownMenuItem
data-testid="folder-card-archive-action"
onClick={(e) => {
e.stopPropagation()
onAction?.('archive', item)
}}
>
<Archive className="mr-2 h-4 w-4" />
<span>{m.archive()}</span>
</DropdownMenuItem>
<DropdownMenuItem
data-testid="folder-card-restore-archive-action"
onClick={(e) => {
e.stopPropagation()
onAction?.('restore-archive', item)
}}
>
<ArchiveRestore className="mr-2 h-4 w-4" />
<span>{m.restore_from_archive()}</span>
</DropdownMenuItem>
</>
)}
{canEdit && (
<>
<DropdownMenuSeparator />
@@ -55,6 +55,8 @@ import { FolderCard } from './folder-card'
import { useFileActions } from './use-file-actions'
import { MobileFileBrowserContentSkeleton } from '../loading-skeletons'
import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { ArchiveConfirmDialog } from '../archive-confirm-dialog'
export interface MobileFileBrowserProps {
teamId: string
@@ -167,7 +169,13 @@ export function MobileFileBrowser({
setIsDownloadDialogOpen,
isLoadingLinks,
resolvedFiles,
skippedArchivedCount,
startDownload,
archiveConfirmState,
setArchiveConfirmState,
confirmArchiveOrRestore,
isArchiving,
isRestoringArchive,
} = useFileActions({
teamId,
projectId,
@@ -178,6 +186,7 @@ export function MobileFileBrowser({
isPublic,
shareId,
})
const { archiveStorageEnabled } = useArchiveConfig()
// Infinite scroll trigger
const { ref: loadMoreRef, inView } = useInView()
@@ -510,12 +519,22 @@ export function MobileFileBrowser({
onRename={(newName) => onRenameSubmit(folder, newName)}
onFinishEditing={() => setEditingItemId(null)}
onAction={(action, item) =>
handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item)
handleAction(
action as
| 'rename'
| 'delete'
| 'download'
| 'restore'
| 'archive'
| 'restore-archive',
item,
)
}
isRecentlyDeleted={isRecentlyDeleted}
isRecents={isRecents}
selectedCount={selectedIds.size}
canEdit={canEdit}
archiveStorageEnabled={archiveStorageEnabled}
isShareView={isShareView}
allowDownload={allowDownload}
/>
@@ -563,12 +582,22 @@ export function MobileFileBrowser({
onSaveField={(fieldId, value) => onSaveField?.(file.id!, fieldId, value)}
fields={[]}
onAction={(action, item) =>
handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item)
handleAction(
action as
| 'rename'
| 'delete'
| 'download'
| 'restore'
| 'archive'
| 'restore-archive',
item,
)
}
isRecentlyDeleted={isRecentlyDeleted}
isRecents={isRecents}
selectedCount={selectedIds.size}
canEdit={canEdit}
archiveStorageEnabled={archiveStorageEnabled}
isShareView={isShareView}
allowDownload={allowDownload}
/>
@@ -742,6 +771,14 @@ export function MobileFileBrowser({
<div className="text-sm text-muted-foreground">
{m.download_includes_files({ count: resolvedFiles.length })}
</div>
{skippedArchivedCount > 0 && (
<div
data-testid="download-skipped-archived-notice"
className="text-sm text-amber-600 dark:text-amber-400"
>
{m.download_skipped_archived_notice({ count: skippedArchivedCount })}
</div>
)}
<div className="flex items-start gap-3 p-3 text-sm rounded-lg bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-900/30">
<AlertTriangle className="h-5 w-5 shrink-0 mt-0.5" />
<div>
@@ -777,6 +814,14 @@ export function MobileFileBrowser({
</DialogFooter>
</DialogContent>
</Dialog>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
mode={archiveConfirmState.mode}
onConfirm={confirmArchiveOrRestore}
isPending={isArchiving || isRestoringArchive}
/>
</div>
)
}
@@ -38,6 +38,12 @@ export function useFileActions({
const [resolvedFiles, setResolvedFiles] = useState<
Array<{ id: string; name: string; url: string }>
>([])
const [skippedArchivedCount, setSkippedArchivedCount] = useState(0)
const [archiveConfirmState, setArchiveConfirmState] = useState<{
open: boolean
mode: 'archive' | 'restore'
items: AssetInfo[]
}>({ open: false, mode: 'archive', items: [] })
const queryClient = useQueryClient()
const $createFolder = client.api.folders.$post
@@ -136,6 +142,32 @@ export function useFileActions({
},
})
type ArchiveFilesPost = typeof client.api.files.archive.$post
const { mutate: archiveFiles, isPending: isArchiving } = useMutation<
InferResponseType<ArchiveFilesPost, 200>,
Error,
InferRequestType<ArchiveFilesPost>
>({
mutationFn: async (request) => {
const res = await client.api.files.archive.$post(request)
if (!res.ok) throw new Error(m.archive_failed_toast())
return (await res.json()) as unknown as InferResponseType<ArchiveFilesPost, 200>
},
})
type RestoreArchiveFilesPost = (typeof client.api.files)['restore-archive']['$post']
const { mutate: restoreArchiveFiles, isPending: isRestoringArchive } = useMutation<
InferResponseType<RestoreArchiveFilesPost, 200>,
Error,
InferRequestType<RestoreArchiveFilesPost>
>({
mutationFn: async (request) => {
const res = await client.api.files['restore-archive'].$post(request)
if (!res.ok) throw new Error(m.restore_archive_failed_toast())
return (await res.json()) as unknown as InferResponseType<RestoreArchiveFilesPost, 200>
},
})
const handleRename = (item: AssetInfo) => {
setEditingItemId(item.id!)
}
@@ -222,11 +254,21 @@ export function useFileActions({
setIsDownloadDialogOpen(true)
setIsLoadingLinks(true)
setResolvedFiles([])
setSkippedArchivedCount(0)
try {
if (isPublic && shareId) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const links: Array<{ id: string; name: string; url: string }> = []
let skipped = 0
for (const item of items) {
if (
item.status === 'archived' ||
item.status === 'archiving' ||
item.status === 'restoring'
) {
skipped++
continue
}
const key = item.media?.original?.key
if (!key || !item.id) continue
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
@@ -245,11 +287,24 @@ export function useFileActions({
links.push({ id: item.id, name: item.name || 'download', url })
}
}
setSkippedArchivedCount(skipped)
if (links.length === 0 && skipped > 0) {
setIsDownloadDialogOpen(false)
toast.error(m.download_all_archived_error())
return
}
setResolvedFiles(links)
} else {
const res = await getDownloadLinks({
json: { ids: items.map((i) => i.id!) },
})
const skipped = res.skippedArchivedCount ?? 0
setSkippedArchivedCount(skipped)
if (res.files.length === 0 && skipped > 0) {
setIsDownloadDialogOpen(false)
toast.error(m.download_all_archived_error())
return
}
setResolvedFiles(res.files)
}
} catch (error) {
@@ -268,7 +323,12 @@ export function useFileActions({
json: { ids: items.map((i) => i.id!) },
})
const files = res.files
if (files.length === 0) return
if (files.length === 0) {
if ((res.skippedArchivedCount ?? 0) > 0) {
toast.error(m.download_all_archived_error())
}
return
}
let text = ''
if (files.length === 1) {
@@ -287,6 +347,73 @@ export function useFileActions({
}
}
const handleArchive = (items: AssetInfo[]) => {
if (items.length === 0) return
setArchiveConfirmState({
open: true,
mode: 'archive',
items,
})
}
const handleRestoreArchive = (items: AssetInfo[]) => {
if (items.length === 0) return
setArchiveConfirmState({
open: true,
mode: 'restore',
items,
})
}
const confirmArchiveOrRestore = () => {
const ids = archiveConfirmState.items.map((i) => i.id!).filter(Boolean)
if (ids.length === 0) {
setArchiveConfirmState((prev) => ({ ...prev, open: false, items: [] }))
return
}
if (archiveConfirmState.mode === 'archive') {
archiveFiles(
{ json: { ids } },
{
onSuccess: (data) => {
if (data.archivedAssetIds.length > 0) {
toast.success(m.archive_started_toast({ count: data.archivedAssetIds.length }))
} else {
toast.info(m.archive_no_eligible_assets_toast())
}
queryClient.removeQueries({ queryKey: ['file', teamId] })
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
setArchiveConfirmState((prev) => ({ ...prev, open: false, items: [] }))
},
onError: () => {
toast.error(m.archive_failed_toast())
},
},
)
} else {
restoreArchiveFiles(
{ json: { ids } },
{
onSuccess: (data) => {
if (data.restoredAssetIds.length > 0) {
toast.success(
m.restore_archive_started_toast({ count: data.restoredAssetIds.length }),
)
} else {
toast.info(m.restore_archive_no_eligible_assets_toast())
}
queryClient.removeQueries({ queryKey: ['file', teamId] })
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
setArchiveConfirmState((prev) => ({ ...prev, open: false, items: [] }))
},
onError: () => {
toast.error(m.restore_archive_failed_toast())
},
},
)
}
}
const startDownload = () => {
const files = [...resolvedFiles]
setIsDownloadDialogOpen(false)
@@ -387,7 +514,14 @@ export function useFileActions({
}
const handleAction = (
action: 'rename' | 'delete' | 'download' | 'restore' | 'copy-name-and-download-link',
action:
| 'rename'
| 'delete'
| 'download'
| 'restore'
| 'copy-name-and-download-link'
| 'archive'
| 'restore-archive',
item: AssetInfo,
) => {
const isSelected = selectedIds.has(item.id!)
@@ -411,6 +545,12 @@ export function useFileActions({
case 'copy-name-and-download-link':
handleCopyNameAndDownloadLink(targetItems)
break
case 'archive':
handleArchive(targetItems)
break
case 'restore-archive':
handleRestoreArchive(targetItems)
break
}
}
@@ -422,6 +562,8 @@ export function useFileActions({
handleRestore,
handleDownload,
handleCopyNameAndDownloadLink,
handleArchive,
handleRestoreArchive,
handleNewFolder,
handleAction,
onRenameSubmit,
@@ -433,6 +575,12 @@ export function useFileActions({
setIsDownloadDialogOpen,
isLoadingLinks,
resolvedFiles,
skippedArchivedCount,
startDownload,
archiveConfirmState,
setArchiveConfirmState,
confirmArchiveOrRestore,
isArchiving,
isRestoringArchive,
}
}
@@ -45,6 +45,7 @@ export interface MobileFileDetailProps {
id: string
version: number
name?: string | null
status?: string | null
previewUrl?: string | null
}>
activeFileId: string
@@ -58,6 +59,8 @@ export interface MobileFileDetailProps {
onNavigateBack: () => void
onRenameFile?: (newName: string) => Promise<void>
onDeleteFile?: () => Promise<void>
onArchiveFile?: () => void
onRestoreArchiveFile?: () => void
onSaveField: (fieldId: string, value: unknown) => void
onSelectVersion?: (versionId: string) => void
}
@@ -81,6 +84,8 @@ export function MobileFileDetail({
onNavigateBack,
onRenameFile,
onDeleteFile,
onArchiveFile,
onRestoreArchiveFile,
onSaveField,
onSelectVersion,
}: MobileFileDetailProps) {
@@ -214,6 +219,7 @@ export function MobileFileDetail({
fileName={file.name}
folderName={folderName}
version={versionNumber}
status={file.status}
versions={versions}
activeFileId={activeFileId}
isPublic={isPublic}
@@ -232,6 +238,8 @@ export function MobileFileDetail({
setIsRenameDialogOpen(true)
}}
onDelete={() => setIsDeleteDialogOpen(true)}
onArchive={onArchiveFile}
onRestoreArchive={onRestoreArchiveFile}
onLinkedTasks={!isPublic ? () => setIsLinkedTasksOpen(true) : undefined}
linkedTaskCount={linkedTaskCount}
/>
@@ -16,10 +16,13 @@ import {
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import {
Archive,
ArchiveRestore,
ChevronDown,
ChevronLeft,
ChevronRight,
Download,
Loader2,
MoreVertical,
Pencil,
SquareKanban,
@@ -32,10 +35,12 @@ export interface MobileFileHeaderProps {
fileName: string
folderName?: string
version?: number
status?: string
versions?: Array<{
id: string
version: number
name?: string | null
status?: string | null
}>
activeFileId: string
isPublic?: boolean
@@ -60,6 +65,8 @@ export interface MobileFileHeaderProps {
onSelectVersion?: (versionId: string) => void
onRename?: () => void
onDelete?: () => void
onArchive?: () => void
onRestoreArchive?: () => void
onLinkedTasks?: () => void
linkedTaskCount?: number
}
@@ -68,6 +75,7 @@ export function MobileFileHeader({
fileName,
folderName,
version,
status,
versions,
activeFileId,
isPublic = false,
@@ -83,9 +91,13 @@ export function MobileFileHeader({
onSelectVersion,
onRename,
onDelete,
onArchive,
onRestoreArchive,
onLinkedTasks,
linkedTaskCount = 0,
}: MobileFileHeaderProps) {
const isOriginalUnavailable =
status === 'archived' || status === 'archiving' || status === 'restoring'
const handleDownload = async (key: string) => {
try {
const res =
@@ -183,6 +195,36 @@ export function MobileFileHeader({
)}
</div>
)}
{status === 'archived' && (
<Badge
variant="secondary"
data-testid="detail-header-archived-badge"
className="ml-1 gap-0.5 px-1 py-0 text-[10px] shrink-0"
>
<Archive className="h-2.5 w-2.5" />
<span>{m.archived_status()}</span>
</Badge>
)}
{status === 'archiving' && (
<Badge
variant="secondary"
data-testid="detail-header-archiving-badge"
className="ml-1 gap-0.5 px-1 py-0 text-[10px] shrink-0"
>
<Loader2 className="h-2.5 w-2.5 animate-spin" />
<span>{m.archiving_status()}</span>
</Badge>
)}
{status === 'restoring' && (
<Badge
variant="secondary"
data-testid="detail-header-restoring-badge"
className="ml-1 gap-0.5 px-1 py-0 text-[10px] shrink-0"
>
<Loader2 className="h-2.5 w-2.5 animate-spin" />
<span>{m.restoring_status()}</span>
</Badge>
)}
</div>
{/* Prev / Next file navigation buttons */}
@@ -257,7 +299,10 @@ export function MobileFileHeader({
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleDownload(downloadInfo.originalKey!)}
disabled={isOriginalUnavailable}
onClick={() =>
!isOriginalUnavailable && handleDownload(downloadInfo.originalKey!)
}
className="flex items-center justify-between text-xs cursor-pointer"
>
<span>{m.original?.() || 'Original'}</span>
@@ -273,9 +318,11 @@ export function MobileFileHeader({
) : (
<DropdownMenuItem
onClick={() =>
downloadInfo?.originalKey && handleDownload(downloadInfo.originalKey)
downloadInfo?.originalKey &&
!isOriginalUnavailable &&
handleDownload(downloadInfo.originalKey)
}
disabled={!downloadInfo?.originalKey}
disabled={!downloadInfo?.originalKey || isOriginalUnavailable}
className="flex items-center gap-2 text-xs cursor-pointer"
>
<Download className="h-3.5 w-3.5" />
@@ -345,6 +392,28 @@ export function MobileFileHeader({
</DropdownMenuItem>
)}
{/* Archive / Restore */}
{canEdit && !isPublic && (!status || status === 'processed') && onArchive && (
<DropdownMenuItem
data-testid="detail-header-archive-action"
onClick={onArchive}
className="flex items-center gap-2 text-xs cursor-pointer"
>
<Archive className="h-3.5 w-3.5" />
<span>{m.archive()}</span>
</DropdownMenuItem>
)}
{canEdit && !isPublic && status === 'archived' && onRestoreArchive && (
<DropdownMenuItem
data-testid="detail-header-restore-archive-action"
onClick={onRestoreArchive}
className="flex items-center gap-2 text-xs cursor-pointer"
>
<ArchiveRestore className="h-3.5 w-3.5" />
<span>{m.restore_from_archive()}</span>
</DropdownMenuItem>
)}
{/* Delete */}
{canEdit && onDelete && (
<>
+127 -1
View File
@@ -41,6 +41,8 @@ import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-q
import { useMatch, useNavigate, useParams } from '@tanstack/react-router'
import {
AlertTriangle,
Archive,
ArchiveRestore,
Bookmark,
ChevronDown,
ChevronRight,
@@ -63,6 +65,8 @@ import { useInView } from 'react-intersection-observer'
import { toast } from 'sonner'
import type { DragState } from './dnd-types'
import { m } from '@/ui/paraglide/messages.js'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { ArchiveConfirmDialog } from './archive-confirm-dialog'
interface FolderTreeProps {
teamId: string
@@ -96,6 +100,7 @@ export function FolderTree({
const navigate = useNavigate()
const queryClient = useQueryClient()
const { canEdit } = usePermissions(projectId)
const { archiveStorageEnabled } = useArchiveConfig()
const isRecentlyDeleted = useMatch({
from: '/projects/$projectId/recently-deleted',
shouldThrow: false,
@@ -310,17 +315,77 @@ export function FolderTree({
const [resolvedFiles, setResolvedFiles] = useState<
Array<{ id: string; name: string; url: string }>
>([])
const [skippedArchivedCount, setSkippedArchivedCount] = useState(0)
const [archiveConfirmState, setArchiveConfirmState] = useState<{
open: boolean
mode: 'archive' | 'restore'
folderId: string | null
}>({ open: false, mode: 'archive', folderId: null })
const { mutate: archiveFolder, isPending: isArchivingFolder } = useMutation({
mutationFn: async (folderId: string) => {
const res = await client.api.files.archive.$post({
json: { ids: [folderId] },
})
if (!res.ok) throw new Error(m.archive_failed_toast())
return await res.json()
},
onSuccess: (data) => {
if (data.archivedAssetIds.length > 0) {
toast.success(m.archive_started_toast({ count: data.archivedAssetIds.length }))
} else {
toast.info(m.archive_no_eligible_assets_toast())
}
queryClient.removeQueries({ queryKey: ['file', teamId] })
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
setArchiveConfirmState((prev) => ({ ...prev, open: false, folderId: null }))
},
onError: () => {
toast.error(m.archive_failed_toast())
},
})
const { mutate: restoreArchiveFolder, isPending: isRestoringArchiveFolder } = useMutation({
mutationFn: async (folderId: string) => {
const res = await client.api.files['restore-archive'].$post({
json: { ids: [folderId] },
})
if (!res.ok) throw new Error(m.restore_archive_failed_toast())
return await res.json()
},
onSuccess: (data) => {
if (data.restoredAssetIds.length > 0) {
toast.success(m.restore_archive_started_toast({ count: data.restoredAssetIds.length }))
} else {
toast.info(m.restore_archive_no_eligible_assets_toast())
}
queryClient.removeQueries({ queryKey: ['file', teamId] })
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
setArchiveConfirmState((prev) => ({ ...prev, open: false, folderId: null }))
},
onError: () => {
toast.error(m.restore_archive_failed_toast())
},
})
const handleDownloadFolder = async (folderId: string) => {
setIsDownloadOpen(true)
setIsLoadingLinks(true)
setResolvedFiles([])
setSkippedArchivedCount(0)
try {
const res = await client.api.files['download-links'].$post({
json: { ids: [folderId] },
})
if (!res.ok) throw new Error(m.failed_to_prepare_download_links())
const data = await res.json()
const skipped = data.skippedArchivedCount ?? 0
setSkippedArchivedCount(skipped)
if (data.files.length === 0 && skipped > 0) {
setIsDownloadOpen(false)
toast.error(m.download_all_archived_error())
return
}
setResolvedFiles(data.files)
} catch (error) {
toast.error(m.failed_to_prepare_download_links())
@@ -539,6 +604,13 @@ export function FolderTree({
onDownloadTrigger={(id) => {
handleDownloadFolder(id)
}}
archiveStorageEnabled={archiveStorageEnabled}
onArchiveTrigger={(id) => {
setArchiveConfirmState({ open: true, mode: 'archive', folderId: id })
}}
onRestoreArchiveTrigger={(id) => {
setArchiveConfirmState({ open: true, mode: 'restore', folderId: id })
}}
ancestorFolders={ancestorFolders}
/>
@@ -913,6 +985,14 @@ export function FolderTree({
<div className="text-sm text-muted-foreground">
{m.download_includes_files({ count: resolvedFiles.length })}
</div>
{skippedArchivedCount > 0 && (
<div
data-testid="download-skipped-archived-notice"
className="text-sm text-amber-600 dark:text-amber-400"
>
{m.download_skipped_archived_notice({ count: skippedArchivedCount })}
</div>
)}
<div className="flex items-start gap-3 p-3 text-sm rounded-lg bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-900/30">
<AlertTriangle className="h-5 w-5 shrink-0 mt-0.5" />
<div>
@@ -948,6 +1028,21 @@ export function FolderTree({
</DialogFooter>
</DialogContent>
</Dialog>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
mode={archiveConfirmState.mode}
onConfirm={() => {
if (!archiveConfirmState.folderId) return
if (archiveConfirmState.mode === 'archive') {
archiveFolder(archiveConfirmState.folderId)
} else {
restoreArchiveFolder(archiveConfirmState.folderId)
}
}}
isPending={isArchivingFolder || isRestoringArchiveFolder}
/>
</div>
)
}
@@ -1055,9 +1150,12 @@ interface FolderTreeItemProps {
onSelect?: (folder: AssetInfo) => void
selectedFolderId?: string
canEdit?: boolean
archiveStorageEnabled?: boolean
onRenameTrigger: (id: string, name: string) => void
onDeleteTrigger: (id: string) => void
onDownloadTrigger: (id: string) => void
onArchiveTrigger?: (id: string) => void
onRestoreArchiveTrigger?: (id: string) => void
ancestorFolders?: AncestorFolder[]
}
@@ -1071,9 +1169,12 @@ function FolderTreeItem({
onSelect,
selectedFolderId,
canEdit,
archiveStorageEnabled,
onRenameTrigger,
onDeleteTrigger,
onDownloadTrigger,
onArchiveTrigger,
onRestoreArchiveTrigger,
ancestorFolders,
}: FolderTreeItemProps) {
const isAncestor = useMemo(() => {
@@ -1251,7 +1352,7 @@ function FolderTreeItem({
<MoreHorizontal className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-32">
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => {
onRenameTrigger(folder.id!, folder.name)
@@ -1268,6 +1369,28 @@ function FolderTreeItem({
<Download className="mr-2 h-4 w-4" />
{m.download()}
</DropdownMenuItem>
{archiveStorageEnabled && (
<>
<DropdownMenuItem
data-testid="folder-tree-archive-action"
onClick={() => {
onArchiveTrigger?.(folder.id!)
}}
>
<Archive className="mr-2 h-4 w-4" />
{m.archive()}
</DropdownMenuItem>
<DropdownMenuItem
data-testid="folder-tree-restore-archive-action"
onClick={() => {
onRestoreArchiveTrigger?.(folder.id!)
}}
>
<ArchiveRestore className="mr-2 h-4 w-4" />
{m.restore_from_archive()}
</DropdownMenuItem>
</>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive focus:text-destructive focus:bg-destructive/10"
@@ -1308,6 +1431,9 @@ function FolderTreeItem({
onRenameTrigger={onRenameTrigger}
onDeleteTrigger={onDeleteTrigger}
onDownloadTrigger={onDownloadTrigger}
archiveStorageEnabled={archiveStorageEnabled}
onArchiveTrigger={onArchiveTrigger}
onRestoreArchiveTrigger={onRestoreArchiveTrigger}
ancestorFolders={ancestorFolders}
/>
))}
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
import {
@@ -8,6 +9,7 @@ import {
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { PointerActivationConstraints } from '@dnd-kit/dom'
@@ -16,9 +18,19 @@ import { isSortable, useSortable } from '@dnd-kit/react/sortable'
import type { StackVersionInfo } from '@shumai/dtos'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { format, parseISO } from 'date-fns'
import { Bot, FileIcon, GripVertical, MoreVertical, Trash2 } from 'lucide-react'
import {
Archive,
ArchiveRestore,
Bot,
FileIcon,
GripVertical,
Loader2,
MoreVertical,
Trash2,
} from 'lucide-react'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { ArchiveConfirmDialog } from './archive-confirm-dialog'
interface ManageVersionsDialogProps {
open: boolean
@@ -34,7 +46,10 @@ interface SortableVersionRowProps {
displayVersionNumber: number
index: number
canEdit: boolean
archiveStorageEnabled?: boolean
onRemove: (versionId: string) => void
onArchive?: (versionId: string) => void
onRestoreArchive?: (versionId: string) => void
}
function formatVersionDate(dateString?: string | null): string | null {
@@ -53,7 +68,10 @@ function SortableVersionRow({
displayVersionNumber,
index,
canEdit,
archiveStorageEnabled = false,
onRemove,
onArchive,
onRestoreArchive,
}: SortableVersionRowProps) {
const [dropdownOpen, setDropdownOpen] = useState(false)
const { ref, handleRef } = useSortable({
@@ -102,9 +120,41 @@ function SortableVersionRow({
{/* 4. Name / Creator / Create Date (2 rows) */}
<div className="flex flex-col flex-1 min-w-0 text-left">
{/* Row 1: Name */}
<span className="truncate text-sm font-medium text-foreground" title={version.name || ''}>
{version.name || 'Untitled'}
</span>
<div className="flex items-center gap-1.5 min-w-0">
<span className="truncate text-sm font-medium text-foreground" title={version.name || ''}>
{version.name || 'Untitled'}
</span>
{version.status === 'archived' && (
<Badge
variant="secondary"
data-testid="version-row-archived-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Archive className="h-3 w-3" />
<span>{m.archived_status()}</span>
</Badge>
)}
{version.status === 'archiving' && (
<Badge
variant="secondary"
data-testid="version-row-archiving-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Loader2 className="h-3 w-3 animate-spin" />
<span>{m.archiving_status()}</span>
</Badge>
)}
{version.status === 'restoring' && (
<Badge
variant="secondary"
data-testid="version-row-restoring-badge"
className="gap-1 px-1.5 py-0 text-xs shrink-0"
>
<Loader2 className="h-3 w-3 animate-spin" />
<span>{m.restoring_status()}</span>
</Badge>
)}
</div>
{/* Row 2: Creator & Create Date */}
<div className="flex items-center gap-1.5 text-xs text-muted-foreground truncate">
{version.agent ? (
@@ -148,6 +198,26 @@ function SortableVersionRow({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{archiveStorageEnabled && (!version.status || version.status === 'processed') && (
<DropdownMenuItem
data-testid="version-row-archive-action"
onClick={() => onArchive?.(version.id)}
className="cursor-pointer"
>
<Archive className="h-4 w-4 mr-2" />
<span>{m.archive()}</span>
</DropdownMenuItem>
)}
{archiveStorageEnabled && version.status === 'archived' && (
<DropdownMenuItem
data-testid="version-row-restore-archive-action"
onClick={() => onRestoreArchive?.(version.id)}
className="cursor-pointer"
>
<ArchiveRestore className="h-4 w-4 mr-2" />
<span>{m.restore_from_archive()}</span>
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={() => onRemove(version.id)}
className="text-destructive focus:text-destructive cursor-pointer"
@@ -171,7 +241,17 @@ export function ManageVersionsDialog({
onStackDissolved,
}: ManageVersionsDialogProps) {
const queryClient = useQueryClient()
const { archiveStorageEnabled } = useArchiveConfig()
const [localVersions, setLocalVersions] = useState<StackVersionInfo[]>([])
const [archiveConfirmState, setArchiveConfirmState] = useState<{
open: boolean
mode: 'archive' | 'restore'
versionId: string | null
}>({ open: false, mode: 'archive', versionId: null })
const hasTransitioningVersions = localVersions.some(
(v) => v.status === 'archiving' || v.status === 'restoring',
)
const { data: fetchedVersions, isLoading } = useQuery({
queryKey: ['version_stacks', stackId, 'versions'],
@@ -183,6 +263,57 @@ export function ManageVersionsDialog({
return (await res.json()) as StackVersionInfo[]
},
enabled: open && !!stackId,
refetchInterval: hasTransitioningVersions ? 2000 : false,
})
const { mutate: archiveVersion, isPending: isArchivingVersion } = useMutation({
mutationFn: async (versionId: string) => {
const res = await client.api.files.archive.$post({
json: { ids: [versionId] },
})
if (!res.ok) throw new Error(m.archive_failed_toast())
return await res.json()
},
onSuccess: (data) => {
if (data.archivedAssetIds.length > 0) {
toast.success(m.archive_started_toast({ count: data.archivedAssetIds.length }))
} else {
toast.info(m.archive_no_eligible_assets_toast())
}
queryClient.invalidateQueries({ queryKey: ['version_stacks', stackId, 'versions'] })
queryClient.invalidateQueries({ queryKey: ['files'] })
queryClient.removeQueries({ queryKey: ['file'] })
queryClient.invalidateQueries({ queryKey: ['search'] })
setArchiveConfirmState((prev) => ({ ...prev, open: false, versionId: null }))
},
onError: () => {
toast.error(m.archive_failed_toast())
},
})
const { mutate: restoreArchiveVersion, isPending: isRestoringArchiveVersion } = useMutation({
mutationFn: async (versionId: string) => {
const res = await client.api.files['restore-archive'].$post({
json: { ids: [versionId] },
})
if (!res.ok) throw new Error(m.restore_archive_failed_toast())
return await res.json()
},
onSuccess: (data) => {
if (data.restoredAssetIds.length > 0) {
toast.success(m.restore_archive_started_toast({ count: data.restoredAssetIds.length }))
} else {
toast.info(m.restore_archive_no_eligible_assets_toast())
}
queryClient.invalidateQueries({ queryKey: ['version_stacks', stackId, 'versions'] })
queryClient.invalidateQueries({ queryKey: ['files'] })
queryClient.removeQueries({ queryKey: ['file'] })
queryClient.invalidateQueries({ queryKey: ['search'] })
setArchiveConfirmState((prev) => ({ ...prev, open: false, versionId: null }))
},
onError: () => {
toast.error(m.restore_archive_failed_toast())
},
})
useEffect(() => {
@@ -318,7 +449,14 @@ export function ManageVersionsDialog({
displayVersionNumber={localVersions.length - index}
index={index}
canEdit={canEdit}
archiveStorageEnabled={archiveStorageEnabled}
onRemove={handleRemove}
onArchive={(versionId) =>
setArchiveConfirmState({ open: true, mode: 'archive', versionId })
}
onRestoreArchive={(versionId) =>
setArchiveConfirmState({ open: true, mode: 'restore', versionId })
}
/>
))}
</DragDropProvider>
@@ -326,6 +464,20 @@ export function ManageVersionsDialog({
)}
</ScrollArea>
</DialogContent>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(nextOpen) => setArchiveConfirmState((prev) => ({ ...prev, open: nextOpen }))}
mode={archiveConfirmState.mode}
onConfirm={() => {
if (!archiveConfirmState.versionId) return
if (archiveConfirmState.mode === 'archive') {
archiveVersion(archiveConfirmState.versionId)
} else {
restoreArchiveVersion(archiveConfirmState.versionId)
}
}}
isPending={isArchivingVersion || isRestoringArchiveVersion}
/>
</Dialog>
)
}
@@ -427,6 +427,7 @@ export function PublicShareManager({
currentAsset: {
name: viewingFileData?.name || currentFolderName,
type: viewingFileId ? 'file' : 'folder',
status: viewingFileData?.status,
version: stackFileData?.versionStack
? (stackFileData.versionStack.versions.find((v) => v.id === activeFileId)?.version ??
stackFileData.versionStack.versions.length)
@@ -18,6 +18,7 @@ import RatingField from '../fields/rating-field'
import { useEffect, useMemo } from 'react'
import { useMemberStore } from '@/ui/stores/members'
import { useTeamId } from '@/ui/hooks/use-team-id'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { m } from '@/ui/paraglide/messages.js'
interface FilterPanelProps {
@@ -39,6 +40,7 @@ export function FilterPanel({
}: FilterPanelProps) {
const teamId = useTeamId()
const { members, fetchMembers } = useMemberStore()
const { archiveStorageEnabled } = useArchiveConfig()
useEffect(() => {
if (teamId) {
@@ -60,6 +62,9 @@ export function FilterPanel({
{ id: 'createdAt', label: m.field_created_at(), type: 'date' },
{ id: 'updatedAt', label: m.field_updated_at(), type: 'date' },
{ id: 'sizeByte', label: m.field_size(), type: 'number' },
...(archiveStorageEnabled
? [{ id: 'isArchived', label: m.filter_archived(), type: 'toggle' }]
: []),
]
const custom = fields.map((f) => ({
id: f.id!,
@@ -72,7 +77,7 @@ export function FilterPanel({
config: f.config,
}))
return [...sys, ...custom].filter((f) => !excludeFields?.includes(f.id))
}, [fields, memberOptions, excludeFields])
}, [fields, memberOptions, excludeFields, archiveStorageEnabled])
const handleAddCondition = () => {
onChange([
@@ -100,7 +105,7 @@ export function FilterPanel({
const field = allFields.find((f) => f.id === value)
if (field) {
newConditions[index].operator = getDefaultOperator(field.type)
newConditions[index].value = ''
newConditions[index].value = field.type === 'toggle' ? true : ''
}
}
@@ -518,6 +523,7 @@ function ConditionValueInput({
}
if (field.type === 'toggle') {
const isArchivedField = field.id === 'isArchived'
return (
<Select
value={value === true ? 'true' : 'false'}
@@ -527,8 +533,12 @@ function ConditionValueInput({
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="true">{m.toggle_checked()}</SelectItem>
<SelectItem value="false">{m.toggle_unchecked()}</SelectItem>
<SelectItem value="true">
{isArchivedField ? m.filter_archived_only() : m.toggle_checked()}
</SelectItem>
<SelectItem value="false">
{isArchivedField ? m.filter_not_archived() : m.toggle_unchecked()}
</SelectItem>
</SelectContent>
</Select>
)
+4
View File
@@ -64,6 +64,8 @@ export function TopNav() {
onFolderClick,
onRename,
onDelete,
onArchive,
onRestoreArchive,
compareMode,
canCompareVersions,
onCompareVersions,
@@ -162,6 +164,8 @@ export function TopNav() {
onFolderClick={onFolderClick}
onRename={onRename}
onDelete={onDelete}
onArchive={onArchive}
onRestoreArchive={onRestoreArchive}
compareMode={compareMode}
canCompareVersions={canCompareVersions}
onCompareVersions={onCompareVersions}
@@ -77,8 +77,14 @@ export const DefaultViewer = React.forwardRef<MediaController, FileViewerProps>(
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
{allowDownload && (
<button
data-testid="default-viewer-download-button"
onClick={handleDownload}
disabled={!file.media?.original?.key}
disabled={
!file.media?.original?.key ||
file.status === 'archived' ||
file.status === 'archiving' ||
file.status === 'restoring'
}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
title="Download original file"
>
@@ -213,7 +213,12 @@ export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
onZoomOut={() => handleZoom(0.8)}
onFit={handleFit}
onDownload={handleDownload}
canDownload={!!file.media?.original?.key}
canDownload={
!!file.media?.original?.key &&
file.status !== 'archived' &&
file.status !== 'archiving' &&
file.status !== 'restoring'
}
onCopy={handleCopy}
copied={copied}
canCopy={!!bestUrl}
@@ -514,7 +514,14 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
zoom={zoom}
isFullScreen={isFullScreen}
allowDownload={allowDownload}
onDownload={data.media?.original?.key ? handleDownload : undefined}
onDownload={
data.media?.original?.key &&
data.status !== 'archived' &&
data.status !== 'archiving' &&
data.status !== 'restoring'
? handleDownload
: undefined
}
togglePlay={togglePlay}
onSeekDegree={seekToDegree}
onZoomChange={handleZoomChange}
@@ -0,0 +1,38 @@
// @vitest-environment happy-dom
import { cleanup, render, screen } from '@testing-library/react'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { PdfViewer } from './pdf-viewer'
import type { AssetInfo } from '@shumai/dtos'
vi.mock('pdfjs-dist', () => ({
GlobalWorkerOptions: { workerSrc: '' },
getDocument: vi.fn(),
}))
describe('PdfViewer', () => {
afterEach(() => {
cleanup()
})
it('renders archived placeholder when native PDF is archived and pdfTranscode.url is absent', () => {
const archivedPdf: AssetInfo = {
id: 'pdf-1',
name: 'document.pdf',
type: 'file',
status: 'archived',
sizeByte: 1024,
fileCount: 0,
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-01T00:00:00Z',
media: {
original: { key: 'files/pdf-1/document.pdf' },
pdfTranscode: { key: 'files/pdf-1/document.pdf' },
},
} as AssetInfo
render(<PdfViewer file={archivedPdf} />)
expect(screen.getByTestId('pdf-viewer-archived-state')).toBeTruthy()
})
})
@@ -1,6 +1,8 @@
import { client } from '@/ui/api/client'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { m } from '@/ui/paraglide/messages.js'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import { Archive } from 'lucide-react'
import * as pdfjsLib from 'pdfjs-dist'
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react'
import { FileViewerProps, MediaController } from '../types'
@@ -166,6 +168,9 @@ export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
}, [])
const fileUrl = file.media?.pdfTranscode?.url
const isOriginalUnavailable =
file.status === 'archived' || file.status === 'archiving' || file.status === 'restoring'
const isNativePdfArchived = !fileUrl && isOriginalUnavailable
// Load PDF Document
useEffect(() => {
@@ -409,6 +414,16 @@ export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
<div className="absolute inset-0 flex items-center justify-center bg-black/40 z-20">
<div className="w-8 h-8 border-4 border-white/30 border-t-white rounded-full animate-spin" />
</div>
) : isNativePdfArchived ? (
<div
data-testid="pdf-viewer-archived-state"
className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center text-muted-foreground"
>
<Archive className="h-12 w-12 text-muted-foreground/70" />
<p className="text-sm font-medium text-foreground">
{m.pdf_archived_placeholder()}
</p>
</div>
) : error ? (
<div className="absolute inset-0 flex items-center justify-center text-gray-500 text-sm">
{error}
@@ -465,7 +480,7 @@ export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
onZoomOut={() => handleZoom(0.8)}
onFit={handleFit}
onDownload={handleDownload}
canDownload={!!file.media?.original?.key}
canDownload={!!file.media?.original?.key && !isOriginalUnavailable}
allowDownload={allowDownload}
/>
</div>
@@ -425,9 +425,20 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
(isAudio ? (
<button
onClick={() => handleDownload(data.media?.original?.key || '')}
className="transition-colors hover:text-primary"
title={m.download()}
disabled={!data.media?.original?.key}
className="transition-colors hover:text-primary disabled:opacity-50"
title={
data.status === 'archived' ||
data.status === 'archiving' ||
data.status === 'restoring'
? m.original_archived_tooltip()
: m.download()
}
disabled={
!data.media?.original?.key ||
data.status === 'archived' ||
data.status === 'archiving' ||
data.status === 'restoring'
}
>
<Download className="h-5 w-5" />
</button>
@@ -468,7 +479,24 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleDownload(data.media?.original?.key ?? '')}
disabled={
data.status === 'archived' ||
data.status === 'archiving' ||
data.status === 'restoring'
}
title={
data.status === 'archived' ||
data.status === 'archiving' ||
data.status === 'restoring'
? m.original_archived_tooltip()
: undefined
}
onClick={() =>
data.status !== 'archived' &&
data.status !== 'archiving' &&
data.status !== 'restoring' &&
handleDownload(data.media?.original?.key ?? '')
}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
>
<span>{m.original()}</span>
@@ -0,0 +1,30 @@
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
export interface ArchiveConfig {
archiveStorageEnabled: boolean
isLoading: boolean
}
export function useArchiveConfig(): ArchiveConfig {
const { data, isLoading } = useQuery({
queryKey: ['signup-info'],
queryFn: async () => {
const res = await client.api['signup-info'].$get()
if (!res.ok) {
return { initialized: true, demoMode: false, archiveStorageEnabled: false }
}
return (await res.json()) as {
initialized?: boolean
demoMode?: boolean
archiveStorageEnabled?: boolean
}
},
staleTime: 5 * 60 * 1000,
})
return {
archiveStorageEnabled: Boolean(data?.archiveStorageEnabled),
isLoading,
}
}
+15 -3
View File
@@ -23,7 +23,11 @@ export function useBatchFileStatus({ teamId, items }: UseBatchFileStatusOptions)
return items
.filter((item) => {
if (!item.id || (item.type !== 'file' && item.type !== 'version_stack')) return false
const isUploadedOrProcessing = item.status === 'uploaded' || item.status === 'processing'
const isUploadedOrProcessing =
item.status === 'uploaded' ||
item.status === 'processing' ||
item.status === 'archiving' ||
item.status === 'restoring'
const progress = fileProgress[item.id]
const isUploadCompleted =
item.status === 'uploading' &&
@@ -71,12 +75,20 @@ export function useBatchFileStatus({ teamId, items }: UseBatchFileStatusOptions)
}
const anyFinished = assets.some(
(a) => a.status === 'processed' || a.status === 'failed' || a.status === 'error',
(a) =>
a.status === 'processed' ||
a.status === 'archived' ||
a.status === 'failed' ||
a.status === 'error',
)
const allFinished =
assets.length > 0 &&
assets.every(
(a) => a.status === 'processed' || a.status === 'failed' || a.status === 'error',
(a) =>
a.status === 'processed' ||
a.status === 'archived' ||
a.status === 'failed' ||
a.status === 'error',
)
const now = Date.now()
+28 -1
View File
@@ -1615,5 +1615,32 @@
"cancel_upload_task_confirm_title": "Cancel upload task?",
"cancel_upload_task_confirm_description": "Files that have already finished uploading will be kept in your project. Any incomplete or pending uploads will be canceled and removed.",
"upload_task_canceled": "Upload task canceled",
"failed_to_cancel_upload_task": "Failed to cancel upload task"
"failed_to_cancel_upload_task": "Failed to cancel upload task",
"archive": "Archive",
"restore_from_archive": "Restore from archive",
"archived": "Archived",
"archiving": "Archiving...",
"restoring": "Restoring...",
"archived_status": "Archived",
"archiving_status": "Archiving...",
"restoring_status": "Restoring...",
"archive_confirm_title": "Archive Original File(s)",
"archive_confirm_description": "This will move the original raw file(s) to archive storage. Previews, proxy streams, comments, and metadata will remain available, but original file downloads will be disabled until restored.",
"restore_archive_confirm_title": "Restore from Archive",
"restore_archive_confirm_description": "This will restore the original raw file(s) back to main storage. If stored in cold archive tiers (such as Glacier), restoration may take minutes to hours.",
"archive_started_toast": "Archiving started in the background",
"restore_archive_started_toast": "Restore from archive started in the background",
"archive_no_eligible_assets_toast": "No eligible processed files found to archive",
"restore_archive_no_eligible_assets_toast": "No archived files found to restore",
"archive_failed_toast": "Failed to start archive",
"restore_archive_failed_toast": "Failed to start restore from archive",
"original_archived_tooltip": "Original file is archived — restore to download original",
"pdf_archived_placeholder": "Original PDF is archived — restore to view PDF",
"download_skipped_archived_notice": "{count} archived file(s) were skipped because their original files are in archive storage.",
"download_all_archived_error": "All selected files are archived. Restore them first to download original files.",
"filter_archived": "Archive Status",
"filter_archived_only": "Archived",
"filter_not_archived": "Not Archived",
"task_type_archive_asset": "Archive Asset",
"task_type_restore_asset": "Restore Asset"
}
+28 -1
View File
@@ -1615,5 +1615,32 @@
"cancel_upload_task_confirm_title": "取消上传任务?",
"cancel_upload_task_confirm_description": "已完成上传的文件将保留在项目中。任何未完成或等待中的上传将被取消并移除。",
"upload_task_canceled": "上传任务已取消",
"failed_to_cancel_upload_task": "取消上传任务失败"
"failed_to_cancel_upload_task": "取消上传任务失败",
"archive": "归档",
"restore_from_archive": "从归档恢复",
"archived": "已归档",
"archiving": "归档中...",
"restoring": "恢复中...",
"archived_status": "已归档",
"archiving_status": "归档中...",
"restoring_status": "恢复中...",
"archive_confirm_title": "归档原始文件",
"archive_confirm_description": "此操作会将原始文件移动到归档存储。预览、代理视频流、评论和元数据仍可正常使用,但在从归档恢复之前将无法下载原始文件。",
"restore_archive_confirm_title": "从归档恢复",
"restore_archive_confirm_description": "此操作会将原始文件从归档存储恢复回主存储。如果保存在冷归档存储层(如 Glacier),恢复可能需要几分钟到数小时。",
"archive_started_toast": "已在后台开始归档",
"restore_archive_started_toast": "已在后台开始从归档恢复",
"archive_no_eligible_assets_toast": "未找到可归档的已处理文件",
"restore_archive_no_eligible_assets_toast": "未找到可恢复的已归档文件",
"archive_failed_toast": "启动归档失败",
"restore_archive_failed_toast": "启动从归档恢复失败",
"original_archived_tooltip": "原始文件已归档 — 请先恢复以下载原文件",
"pdf_archived_placeholder": "原始 PDF 文件已归档 — 请先恢复以查看 PDF",
"download_skipped_archived_notice": "已跳过 {count} 个已归档文件,因为其原始文件位于归档存储中。",
"download_all_archived_error": "所选文件均已归档。请先恢复后再下载原始文件。",
"filter_archived": "归档状态",
"filter_archived_only": "已归档",
"filter_not_archived": "未归档",
"task_type_archive_asset": "归档资产",
"task_type_restore_asset": "恢复归档资产"
}
@@ -6,6 +6,8 @@ import { FileViewer } from '@/ui/components/file-viewer'
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
import { MobileFileDetail } from '@/ui/components/file-viewer/mobile-file-detail'
import { ArchiveConfirmDialog } from '@/ui/components/archive-confirm-dialog'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { useIsMobile } from '@/ui/hooks/use-mobile'
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
import { ResizeHandle } from '@/ui/components/resize-handle'
@@ -68,6 +70,7 @@ function FileViewPage() {
const isCompareMode = !!search.compare && !!compareLeftId && !!compareRightId
const mediaControllerRef = useRef<MediaController | null>(null)
const { archiveStorageEnabled } = useArchiveConfig()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const [annotations, setAnnotations] = useState<Annotation[]>([])
@@ -142,6 +145,10 @@ function FileViewPage() {
},
enabled: !!teamId,
placeholderData: keepPreviousData,
refetchInterval: (query) => {
const status = query.state.data?.status
return status === 'archiving' || status === 'restoring' ? 2000 : false
},
})
const {
@@ -160,6 +167,10 @@ function FileViewPage() {
},
enabled: !!teamId && !!versionAssetId,
placeholderData: keepPreviousData,
refetchInterval: (query) => {
const status = query.state.data?.status
return status === 'archiving' || status === 'restoring' ? 2000 : false
},
})
const { data: versionsList } = useQuery({
@@ -201,6 +212,60 @@ function FileViewPage() {
const renameInputRef = useRef<HTMLInputElement>(null)
const renameSettledRef = useRef(false)
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [archiveConfirmState, setArchiveConfirmState] = useState<{
open: boolean
mode: 'archive' | 'restore'
}>({ open: false, mode: 'archive' })
const { mutate: archiveFile, isPending: isArchivingFile } = useMutation({
mutationFn: async (targetId: string) => {
const res = await client.api.files.archive.$post({
json: { ids: [targetId] },
})
if (!res.ok) throw new Error(m.archive_failed_toast())
return await res.json()
},
onSuccess: (data) => {
if (data.archivedAssetIds.length > 0) {
toast.success(m.archive_started_toast({ count: data.archivedAssetIds.length }))
} else {
toast.info(m.archive_no_eligible_assets_toast())
}
queryClient.invalidateQueries({ queryKey: ['files'] })
queryClient.removeQueries({ queryKey: ['file', teamId] })
queryClient.invalidateQueries({ queryKey: ['version_stacks'] })
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
setArchiveConfirmState((prev) => ({ ...prev, open: false }))
},
onError: () => {
toast.error(m.archive_failed_toast())
},
})
const { mutate: restoreArchiveFile, isPending: isRestoringArchiveFile } = useMutation({
mutationFn: async (targetId: string) => {
const res = await client.api.files['restore-archive'].$post({
json: { ids: [targetId] },
})
if (!res.ok) throw new Error(m.restore_archive_failed_toast())
return await res.json()
},
onSuccess: (data) => {
if (data.restoredAssetIds.length > 0) {
toast.success(m.restore_archive_started_toast({ count: data.restoredAssetIds.length }))
} else {
toast.info(m.restore_archive_no_eligible_assets_toast())
}
queryClient.invalidateQueries({ queryKey: ['files'] })
queryClient.removeQueries({ queryKey: ['file', teamId] })
queryClient.invalidateQueries({ queryKey: ['version_stacks'] })
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
setArchiveConfirmState((prev) => ({ ...prev, open: false }))
},
onError: () => {
toast.error(m.restore_archive_failed_toast())
},
})
const $renameFile = client.api.files[':fileId'].$put
const {
@@ -287,6 +352,7 @@ function FileViewPage() {
id: activeFileId || fileId,
name: fileData.name,
type: 'file',
status: fileData.status,
version: versionsDataList
? (versionsDataList.find((v: { id: string }) => v.id === activeFileId)?.version ??
versionsDataList.length)
@@ -338,6 +404,12 @@ function FileViewPage() {
onDelete: () => {
setIsDeleteDialogOpen(true)
},
onArchive: () => {
setArchiveConfirmState({ open: true, mode: 'archive' })
},
onRestoreArchive: () => {
setArchiveConfirmState({ open: true, mode: 'restore' })
},
})
}
@@ -617,60 +689,86 @@ function FileViewPage() {
if (isMobile && !isCompareMode) {
return (
<MobileFileDetail
projectId={projectId}
teamId={teamId}
fileId={fileId}
file={fileData as unknown as AssetInfo}
projectInfo={projectInfo}
ancestorFolders={fileData.ancestorFolders ?? []}
parentFolderId={parentFolderId}
versions={versionsDataList}
activeFileId={activeFileId}
startTime={startTime}
siblingFiles={carouselState.files}
onNavigateToFile={(targetId) => {
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId: targetId },
})
}}
onNavigateBack={() => {
if (parentFolderId && parentFolderId !== projectInfo?.rootFolder) {
<>
<MobileFileDetail
projectId={projectId}
teamId={teamId}
fileId={fileId}
file={fileData as unknown as AssetInfo}
projectInfo={projectInfo}
ancestorFolders={fileData.ancestorFolders ?? []}
parentFolderId={parentFolderId}
versions={versionsDataList}
activeFileId={activeFileId}
startTime={startTime}
siblingFiles={carouselState.files}
onNavigateToFile={(targetId) => {
navigate({
to: '/projects/$projectId/folders/$folderId',
params: { projectId, folderId: parentFolderId },
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId: targetId },
})
} else {
}}
onNavigateBack={() => {
if (parentFolderId && parentFolderId !== projectInfo?.rootFolder) {
navigate({
to: '/projects/$projectId/folders/$folderId',
params: { projectId, folderId: parentFolderId },
})
} else {
navigate({
to: '/projects/$projectId',
params: { projectId },
})
}
}}
onSelectVersion={(versionId) => {
navigate({
to: '/projects/$projectId',
params: { projectId },
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId },
search: (prev: Record<string, unknown>) => ({
...prev,
version: versionId,
}),
})
}}
onRenameFile={async (newName) => {
await renameFileAsync({
param: { fileId: activeFileId },
json: { name: newName },
})
}}
onDeleteFile={async () => {
await deleteFilesAsync({
json: { ids: [activeFileId] },
})
}}
onArchiveFile={
archiveStorageEnabled
? () => setArchiveConfirmState({ open: true, mode: 'archive' })
: undefined
}
}}
onSelectVersion={(versionId) => {
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId },
search: (prev: Record<string, unknown>) => ({
...prev,
version: versionId,
}),
})
}}
onRenameFile={async (newName) => {
await renameFileAsync({
param: { fileId: activeFileId },
json: { name: newName },
})
}}
onDeleteFile={async () => {
await deleteFilesAsync({
json: { ids: [activeFileId] },
})
}}
onSaveField={handleSaveField}
/>
onRestoreArchiveFile={
archiveStorageEnabled
? () => setArchiveConfirmState({ open: true, mode: 'restore' })
: undefined
}
onSaveField={handleSaveField}
/>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
mode={archiveConfirmState.mode}
onConfirm={() => {
if (!activeFileId) return
if (archiveConfirmState.mode === 'archive') {
archiveFile(activeFileId)
} else {
restoreArchiveFile(activeFileId)
}
}}
isPending={isArchivingFile || isRestoringArchiveFile}
/>
</>
)
}
@@ -823,6 +921,21 @@ function FileViewPage() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
mode={archiveConfirmState.mode}
onConfirm={() => {
if (!activeFileId) return
if (archiveConfirmState.mode === 'archive') {
archiveFile(activeFileId)
} else {
restoreArchiveFile(activeFileId)
}
}}
isPending={isArchivingFile || isRestoringArchiveFile}
/>
</div>
)
}
+4
View File
@@ -12,6 +12,7 @@ export interface TopNavProjectState {
name?: string
type: 'file' | 'folder'
version?: number
status?: string
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
}
isRootFolder: boolean
@@ -31,6 +32,7 @@ export interface TopNavProjectState {
id: string
version: number
name?: string | null
status?: string | null
previewUrl?: string | null
creator?: { id: string; name: string | null } | null
agent?: { id: string; name: string } | null
@@ -42,6 +44,8 @@ export interface TopNavProjectState {
onFolderClick?: (folderId: string) => void
onRename?: () => void
onDelete?: () => void
onArchive?: () => void
onRestoreArchive?: () => void
isRightSidebarCollapsed?: boolean
onRightSidebarToggle?: () => void
// Compare Versions
@@ -88,8 +88,13 @@ export const updateAssetStatusActivity = defineStep(
where: { id: params.assetId },
select: { media: true, status: true },
})
// Never overwrite an asset that has already completed media processing
if (asset?.status === AssetStatus.processed) {
// Never overwrite an asset that has already completed media processing or is archived
if (
asset?.status === AssetStatus.processed ||
asset?.status === AssetStatus.archived ||
asset?.status === AssetStatus.archiving ||
asset?.status === AssetStatus.restoring
) {
return
}
const data: Prisma.AssetUpdateInput = { status: params.status }
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { DbosExecutor, getDbosDatabaseUrl, getQueueForTaskType } from './dbos-executor'
import { TaskQueueAgent, TaskQueueTranscode } from './workflow-utils'
import { TaskQueueAgent, TaskQueueArchive, TaskQueueTranscode } from './workflow-utils'
import { WorkflowTaskStatus, WorkflowTaskType, WorkflowTask, prisma } from '@shumai/db'
import { DBOS } from '@dbos-inc/dbos-sdk'
@@ -44,6 +44,8 @@ describe('DbosExecutor Tests', () => {
expect(getQueueForTaskType(WorkflowTaskType.transcode_image)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.ai_embedding)).toBe(TaskQueueAgent)
expect(getQueueForTaskType(WorkflowTaskType.chat)).toBe(TaskQueueAgent)
expect(getQueueForTaskType(WorkflowTaskType.archive_asset)).toBe(TaskQueueArchive)
expect(getQueueForTaskType(WorkflowTaskType.restore_asset)).toBe(TaskQueueArchive)
expect(getQueueForTaskType('unknown_type')).toBe(TaskQueueAgent)
})
+16 -1
View File
@@ -8,6 +8,7 @@ import {
registerLocalTaskAbortController,
runInLocalTaskContext,
TaskQueueAgent,
TaskQueueArchive,
TaskQueueTranscode,
triggerLocalCancel,
unregisterLocalTaskAbortController,
@@ -69,6 +70,9 @@ export function getQueueForTaskType(type: string | null | undefined): string {
case WorkflowTaskType.transcode_watermark:
case WorkflowTaskType.transcode_3d:
return TaskQueueTranscode
case WorkflowTaskType.archive_asset:
case WorkflowTaskType.restore_asset:
return TaskQueueArchive
default:
if (type && type.startsWith('transcode')) {
return TaskQueueTranscode
@@ -84,7 +88,7 @@ export class DbosExecutor extends EventEmitter {
private launchPromise: Promise<void> | null = null
private started = false
private client: DBOSClient | null = null
private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode]
private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode, TaskQueueArchive]
private heartbeatIntervals = new Map<string, Timer>()
private inFlightSubmits = new Set<Promise<string>>()
private executorId?: string
@@ -116,6 +120,10 @@ export class DbosExecutor extends EventEmitter {
return getConcurrencyLimit(process.env.CONCURRENCY_AGENT, 5)
}
getArchiveConcurrencyLimit(): number {
return getConcurrencyLimit(process.env.CONCURRENCY_ARCHIVE, 5)
}
private registerAllWorkflowsWithDbos(): void {
const workflows = getRegisteredWorkflows()
for (const type of workflows.keys()) {
@@ -219,6 +227,7 @@ export class DbosExecutor extends EventEmitter {
if (this.listenQueues.length === 1) {
if (this.listenQueues[0] === TaskQueueTranscode) return 'shumai-transcode'
if (this.listenQueues[0] === TaskQueueAgent) return 'shumai-agent'
if (this.listenQueues[0] === TaskQueueArchive) return 'shumai-archive'
}
return 'shumai-all'
}
@@ -302,6 +311,12 @@ export class DbosExecutor extends EventEmitter {
minPollingIntervalMs,
onConflict: 'always_update',
})
} else if (queueName === TaskQueueArchive) {
await DBOS.registerQueue(TaskQueueArchive, {
workerConcurrency: this.getArchiveConcurrencyLimit(),
minPollingIntervalMs,
onConflict: 'always_update',
})
}
}
})()
@@ -7,6 +7,7 @@ export { DBOS, DBOSError }
*/
export const TaskQueueAgent = 'agent_queue'
export const TaskQueueTranscode = 'transcode_queue'
export const TaskQueueArchive = 'archive_queue'
export class WorkflowFailure extends Error {
readonly nonRetryable: boolean
+29
View File
@@ -193,6 +193,35 @@ export class WorkflowService {
where: { id: task.assetId, status: AssetStatus.processing },
data: { status: AssetStatus.failed },
})
} else if (task.type === 'archive_asset' || task.type === 'restore_asset') {
const payload = currentTask.payload as PrismaJson.WorkflowTaskPayload | null
let storageKeyId = payload?.archive?.storageKeyId
if (!storageKeyId && task.assetId) {
const asset = await prisma.asset.findUnique({
where: { id: task.assetId },
select: { storageKeyId: true },
})
storageKeyId = asset?.storageKeyId ?? undefined
}
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,
},
})
}
}
}
recoveredCount++
continue