gongxiangp2/lib/xiaoyi-delivery-gc.ts

188 lines
7.2 KiB
TypeScript

import { lstat, readdir, rm, rmdir, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { acquireDeliveryAttemptLock } from '@/lib/delivery-revisions'
import { findPurgeFileReferences, identifyPurgeFile, removePurgeFile, snapshotPurgeFile, type PurgeFile } from '@/lib/material-purge-files'
import { prisma } from '@/lib/prisma'
import { deleteStoredUploadFileFromRemote } from '@/lib/remote-upload-sync'
import { buildStoredUploadPath, getUploadRootDir } from '@/lib/upload-paths'
import { cleanExpiredXiaoyiUpload, XIAOYI_GC_GRACE_MS } from '@/lib/temp-cleanup'
const MARKER = '.gc-candidate'
const SAFE_PROJECT = /^[A-Za-z0-9_-]{1,80}$/
const SAFE_ATTEMPT = /^[A-Za-z0-9_-]{1,117}$/
const SAFE_UPLOAD = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/
const SAFE_OWNER = /^[a-f0-9]{64}$/
const BATCH = 50
type Outcome = 'candidate' | 'marked' | 'retained' | 'deleted' | 'skipped' | 'unavailable'
async function safeStat(file: string) {
const stat = await lstat(file).catch((error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return null
throw error
})
if (stat?.isSymbolicLink()) throw new Error('交付文件路径包含符号链接')
return stat
}
async function directories(root: string, pattern: RegExp) {
if (!(await safeStat(root))?.isDirectory()) return []
return (await readdir(root, { withFileTypes: true }))
.filter(item => item.isDirectory() && pattern.test(item.name)).map(item => item.name).sort()
}
async function inspectAttempt(root: string, parts: string[], dryRun: boolean): Promise<Outcome> {
const [owner, project, attempt] = parts
const folder = path.join(root, ...parts)
const cutoff = Date.now() - XIAOYI_GC_GRACE_MS
const initial = await safeStat(folder)
if (!initial?.isDirectory() || initial.mtimeMs > cutoff) return 'skipped'
const release = await acquireDeliveryAttemptLock(owner, project, attempt, 500)
try {
let location = path.dirname(root)
for (const segment of [path.basename(root), ...parts]) {
location = path.join(location, segment)
if (!(await safeStat(location))?.isDirectory()) return 'skipped'
}
const marker = path.join(folder, MARKER)
const markerStat = await safeStat(marker)
if (markerStat && !markerStat.isFile()) return 'unavailable'
const files: PurgeFile[] = []
const nestedFolders: string[] = []
const walk = async (relative: string[], depth: number): Promise<boolean> => {
for (const name of await readdir(path.join(folder, ...relative))) {
if (relative.length === 0 && name === MARKER) continue
if (name.includes('\\') || /[\x00-\x1f]/.test(name)) return false
const child = [...relative, name]
const target = path.join(folder, ...child)
const stat = await safeStat(target)
if (!stat || stat.mtimeMs > cutoff) return false
if (stat.isDirectory() && depth < 3) {
if (!await walk(child, depth + 1)) return false
nestedFolders.push(target)
} else if (stat.isFile() && files.length < 500) {
const file = identifyPurgeFile(buildStoredUploadPath('xiaoyi-deliveries', ...parts, ...child))
if (!file) return false
files.push(await snapshotPurgeFile(file))
} else return false
}
return true
}
if (!await walk([], 0)) return 'unavailable'
const refs = await findPurgeFileReferences(prisma, files)
release.assertHeld()
if (refs.size) {
if (!dryRun && markerStat) await rm(marker, { force: true })
return 'retained'
}
if (!markerStat) {
if (dryRun) return 'candidate'
await writeFile(marker, new Date().toISOString(), { flag: 'wx' })
return 'marked'
}
if (markerStat.mtimeMs > cutoff) return 'marked'
if (dryRun) return 'candidate'
for (const file of files) {
release.assertHeld()
await deleteStoredUploadFileFromRemote(file.source)
await removePurgeFile(file)
}
for (const directory of nestedFolders) await rmdir(directory)
await rm(marker, { force: true })
await rmdir(folder)
return 'deleted'
} finally {
await release()
}
}
async function* attempts(root: string) {
for (const owner of await directories(root, SAFE_OWNER)) {
for (const project of await directories(path.join(root, owner), SAFE_PROJECT)) {
for (const attempt of await directories(path.join(root, owner, project), SAFE_ATTEMPT)) {
yield [owner, project, attempt]
}
}
}
}
function summarizeGcOutcomes(rows: Array<{ key: string; outcome: Outcome }>) {
const summary: Record<Outcome, number> & { total: number } = {
total: rows.length,
candidate: 0,
marked: 0,
retained: 0,
deleted: 0,
skipped: 0,
unavailable: 0,
}
for (const row of rows) summary[row.outcome] += 1
return summary
}
export async function collectXiaoyiDeliveryGarbage(options: {
dryRun?: boolean; kind: 'deliveries' | 'uploads'; after?: string
}) {
const dryRun = options.dryRun !== false
const uploadRoot = getUploadRootDir()
const root = path.join(uploadRoot, options.kind === 'deliveries' ? 'xiaoyi-deliveries' : 'temp')
const rows: Array<{ key: string; outcome: Outcome }> = []
if (!(await safeStat(uploadRoot))?.isDirectory()) {
return { dryRun, rows, next: null, summary: summarizeGcOutcomes(rows) }
}
const keys = options.kind === 'deliveries' ? attempts(root)
: (await directories(root, SAFE_UPLOAD)).map(key => [key])
const cursor = options.after?.split('/')
for await (const parts of keys) {
const key = parts.join('/')
if (cursor) {
const difference = parts.findIndex((part, index) => part !== cursor[index])
if (difference === -1 || parts[difference] < (cursor[difference] ?? '')) continue
}
if (rows.length === BATCH) {
return { dryRun, rows, next: rows[rows.length - 1].key, summary: summarizeGcOutcomes(rows) }
}
try {
let outcome: Outcome
if (options.kind === 'deliveries') outcome = await inspectAttempt(root, parts, dryRun)
else outcome = await cleanExpiredXiaoyiUpload(parts[0], dryRun)
rows.push({ key, outcome })
} catch (error) {
console.warn('[xiaoyi-gc] 保留暂无法核对的文件', { key, error })
rows.push({ key, outcome: 'unavailable' })
}
}
return { dryRun, rows, next: null, summary: summarizeGcOutcomes(rows) }
}
export async function reconcileXiaoyiOrphanStorage(options?: { dryRun?: boolean; maxBatches?: number }) {
const dryRun = options?.dryRun !== false
const maxBatches = Number.isFinite(options?.maxBatches) && Number(options?.maxBatches) > 0
? Math.min(Number(options?.maxBatches), 100)
: 20
const runKind = async (kind: 'uploads' | 'deliveries') => {
const totals = summarizeGcOutcomes([])
let after: string | undefined
let batches = 0
let truncated = false
while (batches < maxBatches) {
batches += 1
const page = await collectXiaoyiDeliveryGarbage({ dryRun, kind, after })
for (const [key, count] of Object.entries(page.summary) as Array<[keyof typeof totals, number]>) {
totals[key] += count
}
if (!page.next) break
after = page.next
if (batches >= maxBatches) truncated = true
}
return { ...totals, batches, truncated }
}
return {
dryRun,
uploads: await runKind('uploads'),
deliveries: await runKind('deliveries'),
}
}