mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 19:04:23 +00:00
feat(storage): add team auto-archive assets policy and background job (#516)
* feat(storage): add team auto-archive assets policy and background job * fix(storage): address code review feedback on lock safety, starvation, and permissions * docs: update readme and expand archive storage documentation with auto-archive details * feat(storage): log info message on auto-archive job start and finish with archived count * style(storage): stack age threshold and grace period vertically with updated grace period description * fix(storage): only log auto-archive info messages when candidate assets are found to process
This commit is contained in:
@@ -82,7 +82,17 @@ export class AssetArchiveService {
|
||||
})
|
||||
}
|
||||
|
||||
async archiveAssets(assetIds: string[]): Promise<ArchiveAssetsResponse> {
|
||||
async archiveAssets(
|
||||
assetIds: string[],
|
||||
options?: {
|
||||
suppressBusyErrors?: boolean
|
||||
autoArchivePolicy?: {
|
||||
method: 'not_updated' | 'after_created'
|
||||
cutoffDate: Date
|
||||
restoreCutoffDate: Date
|
||||
}
|
||||
},
|
||||
): Promise<ArchiveAssetsResponse> {
|
||||
if (!isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, { message: 'Archive storage is not configured' })
|
||||
}
|
||||
@@ -187,15 +197,17 @@ export class AssetArchiveService {
|
||||
}
|
||||
|
||||
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',
|
||||
})
|
||||
if (!options?.suppressBusyErrors) {
|
||||
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 }
|
||||
}
|
||||
@@ -206,28 +218,65 @@ export class AssetArchiveService {
|
||||
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: AssetStatus.processed,
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
const sharedAssetIds = sharedAssets.map((a) => a.id)
|
||||
// 1. Lock the storageKey row to serialize concurrent archive requests
|
||||
const lockedKeys = await tx.$queryRaw<Array<{ id: string; isArchived: boolean }>>`
|
||||
SELECT id, is_archived AS "isArchived"
|
||||
FROM storage_keys
|
||||
WHERE id = ${storageKeyId}
|
||||
FOR UPDATE
|
||||
`
|
||||
if (!lockedKeys || lockedKeys.length === 0 || lockedKeys[0].isArchived) {
|
||||
return
|
||||
}
|
||||
|
||||
if (sharedAssetIds.length > 0) {
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: sharedAssetIds } },
|
||||
data: { status: AssetStatus.archiving },
|
||||
// If an auto-archive policy was specified, re-verify under lock that all sibling assets meet the age policy
|
||||
if (options?.autoArchivePolicy) {
|
||||
const policy = options.autoArchivePolicy
|
||||
const ineligible = await tx.asset.findFirst({
|
||||
where: {
|
||||
storageKeyId,
|
||||
isDeleted: false,
|
||||
OR: [
|
||||
{ type: { not: AssetType.file } },
|
||||
{ status: { not: AssetStatus.processed } },
|
||||
...(policy.method === 'not_updated'
|
||||
? [{ updatedAt: { gt: policy.cutoffDate } }]
|
||||
: [
|
||||
{
|
||||
OR: [
|
||||
{ createdAt: { gt: policy.cutoffDate } },
|
||||
{ updatedAt: { gt: policy.restoreCutoffDate } },
|
||||
],
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
for (const id of sharedAssetIds) {
|
||||
archivedAssetIdsSet.add(id)
|
||||
if (ineligible) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Atomic Filter + Update: only files that are currently 'processed' transition to 'archiving'
|
||||
const updatedAssets = await tx.$queryRaw<Array<{ id: string }>>`
|
||||
UPDATE assets
|
||||
SET status = 'archiving'::"AssetStatus", updated_at = NOW()
|
||||
WHERE storage_key_id = ${storageKeyId}
|
||||
AND type = 'file'::"AssetType"
|
||||
AND status = 'processed'::"AssetStatus"
|
||||
AND is_deleted = false
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
if (!updatedAssets || updatedAssets.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
for (const row of updatedAssets) {
|
||||
archivedAssetIdsSet.add(row.id)
|
||||
}
|
||||
|
||||
const existingTask = await tx.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: { in: filesForKey.map((f) => f.id) },
|
||||
|
||||
@@ -2991,8 +2991,18 @@ export class AssetService {
|
||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true, downloadFilename)
|
||||
}
|
||||
|
||||
async archiveAssets(assetIds: string[]): Promise<ArchiveAssetsResponse> {
|
||||
return assetArchiveService.archiveAssets(assetIds)
|
||||
async archiveAssets(
|
||||
assetIds: string[],
|
||||
options?: {
|
||||
suppressBusyErrors?: boolean
|
||||
autoArchivePolicy?: {
|
||||
method: 'not_updated' | 'after_created'
|
||||
cutoffDate: Date
|
||||
restoreCutoffDate: Date
|
||||
}
|
||||
},
|
||||
): Promise<ArchiveAssetsResponse> {
|
||||
return assetArchiveService.archiveAssets(assetIds, options)
|
||||
}
|
||||
|
||||
async restoreArchivedAssets(assetIds: string[]): Promise<RestoreArchivedAssetsResponse> {
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import {
|
||||
AssetStatus,
|
||||
prisma,
|
||||
Prisma,
|
||||
WorkflowTaskType,
|
||||
WorkflowTaskStatus,
|
||||
type User,
|
||||
} from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { assetService } from './asset'
|
||||
import { assetArchiveService } from './asset-archive'
|
||||
import { resetArchiveStorageServiceForTests } from '../s3/archive-storage'
|
||||
import {
|
||||
AutoArchiveJobService,
|
||||
autoArchiveJobService,
|
||||
getAutoArchiveIntervalMs,
|
||||
} from './auto-archive-job'
|
||||
|
||||
describe('AutoArchiveJobService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
const archiveRoot = path.join(process.cwd(), 'data-test-auto-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: 'Auto Archive Owner', email: 'auto-archive-owner@test.com', password: 'pw' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Auto Archive Team',
|
||||
settings: {
|
||||
autoArchive: {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
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 })
|
||||
}
|
||||
autoArchiveJobService.stop()
|
||||
})
|
||||
|
||||
async function createTestFile(params: {
|
||||
name: string
|
||||
key: string
|
||||
createdAt?: Date
|
||||
updatedAt?: Date
|
||||
status?: AssetStatus
|
||||
}) {
|
||||
const asset = await assetService.createAsset({
|
||||
name: params.name,
|
||||
type: 'file',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
key: params.key,
|
||||
sizeByte: 2048,
|
||||
contentType: 'video/mp4',
|
||||
creatorId: owner.id,
|
||||
})
|
||||
|
||||
const updated = await prisma.asset.update({
|
||||
where: { id: asset.id },
|
||||
data: {
|
||||
status: params.status ?? AssetStatus.processed,
|
||||
createdAt: params.createdAt ?? new Date(),
|
||||
updatedAt: params.updatedAt ?? new Date(),
|
||||
},
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
return updated
|
||||
}
|
||||
|
||||
describe('getAutoArchiveIntervalMs', () => {
|
||||
it('returns default 1 hour (3600000ms) when env not specified', () => {
|
||||
delete process.env.AUTO_ARCHIVE_INTERVAL_MINUTES
|
||||
expect(getAutoArchiveIntervalMs()).toBe(3600000)
|
||||
})
|
||||
|
||||
it('parses integer minute strings', () => {
|
||||
process.env.AUTO_ARCHIVE_INTERVAL_MINUTES = '30'
|
||||
expect(getAutoArchiveIntervalMs()).toBe(1800000)
|
||||
})
|
||||
|
||||
it('parses decimal floating point minute strings', () => {
|
||||
process.env.AUTO_ARCHIVE_INTERVAL_MINUTES = '0.02'
|
||||
expect(getAutoArchiveIntervalMs()).toBe(1200)
|
||||
})
|
||||
})
|
||||
|
||||
it('skips scan when archive storage is not configured', async () => {
|
||||
delete process.env.ARCHIVE_STORAGE_BACKEND
|
||||
resetArchiveStorageServiceForTests()
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
expect(res.archivedCount).toBe(0)
|
||||
})
|
||||
|
||||
it('skips teams where autoArchive is disabled', async () => {
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
settings: {
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const oldDate = new Date(Date.now() - 40 * 86_400_000)
|
||||
await createTestFile({
|
||||
name: 'old-file.mp4',
|
||||
key: 'files/test/old-file.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
expect(res.archivedCount).toBe(0)
|
||||
})
|
||||
|
||||
it('archives assets exceeding not_updated threshold while leaving recent assets untouched', async () => {
|
||||
const oldDate = new Date(Date.now() - 35 * 86_400_000)
|
||||
const recentDate = new Date(Date.now() - 5 * 86_400_000)
|
||||
|
||||
const oldFile = await createTestFile({
|
||||
name: 'old-file.mp4',
|
||||
key: 'files/test/old-file.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const recentFile = await createTestFile({
|
||||
name: 'recent-file.mp4',
|
||||
key: 'files/test/recent-file.mp4',
|
||||
updatedAt: recentDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(1)
|
||||
|
||||
const refreshedOld = await prisma.asset.findUniqueOrThrow({ where: { id: oldFile.id } })
|
||||
const refreshedRecent = await prisma.asset.findUniqueOrThrow({ where: { id: recentFile.id } })
|
||||
|
||||
expect(refreshedOld.status).toBe(AssetStatus.archiving)
|
||||
expect(refreshedRecent.status).toBe(AssetStatus.processed)
|
||||
|
||||
const task = await prisma.workflowTask.findFirst({
|
||||
where: { assetId: oldFile.id, type: WorkflowTaskType.archive_asset },
|
||||
})
|
||||
expect(task).not.toBeNull()
|
||||
expect(task?.status).toBe(WorkflowTaskStatus.pending)
|
||||
})
|
||||
|
||||
it('archives assets exceeding after_created threshold and respects postRestoreGraceDays', async () => {
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
settings: {
|
||||
autoArchive: {
|
||||
enabled: true,
|
||||
method: 'after_created',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 14,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const oldCreatedDate = new Date(Date.now() - 45 * 86_400_000)
|
||||
const recentlyRestoredDate = new Date(Date.now() - 2 * 86_400_000)
|
||||
const oldRestoredDate = new Date(Date.now() - 20 * 86_400_000)
|
||||
|
||||
// Old creation, but restored 2 days ago (within 14-day grace period) -> should NOT archive
|
||||
const restoredRecently = await createTestFile({
|
||||
name: 'restored-recently.mp4',
|
||||
key: 'files/test/restored-recently.mp4',
|
||||
createdAt: oldCreatedDate,
|
||||
updatedAt: recentlyRestoredDate,
|
||||
})
|
||||
|
||||
// Old creation, restored 20 days ago (> 14-day grace period) -> SHOULD archive
|
||||
const restoredLongAgo = await createTestFile({
|
||||
name: 'restored-long-ago.mp4',
|
||||
key: 'files/test/restored-long-ago.mp4',
|
||||
createdAt: oldCreatedDate,
|
||||
updatedAt: oldRestoredDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(1)
|
||||
|
||||
const refreshedRecently = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: restoredRecently.id },
|
||||
})
|
||||
const refreshedLongAgo = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: restoredLongAgo.id },
|
||||
})
|
||||
|
||||
expect(refreshedRecently.status).toBe(AssetStatus.processed)
|
||||
expect(refreshedLongAgo.status).toBe(AssetStatus.archiving)
|
||||
})
|
||||
|
||||
it('skips storage key if any sibling file sharing the key was recently modified', async () => {
|
||||
const oldDate = new Date(Date.now() - 40 * 86_400_000)
|
||||
const recentDate = new Date()
|
||||
|
||||
const sharedKey = 'files/test/shared-video.mp4'
|
||||
|
||||
const primaryFile = await createTestFile({
|
||||
name: 'primary.mp4',
|
||||
key: sharedKey,
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
// Create a sibling copy sharing the same storageKeyId but modified recently
|
||||
const siblingCopy = await assetService.createAsset({
|
||||
name: 'sibling-copy.mp4',
|
||||
type: 'file',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
key: sharedKey,
|
||||
sizeByte: 2048,
|
||||
contentType: 'video/mp4',
|
||||
creatorId: owner.id,
|
||||
})
|
||||
|
||||
await prisma.asset.update({
|
||||
where: { id: siblingCopy.id },
|
||||
data: {
|
||||
status: AssetStatus.processed,
|
||||
updatedAt: recentDate,
|
||||
},
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(0)
|
||||
|
||||
const refreshedPrimary = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: primaryFile.id },
|
||||
})
|
||||
expect(refreshedPrimary.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
|
||||
it('handles race conditions: concurrent archive attempts cleanly serialize without duplicate tasks', async () => {
|
||||
const oldDate = new Date(Date.now() - 50 * 86_400_000)
|
||||
const file = await createTestFile({
|
||||
name: 'concurrent-test.mp4',
|
||||
key: 'files/test/concurrent-test.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
|
||||
// Trigger auto-archive and manual archive concurrently
|
||||
const [jobRes, manualRes] = await Promise.all([
|
||||
job.processAutoArchive(),
|
||||
assetService.archiveAssets([file.id], { suppressBusyErrors: true }),
|
||||
])
|
||||
|
||||
// Together they should archive the asset exactly once
|
||||
const totalArchived = jobRes.archivedCount + manualRes.archivedAssetIds.length
|
||||
expect(totalArchived).toBe(1)
|
||||
|
||||
// Verify exactly ONE WorkflowTask was created
|
||||
const tasks = await prisma.workflowTask.findMany({
|
||||
where: { assetId: file.id, type: WorkflowTaskType.archive_asset },
|
||||
})
|
||||
expect(tasks).toHaveLength(1)
|
||||
|
||||
const refreshedFile = await prisma.asset.findUniqueOrThrow({ where: { id: file.id } })
|
||||
expect(refreshedFile.status).toBe(AssetStatus.archiving)
|
||||
})
|
||||
|
||||
it('prevents candidate starvation: storage keys with stuck siblings are ignored so eligible candidates are not blocked', async () => {
|
||||
const oldDate = new Date(Date.now() - 40 * 86_400_000)
|
||||
|
||||
// Key 1: has an old file AND a stuck sibling with status 'failed'
|
||||
const stuckKey = 'files/test/stuck-sibling.mp4'
|
||||
const fileWithStuckSibling = await createTestFile({
|
||||
name: 'stuck-primary.mp4',
|
||||
key: stuckKey,
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
const stuckSibling = await assetService.createAsset({
|
||||
name: 'stuck-sibling-failed.mp4',
|
||||
type: 'file',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
key: stuckKey,
|
||||
sizeByte: 2048,
|
||||
contentType: 'video/mp4',
|
||||
creatorId: owner.id,
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: stuckSibling.id },
|
||||
data: {
|
||||
status: AssetStatus.failed,
|
||||
updatedAt: oldDate,
|
||||
},
|
||||
})
|
||||
|
||||
// Key 2: fully eligible old file
|
||||
const eligibleFile = await createTestFile({
|
||||
name: 'eligible-siblingless.mp4',
|
||||
key: 'files/test/eligible-siblingless.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
// With batchSize 1, the query must pick the eligible file instead of getting stuck on Key 1
|
||||
const res = await job.processAutoArchive(1)
|
||||
|
||||
expect(res.archivedCount).toBe(1)
|
||||
|
||||
const refreshedEligible = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: eligibleFile.id },
|
||||
})
|
||||
expect(refreshedEligible.status).toBe(AssetStatus.archiving)
|
||||
|
||||
const refreshedStuck = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: fileWithStuckSibling.id },
|
||||
})
|
||||
expect(refreshedStuck.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
|
||||
it('skips scan when another process holds the transaction advisory lock', async () => {
|
||||
const queryRawSpy = vi.spyOn(prisma, '$queryRaw').mockImplementation((query: unknown) => {
|
||||
const sqlText = String((query as { strings?: string[] })?.strings || '')
|
||||
if (sqlText.includes('pg_try_advisory_xact_lock')) {
|
||||
return Promise.resolve([{ locked: false }]) as unknown as Prisma.PrismaPromise<unknown>
|
||||
}
|
||||
queryRawSpy.mockRestore()
|
||||
return prisma.$queryRaw(query as TemplateStringsArray)
|
||||
})
|
||||
|
||||
try {
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
expect(res.archivedCount).toBe(0)
|
||||
} finally {
|
||||
queryRawSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('logs info level message on job start and finish with totalArchived count', async () => {
|
||||
const infoSpy = vi.spyOn(logger, 'info')
|
||||
|
||||
const oldDate = new Date(Date.now() - 40 * 86_400_000)
|
||||
await createTestFile({
|
||||
name: 'log-test.mp4',
|
||||
key: 'files/test/log-test.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(1)
|
||||
expect(infoSpy).toHaveBeenCalledWith('Auto-archive job started')
|
||||
expect(infoSpy).toHaveBeenCalledWith({ totalArchived: 1 }, 'Auto-archive job finished')
|
||||
|
||||
infoSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('does not log info level messages when no files are eligible to archive', async () => {
|
||||
const infoSpy = vi.spyOn(logger, 'info')
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(0)
|
||||
expect(infoSpy).not.toHaveBeenCalledWith('Auto-archive job started')
|
||||
expect(infoSpy).not.toHaveBeenCalledWith(expect.anything(), 'Auto-archive job finished')
|
||||
|
||||
infoSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('does not archive non-file assets even if their status is processed and age criteria met', async () => {
|
||||
const oldDate = new Date(Date.now() - 50 * 86_400_000)
|
||||
|
||||
const folder = await assetService.createAsset({
|
||||
name: 'Old Folder',
|
||||
type: 'folder',
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
creatorId: owner.id,
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: folder.id },
|
||||
data: {
|
||||
status: AssetStatus.processed,
|
||||
updatedAt: oldDate,
|
||||
createdAt: oldDate,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await assetArchiveService.archiveAssets([folder.id], {
|
||||
suppressBusyErrors: true,
|
||||
autoArchivePolicy: {
|
||||
method: 'not_updated',
|
||||
cutoffDate: new Date(),
|
||||
restoreCutoffDate: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
expect(res.archivedAssetIds).toHaveLength(0)
|
||||
|
||||
const refreshedFolder = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: folder.id },
|
||||
})
|
||||
expect(refreshedFolder.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
|
||||
it('can start and stop without errors', () => {
|
||||
const job = new AutoArchiveJobService()
|
||||
job.start(1000, 5000)
|
||||
job.stop()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import { prisma, Prisma } from '@shumai/db'
|
||||
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
|
||||
import { assetArchiveService } from '@shumai/core/src/asset/asset-archive'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
export function getAutoArchiveIntervalMs(): number {
|
||||
const raw = process.env.AUTO_ARCHIVE_INTERVAL_MINUTES
|
||||
if (raw) {
|
||||
const parsed = Number.parseFloat(raw)
|
||||
if (!Number.isNaN(parsed) && parsed > 0) {
|
||||
return Math.round(parsed * 60 * 1000)
|
||||
}
|
||||
}
|
||||
return 60 * 60 * 1000 // default 1 hour
|
||||
}
|
||||
|
||||
interface TeamArchiveBatch {
|
||||
teamId: string
|
||||
assetIds: string[]
|
||||
policy: {
|
||||
method: 'not_updated' | 'after_created'
|
||||
cutoffDate: Date
|
||||
restoreCutoffDate: Date
|
||||
}
|
||||
}
|
||||
|
||||
export class AutoArchiveJobService {
|
||||
private isRunning = false
|
||||
private isProcessing = false
|
||||
private timer: NodeJS.Timeout | null = null
|
||||
|
||||
start(initialDelayMs = 60_000, intervalMs?: number): void {
|
||||
if (this.isRunning) return
|
||||
this.isRunning = true
|
||||
logger.info('Starting auto-archive background job')
|
||||
|
||||
const run = async () => {
|
||||
if (!this.isRunning) return
|
||||
try {
|
||||
await this.processAutoArchive()
|
||||
} catch (err: unknown) {
|
||||
logger.error({ err }, 'Error in auto-archive background job')
|
||||
}
|
||||
|
||||
if (this.isRunning) {
|
||||
const nextInterval = intervalMs ?? getAutoArchiveIntervalMs()
|
||||
this.timer = setTimeout(run, nextInterval)
|
||||
}
|
||||
}
|
||||
|
||||
this.timer = setTimeout(run, initialDelayMs)
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.isRunning = false
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer)
|
||||
this.timer = null
|
||||
}
|
||||
logger.info('Stopped auto-archive background job')
|
||||
}
|
||||
|
||||
async processAutoArchive(batchSize = 100): Promise<{ archivedCount: number }> {
|
||||
if (!isArchiveStorageEnabled()) {
|
||||
logger.debug('Archive storage is not configured; skipping auto-archive run')
|
||||
return { archivedCount: 0 }
|
||||
}
|
||||
|
||||
if (this.isProcessing) {
|
||||
logger.debug('Auto-archive job turn already in progress, skipping')
|
||||
return { archivedCount: 0 }
|
||||
}
|
||||
|
||||
this.isProcessing = true
|
||||
|
||||
try {
|
||||
let totalArchived = 0
|
||||
|
||||
// Phase 1: Query & Scan under transaction-scoped advisory lock.
|
||||
// Automatically released as soon as this transaction completes.
|
||||
const teamBatches = await prisma.$transaction(async (tx) => {
|
||||
const lockRes = await tx.$queryRaw<Array<{ locked: boolean }>>`
|
||||
SELECT pg_try_advisory_xact_lock(hashtext('auto_archive_job')) AS locked
|
||||
`
|
||||
if (!lockRes || !lockRes[0]?.locked) {
|
||||
logger.debug(
|
||||
'Could not acquire transaction advisory lock for auto-archive scan, skipping',
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
// Query only teams where autoArchive is enabled via JSON filter
|
||||
const eligibleTeams = await tx.team.findMany({
|
||||
where: {
|
||||
settings: {
|
||||
path: ['autoArchive', 'enabled'],
|
||||
equals: true,
|
||||
},
|
||||
},
|
||||
select: { id: true, settings: true },
|
||||
})
|
||||
|
||||
if (eligibleTeams.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const batches: TeamArchiveBatch[] = []
|
||||
|
||||
for (const team of eligibleTeams) {
|
||||
const settings = (team.settings || {}) as PrismaJson.Settings
|
||||
const autoArchive = settings.autoArchive
|
||||
const method = autoArchive?.method || 'not_updated'
|
||||
const days = Math.max(1, autoArchive?.days || 30)
|
||||
const postRestoreGraceDays = Math.max(1, autoArchive?.postRestoreGraceDays || 30)
|
||||
|
||||
const now = Date.now()
|
||||
const cutoffDate = new Date(now - days * 86_400_000)
|
||||
const restoreCutoffDate = new Date(now - postRestoreGraceDays * 86_400_000)
|
||||
|
||||
// Query candidate assets whose storage keys have NO ineligible sibling.
|
||||
// NOT EXISTS eliminates starvation from stuck/recent siblings at the database level.
|
||||
const candidateRows = await tx.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT a.id
|
||||
FROM assets a
|
||||
JOIN projects p ON a.project_id = p.id
|
||||
JOIN storage_keys sk ON a.storage_key_id = sk.id
|
||||
WHERE p.team_id = ${team.id}
|
||||
AND a.type = 'file'::"AssetType"
|
||||
AND a.status = 'processed'::"AssetStatus"
|
||||
AND a.is_deleted = false
|
||||
AND sk.is_archived = false
|
||||
AND ${
|
||||
method === 'not_updated'
|
||||
? Prisma.sql`a.updated_at <= ${cutoffDate}`
|
||||
: Prisma.sql`a.created_at <= ${cutoffDate} AND a.updated_at <= ${restoreCutoffDate}`
|
||||
}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM assets sib
|
||||
WHERE sib.storage_key_id = a.storage_key_id
|
||||
AND sib.is_deleted = false
|
||||
AND (
|
||||
sib.type != 'file'::"AssetType"
|
||||
OR sib.status != 'processed'::"AssetStatus"
|
||||
OR ${
|
||||
method === 'not_updated'
|
||||
? Prisma.sql`sib.updated_at > ${cutoffDate}`
|
||||
: Prisma.sql`sib.created_at > ${cutoffDate} OR sib.updated_at > ${restoreCutoffDate}`
|
||||
}
|
||||
)
|
||||
)
|
||||
ORDER BY a.id ASC
|
||||
LIMIT ${batchSize};
|
||||
`
|
||||
|
||||
if (candidateRows.length > 0) {
|
||||
batches.push({
|
||||
teamId: team.id,
|
||||
assetIds: candidateRows.map((r) => r.id),
|
||||
policy: { method, cutoffDate, restoreCutoffDate },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return batches
|
||||
})
|
||||
|
||||
if (!teamBatches || teamBatches.length === 0) {
|
||||
return { archivedCount: 0 }
|
||||
}
|
||||
|
||||
logger.info('Auto-archive job started')
|
||||
|
||||
// Phase 2: Execute archival in chunks per team batch.
|
||||
// Each asset/storageKey transition is protected by row-level lock and re-verifies policy.
|
||||
const chunkSize = 50
|
||||
|
||||
for (const batch of teamBatches) {
|
||||
for (let i = 0; i < batch.assetIds.length; i += chunkSize) {
|
||||
const chunk = batch.assetIds.slice(i, i + chunkSize)
|
||||
const result = await assetArchiveService.archiveAssets(chunk, {
|
||||
suppressBusyErrors: true,
|
||||
autoArchivePolicy: batch.policy,
|
||||
})
|
||||
totalArchived += result.archivedAssetIds.length
|
||||
}
|
||||
}
|
||||
|
||||
logger.info({ totalArchived }, 'Auto-archive job finished')
|
||||
return { archivedCount: totalArchived }
|
||||
} finally {
|
||||
this.isProcessing = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const autoArchiveJobService = new AutoArchiveJobService()
|
||||
@@ -1,6 +1,7 @@
|
||||
export * from './agent/agent'
|
||||
export * from './asset/asset'
|
||||
export * from './asset/asset-archive'
|
||||
export * from './asset/auto-archive-job'
|
||||
export * from './auth/auth'
|
||||
export * from './authz/authz'
|
||||
export * from './collection/collection'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as path from 'path'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
@@ -388,6 +389,13 @@ describe('TeamService', () => {
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
archiveStorage: { enabled: false },
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
})
|
||||
|
||||
await teamService.updateSettings(team.id, 'theme', 'dark')
|
||||
@@ -417,6 +425,13 @@ describe('TeamService', () => {
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
archiveStorage: { enabled: false },
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
})
|
||||
|
||||
await teamService.updateSettings(team.id, 'transcode.videoStrategy', 'multi')
|
||||
@@ -456,6 +471,13 @@ describe('TeamService', () => {
|
||||
},
|
||||
appearance: { hideAgent: true },
|
||||
semanticSearchEnabled: false,
|
||||
archiveStorage: { enabled: false },
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -633,4 +655,66 @@ describe('TeamService', () => {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects enabling auto-archive when archive storage is not configured', async () => {
|
||||
delete process.env.ARCHIVE_STORAGE_BACKEND
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner AA', email: 'owner-aa@example.com', password: 'pw' },
|
||||
})
|
||||
const team = await teamService.createTeam(owner, { name: 'AA Team' })
|
||||
|
||||
await expect(
|
||||
teamService.updateSettings(team.id, 'autoArchive', {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
}),
|
||||
).rejects.toThrow('Cannot enable auto archive when archive storage is not configured')
|
||||
|
||||
await expect(teamService.updateSettings(team.id, 'autoArchive.enabled', true)).rejects.toThrow(
|
||||
'Cannot enable auto archive when archive storage is not configured',
|
||||
)
|
||||
})
|
||||
|
||||
it('allows updating auto-archive settings when archive storage is configured', async () => {
|
||||
const saved = { ...process.env }
|
||||
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
|
||||
process.env.ARCHIVE_LOCAL_ROOT = '/tmp/shumai-archive-test-team'
|
||||
|
||||
try {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner AA 2', email: 'owner-aa2@example.com', password: 'pw' },
|
||||
})
|
||||
const team = await teamService.createTeam(owner, { name: 'AA Team 2' })
|
||||
|
||||
await teamService.updateSettings(team.id, 'autoArchive', {
|
||||
enabled: true,
|
||||
method: 'after_created',
|
||||
days: 45,
|
||||
postRestoreGraceDays: 15,
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(team.id)
|
||||
expect(settings.autoArchive).toEqual({
|
||||
enabled: true,
|
||||
method: 'after_created',
|
||||
days: 45,
|
||||
postRestoreGraceDays: 15,
|
||||
})
|
||||
expect(settings.archiveStorage).toEqual({
|
||||
enabled: true,
|
||||
backend: 'local',
|
||||
localRoot: path.resolve('/tmp/shumai-archive-test-team'),
|
||||
})
|
||||
|
||||
// Non-admin call should mask backend/root details
|
||||
const readerSettings = await teamService.getSettings(team.id, { isAdmin: false })
|
||||
expect(readerSettings.archiveStorage).toEqual({
|
||||
enabled: true,
|
||||
})
|
||||
} finally {
|
||||
process.env = saved
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,6 +10,10 @@ import { AgentService, agentService } from '@shumai/core/src/agent/agent'
|
||||
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import {
|
||||
getArchiveStorageConfig,
|
||||
isArchiveStorageEnabled,
|
||||
} from '@shumai/core/src/s3/archive-storage'
|
||||
import {
|
||||
ServiceCreateTeamRequest,
|
||||
ServiceGetUserTeamsRequest,
|
||||
@@ -23,6 +27,9 @@ import {
|
||||
SandboxSettings,
|
||||
UpdateSandboxSettingsRequest,
|
||||
TeamSettingsResponse,
|
||||
AutoArchiveMethod,
|
||||
AutoArchiveSettings,
|
||||
DEFAULT_AUTO_ARCHIVE_SETTINGS,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
export class TeamService {
|
||||
@@ -300,7 +307,10 @@ export class TeamService {
|
||||
})
|
||||
}
|
||||
|
||||
async getSettings(teamId: string): Promise<TeamSettingsResponse> {
|
||||
async getSettings(
|
||||
teamId: string,
|
||||
options?: { isAdmin?: boolean },
|
||||
): Promise<TeamSettingsResponse> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
@@ -355,6 +365,33 @@ export class TeamService {
|
||||
settings.turntable = await turntableService.getSettings(teamId)
|
||||
settings.gotenberg = await gotenbergService.getSettings(teamId)
|
||||
|
||||
const archiveConfig = getArchiveStorageConfig()
|
||||
if (!archiveConfig.enabled) {
|
||||
settings.archiveStorage = { enabled: false }
|
||||
} else if (options?.isAdmin === false) {
|
||||
settings.archiveStorage = { enabled: true }
|
||||
} else if (archiveConfig.backend === 'local') {
|
||||
settings.archiveStorage = {
|
||||
enabled: true,
|
||||
backend: 'local',
|
||||
localRoot: archiveConfig.localRoot,
|
||||
}
|
||||
} else {
|
||||
settings.archiveStorage = {
|
||||
enabled: true,
|
||||
backend: 's3',
|
||||
endpoint: archiveConfig.endpoint,
|
||||
bucket: archiveConfig.bucket,
|
||||
}
|
||||
}
|
||||
|
||||
settings.autoArchive = {
|
||||
enabled: settings.autoArchive?.enabled ?? false,
|
||||
method: settings.autoArchive?.method ?? 'not_updated',
|
||||
days: settings.autoArchive?.days ?? 30,
|
||||
postRestoreGraceDays: settings.autoArchive?.postRestoreGraceDays ?? 30,
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
@@ -421,6 +458,49 @@ export class TeamService {
|
||||
}
|
||||
settings.appearance.hideAgent = Boolean(value)
|
||||
delete settings['appearance.hideAgent']
|
||||
} else if (key === 'autoArchive') {
|
||||
const autoArchiveVal = value as AutoArchiveSettings
|
||||
if (autoArchiveVal.enabled && !isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Cannot enable auto archive when archive storage is not configured',
|
||||
})
|
||||
}
|
||||
settings.autoArchive = {
|
||||
enabled: Boolean(autoArchiveVal.enabled),
|
||||
method: autoArchiveVal.method || 'not_updated',
|
||||
days: Number(autoArchiveVal.days) || 30,
|
||||
postRestoreGraceDays: Number(autoArchiveVal.postRestoreGraceDays) || 30,
|
||||
}
|
||||
} else if (key === 'autoArchive.enabled') {
|
||||
const enabled = Boolean(value)
|
||||
if (enabled && !isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Cannot enable auto archive when archive storage is not configured',
|
||||
})
|
||||
}
|
||||
if (!settings.autoArchive) {
|
||||
settings.autoArchive = { ...DEFAULT_AUTO_ARCHIVE_SETTINGS }
|
||||
}
|
||||
settings.autoArchive.enabled = enabled
|
||||
delete settings['autoArchive.enabled']
|
||||
} else if (key === 'autoArchive.method') {
|
||||
if (!settings.autoArchive) {
|
||||
settings.autoArchive = { ...DEFAULT_AUTO_ARCHIVE_SETTINGS }
|
||||
}
|
||||
settings.autoArchive.method = value as AutoArchiveMethod
|
||||
delete settings['autoArchive.method']
|
||||
} else if (key === 'autoArchive.days') {
|
||||
if (!settings.autoArchive) {
|
||||
settings.autoArchive = { ...DEFAULT_AUTO_ARCHIVE_SETTINGS }
|
||||
}
|
||||
settings.autoArchive.days = Number(value)
|
||||
delete settings['autoArchive.days']
|
||||
} else if (key === 'autoArchive.postRestoreGraceDays') {
|
||||
if (!settings.autoArchive) {
|
||||
settings.autoArchive = { ...DEFAULT_AUTO_ARCHIVE_SETTINGS }
|
||||
}
|
||||
settings.autoArchive.postRestoreGraceDays = Number(value)
|
||||
delete settings['autoArchive.postRestoreGraceDays']
|
||||
} else {
|
||||
settings[key] = value
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user