192 lines
11 KiB
TypeScript
192 lines
11 KiB
TypeScript
import { spawn } from 'child_process'
|
||
import { createHash, randomUUID } from 'crypto'
|
||
import { chmod, copyFile, lstat, mkdtemp, mkdir, readdir, rename, rm, stat, unlink, writeFile } from 'fs/promises'
|
||
import path from 'path'
|
||
import { tmpdir } from 'os'
|
||
import { pathToFileURL } from 'url'
|
||
import { prisma } from './prisma'
|
||
import { performanceAttachmentPath } from './performance-survey-attachment-storage'
|
||
import { PERFORMANCE_CASE_ATTACHMENT_LIMITS } from './performance-survey-attachment-contract'
|
||
|
||
const LEASE_MS = 10 * 60_000
|
||
const SCRATCH_LIMIT = 512 * 1024 * 1024
|
||
const OFFICE_EXECUTABLE = '/usr/lib/libreoffice/program/soffice.bin'
|
||
|
||
class OfficeProfileRestart extends Error {}
|
||
|
||
async function directoryBytes(directory: string): Promise<number> {
|
||
const entries = await readdir(directory, { withFileTypes: true })
|
||
let bytes = 0
|
||
for (const entry of entries) {
|
||
const file = path.join(directory, entry.name)
|
||
if (entry.isSymbolicLink()) throw new Error('预览目录存在非法链接')
|
||
bytes += entry.isDirectory() ? await directoryBytes(file) : (await stat(file)).size
|
||
}
|
||
return bytes
|
||
}
|
||
|
||
// Converters see only system executables, fonts and this attempt's disposable files.
|
||
export async function runPerformancePreviewCommand(directory: string, executable: string, args: string[], timeout = 300_000) {
|
||
if (process.platform !== 'linux') throw new Error('预览需要Linux文档转换沙箱,请在配置的容器环境重试')
|
||
const temp = path.join(directory, 'temp')
|
||
await mkdir(temp, { recursive: true, mode: 0o700 })
|
||
const converterArgs = args.map((argument) => argument.replaceAll('/work', directory))
|
||
return new Promise<string>((resolve, reject) => {
|
||
const child = spawn('/usr/local/bin/performance-preview-sandbox', [directory, executable, ...converterArgs], {
|
||
detached: true,
|
||
stdio: ['ignore', 'pipe', 'pipe'],
|
||
env: { NODE_ENV: 'production', PATH: '/usr/bin:/bin', HOME: path.join(directory, 'profile'), TMPDIR: temp, LANG: 'C.UTF-8', SAL_USE_VCLPLUGIN: 'svp' },
|
||
})
|
||
let output = ''
|
||
let failure: Error | null = null
|
||
const stop = (message: string) => {
|
||
failure = new Error(message)
|
||
try { process.kill(-child.pid!, 'SIGKILL') } catch { child.kill('SIGKILL') }
|
||
}
|
||
const timer = setTimeout(() => stop('预览生成超时,可重试或下载原件'), timeout)
|
||
let checking = false
|
||
const diskTimer = setInterval(() => {
|
||
if (checking) return
|
||
checking = true
|
||
void directoryBytes(directory).then((bytes) => {
|
||
if (bytes > SCRATCH_LIMIT) stop('预览临时文件超过512MB限制')
|
||
}).catch(() => stop('预览临时目录不可用')).finally(() => { checking = false })
|
||
}, 1000)
|
||
const collect = (chunk: Buffer) => {
|
||
output += chunk.toString()
|
||
if (output.length > 64_000) stop('预览输出超过限制')
|
||
}
|
||
child.stdout.on('data', collect)
|
||
child.stderr.on('data', collect)
|
||
child.on('error', (error) => { failure = error })
|
||
child.on('close', (code) => {
|
||
clearTimeout(timer)
|
||
clearInterval(diskTimer)
|
||
// A converter may fork helpers. Stop its process group before inspecting
|
||
// artifacts so a surviving child cannot race file validation and copying.
|
||
try { process.kill(-child.pid!, 'SIGKILL') } catch {}
|
||
if (failure) reject(failure)
|
||
else if (executable === OFFICE_EXECUTABLE && code === 81) reject(new OfficeProfileRestart())
|
||
else if (code !== 0) reject(new Error('转换沙箱未完成处理,请检查转换工具及Linux Landlock支持后重试'))
|
||
else resolve(output)
|
||
})
|
||
})
|
||
}
|
||
|
||
async function convertOfficeDocument(directory: string, source: string) {
|
||
const profileUrl = pathToFileURL(path.join(directory, 'profile')).href
|
||
// LibreOffice hashes UTF-16 user-installation URLs and emits unpadded hex.
|
||
const digest = createHash('md5').update(Buffer.from(profileUrl, 'utf16le')).digest()
|
||
const pipeHash = Array.from(digest, (byte) => byte.toString(16)).join('')
|
||
const socket = `/tmp/OSL_PIPE_${process.getuid!()}_SingleOfficeIPC_${pipeHash}`
|
||
const args = [`-env:UserInstallation=${profileUrl}`, '--headless', '--nologo', '--nodefault', '--nolockcheck', '--norestore', '--convert-to', 'pdf', '--outdir', '/work', source]
|
||
for (let attempt = 0; attempt < 2; attempt++) {
|
||
try {
|
||
await runPerformancePreviewCommand(directory, OFFICE_EXECUTABLE, args)
|
||
return
|
||
} catch (error) {
|
||
// A fresh profile requests one restart after registering built-in filters.
|
||
if (!(error instanceof OfficeProfileRestart) || attempt > 0) throw error
|
||
} finally {
|
||
const stats = await lstat(socket).catch(() => null)
|
||
if (stats?.isSocket() && stats.uid === process.getuid!()) await unlink(socket)
|
||
}
|
||
}
|
||
}
|
||
|
||
export async function convertPerformanceAttachment(directory: string, extension: string, kind: string) {
|
||
if (kind === 'video') {
|
||
const probe = JSON.parse(await runPerformancePreviewCommand(directory, '/usr/bin/ffprobe', ['-v', 'error', '-show_streams', '-of', 'json', `/work/source.${extension}`]))
|
||
if (!probe.streams?.some((stream: any) => stream.codec_type === 'video')) throw new Error('文件没有可播放的视频轨道')
|
||
await runPerformancePreviewCommand(directory, '/usr/bin/ffmpeg', ['-nostdin', '-v', 'error', '-threads', '1', '-i', `/work/source.${extension}`, '-map', '0:v:0', '-map', '0:a:0?', '-vf', 'scale=w=1280:h=1280:force_original_aspect_ratio=decrease:force_divisible_by=2', '-c:v', 'libx264', '-threads', '1', '-preset', 'fast', '-crf', '23', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-movflags', '+faststart', '/work/playback.mp4'])
|
||
return { pageCount: null, previewPageCount: null }
|
||
}
|
||
let pdf = `/work/source.${extension}`
|
||
if (extension !== 'pdf') {
|
||
const profile = path.join(directory, 'profile/user')
|
||
await mkdir(profile, { recursive: true })
|
||
await writeFile(path.join(profile, 'registrymodifications.xcu'), '<?xml version="1.0"?><oor:items xmlns:oor="http://openoffice.org/2001/registry"><item oor:path="/org.openoffice.Office.Common/Security/Scripting"><prop oor:name="MacroSecurityLevel" oor:op="fuse"><value>3</value></prop></item><item oor:path="/org.openoffice.Office.Common/Load"><prop oor:name="UpdateDocMode" oor:op="fuse"><value>0</value></prop></item></oor:items>')
|
||
await convertOfficeDocument(directory, pdf)
|
||
pdf = '/work/source.pdf'
|
||
}
|
||
const info = await runPerformancePreviewCommand(directory, '/usr/bin/pdfinfo', [pdf])
|
||
const pageCount = Number(info.match(/^Pages:\s+(\d+)/m)?.[1])
|
||
if (!Number.isSafeInteger(pageCount) || pageCount < 1) throw new Error('文档没有可预览页面')
|
||
const previewPageCount = Math.min(pageCount, PERFORMANCE_CASE_ATTACHMENT_LIMITS.previewPages)
|
||
await runPerformancePreviewCommand(directory, '/usr/bin/pdftoppm', ['-f', '1', '-l', String(previewPageCount), '-scale-to', '1600', '-jpeg', '-jpegopt', 'quality=82', pdf, '/work/page'])
|
||
const generatedPages = await readdir(directory)
|
||
for (let page = 1; page <= previewPageCount; page++) {
|
||
const generated = generatedPages.find((name) => new RegExp(`^page-0*${page}\\.jpg$`).test(name))
|
||
if (!generated) throw new Error('文档页面生成不完整')
|
||
await rename(path.join(directory, generated), path.join(directory, `${page}.jpg`))
|
||
await chmod(path.join(directory, `${page}.jpg`), 0o600)
|
||
}
|
||
return { pageCount, previewPageCount }
|
||
}
|
||
|
||
export async function processNextPerformanceAttachment() {
|
||
const token = randomUUID()
|
||
const attachment = await prisma.$transaction(async (tx) => {
|
||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(721569204)`
|
||
const now = new Date()
|
||
if (await tx.performanceSurveyAttachment.count({ where: { status: 'processing', leaseExpiresAt: { gt: now } } })) return null
|
||
const job = await tx.performanceSurveyAttachment.findFirst({ where: { OR: [{ status: 'queued' }, { status: 'processing', leaseExpiresAt: { lt: now } }] }, orderBy: { createdAt: 'asc' } })
|
||
if (!job) return null
|
||
if (job.attempts >= 3) {
|
||
await tx.performanceSurveyAttachment.update({ where: { id: job.id }, data: { status: 'failed', error: '预览进程多次中断,请重试', leaseToken: null, leaseExpiresAt: null } })
|
||
return null
|
||
}
|
||
return tx.performanceSurveyAttachment.update({ where: { id: job.id }, data: { status: 'processing', attempts: { increment: 1 }, leaseToken: token, leaseExpiresAt: new Date(Date.now() + LEASE_MS) } })
|
||
})
|
||
if (!attachment) return false
|
||
let directory: string | undefined
|
||
let scratch: string | undefined
|
||
const heartbeat = setInterval(() => {
|
||
void prisma.performanceSurveyAttachment.updateMany({ where: { id: attachment.id, leaseToken: token }, data: { leaseExpiresAt: new Date(Date.now() + LEASE_MS) } }).catch(() => {})
|
||
}, 30_000)
|
||
let retain = false
|
||
try {
|
||
const original = await performanceAttachmentPath(attachment.id, `original.${attachment.extension}`)
|
||
const parent = path.dirname(original)
|
||
for (const entry of await readdir(parent)) {
|
||
if (/^attempt-[0-9a-f-]{36}$/.test(entry) && entry !== attachment.previewKey) await rm(path.join(parent, entry), { recursive: true, force: true })
|
||
}
|
||
directory = path.join(parent, `attempt-${token}`)
|
||
await mkdir(directory, { mode: 0o700 })
|
||
scratch = await mkdtemp(path.join(tmpdir(), 'performance-preview-'))
|
||
await copyFile(original, path.join(scratch, `source.${attachment.extension}`))
|
||
const result = await convertPerformanceAttachment(scratch, attachment.extension, attachment.kind)
|
||
if (await directoryBytes(scratch) > SCRATCH_LIMIT) throw new Error('预览临时文件超过512MB限制')
|
||
const artifacts = attachment.kind === 'video' ? ['playback.mp4'] : Array.from({ length: result.previewPageCount || 0 }, (_, index) => `${index + 1}.jpg`)
|
||
for (const artifact of artifacts) {
|
||
const source = path.join(scratch, artifact)
|
||
if (!(await stat(source)).isFile()) throw new Error('预览文件生成不完整')
|
||
await copyFile(source, path.join(directory, artifact))
|
||
await chmod(path.join(directory, artifact), 0o600)
|
||
}
|
||
const updated = await prisma.performanceSurveyAttachment.updateMany({ where: { id: attachment.id, leaseToken: token, status: 'processing' }, data: { status: 'ready', previewKey: `attempt-${token}`, ...result, error: null, leaseToken: null, leaseExpiresAt: null } })
|
||
retain = updated.count === 1
|
||
} catch (error) {
|
||
await prisma.performanceSurveyAttachment.updateMany({ where: { id: attachment.id, leaseToken: token }, data: { status: 'failed', error: error instanceof Error ? error.message.slice(0, 300) : '预览生成失败', leaseToken: null, leaseExpiresAt: null } })
|
||
} finally {
|
||
clearInterval(heartbeat)
|
||
if (scratch) await rm(scratch, { recursive: true, force: true })
|
||
if (directory && !retain) await rm(directory, { recursive: true, force: true })
|
||
}
|
||
return true
|
||
}
|
||
|
||
export function ensurePerformanceAttachmentWorkerStarted() {
|
||
const state = globalThis as typeof globalThis & { __performanceAttachmentWorker?: NodeJS.Timeout; __performanceAttachmentBusy?: boolean }
|
||
if (state.__performanceAttachmentWorker) return
|
||
const tick = async () => {
|
||
if (state.__performanceAttachmentBusy) return
|
||
state.__performanceAttachmentBusy = true
|
||
try { await processNextPerformanceAttachment() } catch (error) { console.error('[performance-attachment] 预览队列检查失败', error) }
|
||
finally { state.__performanceAttachmentBusy = false }
|
||
}
|
||
state.__performanceAttachmentWorker = setInterval(() => { void tick() }, 5000)
|
||
state.__performanceAttachmentWorker.unref()
|
||
void tick()
|
||
}
|