const { test } = require('node:test') const assert = require('node:assert/strict') const fs = require('node:fs') const path = require('node:path') const vm = require('node:vm') const ts = require('typescript') function load(file, imports, logger = { log() {}, error() {} }, timers = { setTimeout, clearTimeout }) { const source = fs.readFileSync(path.join(__dirname, '../localServer', file), 'utf8') const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText const exports = {} const customRequire = (name) => { if (!(name in imports)) throw new Error(`Unexpected import: ${name}`) return imports[name] } customRequire.resolve = require.resolve vm.runInNewContext(compiled, { exports, console: logger, process, ...timers, require: customRequire }) return exports } const os = require('node:os') const Jimp = require('jimp') const sharp = require('sharp') const childProcess = require('node:child_process') test('CDN下载拒绝立即返回,半成品稳定仍等待,完整大小才就绪,超时清理', async () => { let accepted = false let sizes = [50] let stats = 0 let opened = 0 let removed = 0 let sleeps = 0 const { cdnDownloadImg3 } = load('utils/index.ts', { electron: { app: { isPackaged: false } }, axios: { default: {} }, fs: { default: { existsSync: () => true, promises: { stat: async () => ({ size: sizes[Math.min(stats++, sizes.length - 1)] }), open: async () => { opened++; return { close: async () => {} } }, unlink: async () => { removed++ } } } }, path: { default: path }, crypto: { randomUUID: () => 'test' }, '../api/hookRequest': { default: { fetchCdnDownloadImg: async () => accepted } }, '../config/envConfig': { default: {} } }, undefined, { setTimeout: (callback) => { sleeps++; return setImmediate(callback) }, clearTimeout }) const data = { aes_key: 'key', cdn_key: 'cdn', size: 100, img_type: 1 } assert.equal(await cdnDownloadImg3(data), '') assert.equal(stats, 0) assert.equal(sleeps, 0) accepted = true sizes = [...Array(8).fill(50), ...Array(7).fill(100)] assert.ok((await cdnDownloadImg3(data)).endsWith('key-test.png')) assert.equal(stats, 15) assert.equal(opened, 1) stats = 0 sizes = [50] assert.equal(await cdnDownloadImg3(data), '') assert.equal(stats, 200) assert.equal(opened, 1) assert.equal(removed, 4) stats = 0 sizes = [...Array(100).fill(50), ...Array(7).fill(100)] assert.ok((await cdnDownloadImg3(data)).endsWith('key-test.png')) assert.equal(stats, 107) assert.equal(opened, 2) }) test('图片消息 ID 追加 aes_key 尾三位,其他消息保持原规则', () => { const mapping = load('utils/dataMapping/mapMsgType_V2.ts', { '../../types/typesMsg': {}, '../../const/CONST_MSG_TYPE': { default: { 9: '图片消息', 0: '文本消息' } }, '../../const/CONST_MSG_TYPE_V2': { default: { 14: '图片消息', 2: '文本消息' } } }) const image = mapping.formatMsg_V2({ type: 100, msg_type: 14, user_id: 'R:1234567890', sender: 'sender', time_stamp: 100, content: { aes_key: 'abcdef123' }, is_self_msg: 0, self_user_id: 'self', at_list: [], send_nick_name: 'name' }) assert.equal(image.msg_id, '7890100123') const text = mapping.formatMsg_V2({ type: 100, msg_type: 2, user_id: 'R:1234567890', sender: 'sender', time_stamp: 100, content: 'text', is_self_msg: 0, self_user_id: 'self', at_list: [], send_nick_name: 'name' }) assert.equal(text.msg_id, '7890100') }) function loadCompression(logger) { return load('utils/compressImage.ts', { fs: { default: fs }, path: { default: path }, child_process: childProcess }, logger).compressImage } test('压缩超时等待子进程退出再清理文件,下一张成功时不强杀', async () => { const { EventEmitter } = require('node:events') const events = [] const errors = [] let count = 0 class ImageProcess extends EventEmitter { constructor() { super() this.exitCode = null this.signalCode = null this.number = ++count } send(data) { if (this.number === 3) setImmediate(() => { this.exitCode = 3221225477 this.emit('close', this.exitCode, null) }) if (this.number === 2) setImmediate(() => { this.emit('message', { uploadPath: data.outputPath, reason: '压缩成功', originalBytes: 3000000, uploadBytes: 1000000 }) this.exitCode = 0 this.emit('close', 0, null) }) } kill() { events.push('kill') setImmediate(() => { this.signalCode = 'SIGTERM' events.push('close') this.emit('close', null, 'SIGTERM') }) } } const { compressImage } = load('utils/compressImage.ts', { fs: { default: { promises: { stat: async () => ({ size: 3000000 }), unlink: async () => events.push('unlink') } } }, path: { default: path }, child_process: { spawn: () => new ImageProcess() } }, { log() {}, error: (message) => errors.push(message) }, { setTimeout: (callback, ms) => { assert.equal(ms, 60000) return setTimeout(callback, 50) }, clearTimeout }) assert.equal(await compressImage('stuck.jpg'), 'stuck.jpg') assert.deepEqual(events, ['kill', 'close', 'unlink']) assert.match(errors[0], /图片处理进程超时/) assert.equal(await compressImage('next.jpg'), 'next.jpg.upload.jpg') assert.deepEqual(events, ['kill', 'close', 'unlink']) assert.equal(await compressImage('crashed.jpg'), 'crashed.jpg') assert.match(errors.at(-1), /code=3221225477/) }) test('真实子进程压缩大 PNG,保留尺寸,透明图片、动图、坏图和小图保留原文件', async () => { const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'image-processing-')) try { const logs = [] const errors = [] const compressImage = loadCompression({ log: (message) => logs.push(JSON.parse(message.slice('[图片处理完成] '.length))), error: (message) => errors.push(JSON.parse(message.slice('[图片压缩失败] '.length))) }) const image = new Jimp(1024, 768, 0xffffffff) image.deflateLevel(0) const original = path.join(directory, 'report.png') await sharp(await image.getBufferAsync(Jimp.MIME_PNG)).removeAlpha().png({ compressionLevel: 0 }).toFile(original) assert.ok((await fs.promises.stat(original)).size > 2 * 1024 * 1024) let ticks = 0 const timer = setInterval(() => ticks++, 5) let output try { output = await compressImage(original) } finally { clearInterval(timer) } // 必须真的生成 JPEG,不能把异常回退误认为测试成功。 assert.equal(output, `${original}.upload.jpg`) assert.equal(logs.at(-1).reason, '压缩成功') assert.equal(logs.at(-1).fileName, path.basename(original)) assert.equal(logs.at(-1).uploadFileName, path.basename(output)) assert.equal(logs.at(-1).uploadBytes, (await fs.promises.stat(output)).size) assert.ok(ticks > 0, '编码期间主线程应继续响应定时器') const compressed = await Jimp.read(output) assert.equal(compressed.bitmap.width, 1024) assert.equal(compressed.bitmap.height, 768) assert.ok((await fs.promises.stat(output)).size <= (await fs.promises.stat(original)).size * 0.9) const transparent = path.join(directory, 'transparent.png') image.setPixelColor(0xffffff00, 0, 0) await image.writeAsync(transparent) assert.equal(await compressImage(transparent), transparent) assert.equal(logs.at(-1).reason, '含透明像素') assert.equal(fs.existsSync(`${transparent}.upload.jpg`), false) // APNG 的 acTL 块足以判定需要保留动画,不应进入单帧解码。 const apng = path.join(directory, 'animation.png') const png = await fs.promises.readFile(original) const animationControl = Buffer.alloc(20) animationControl.writeUInt32BE(8, 0) animationControl.write('acTL', 4) await fs.promises.writeFile(apng, Buffer.concat([png.subarray(0, 33), animationControl, png.subarray(33)])) assert.equal(await compressImage(apng), apng) assert.equal(logs.at(-1).reason, '动图') for (const [name, header] of [['animation.gif', 'GIF89a'], ['bad.png', 'bad']]) { const file = path.join(directory, name) const bytes = Buffer.alloc(3 * 1024 * 1024) bytes.write(header) await fs.promises.writeFile(file, bytes) assert.equal(await compressImage(file), file) assert.equal(logs.at(-1).reason, '不支持的格式') } const broken = path.join(directory, 'broken.png') await fs.promises.writeFile(broken, Buffer.concat([png.subarray(0, 8), Buffer.alloc(3 * 1024 * 1024)])) assert.equal(await compressImage(broken), broken) assert.equal(errors.at(-1).filePath, broken) assert.equal(errors.at(-1).reason, '异常回退原图') const small = path.join(directory, 'small.png') await new Jimp(10, 10, 0xffffffff).writeAsync(small) assert.equal(await compressImage(small), small) assert.equal(logs.at(-1).reason, '不超过2MB') assert.equal(logs.at(-1).fileName, path.basename(small)) } finally { await fs.promises.rm(directory, { recursive: true, force: true }) } }) test('真实 JPEG 压缩将 EXIF 方向固化到像素,输出不再携带方向标记', async () => { const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'image-orientation-')) try { const source = await sharp({ create: { width: 80, height: 40, channels: 3, background: '#00aa00' } }).withMetadata({ orientation: 6 }).jpeg().toBuffer() const file = path.join(directory, 'oriented.jpg') await fs.promises.writeFile(file, Buffer.concat([source, Buffer.alloc(3 * 1024 * 1024)])) const output = await loadCompression()(file) assert.equal(output, `${file}.upload.jpg`) const metadata = await sharp(output).metadata() assert.equal(metadata.width, 40) assert.equal(metadata.height, 80) assert.equal(metadata.orientation, undefined) } finally { await fs.promises.rm(directory, { recursive: true, force: true }) } }) test('图片处理单并发,失败继续,上传后清理文件', async () => { const events = [] const errors = [] const backlogSizes = [] const pending = [] const message = (id) => ({ id, wxMsgId: id, contentType: 9, contentImageInfo: JSON.stringify({ aes_key: id }) }) const api = { saveMsg: async (data) => message(data.wxMsgId), uploadImg: async (file) => { events.push(`upload:${file}`); return 'image.jpg' }, updateMsg: (data) => { events.push(`update:${data.id}`) return new Promise((resolve) => pending.push(resolve)) } } const { default: service } = load('services/receiveMsgServices.ts', { '../store/data': { default: { get: (key) => key === 'accInfo' ? { nick_name: 'test' } : '' } }, '../const/CONST_MSG_TYPE': { default: {} }, '../api/hookRequest': { default: {} }, '../config/envConfig': { default: { urlENV: { OSS_BASE: 'https://oss/' } } }, '../api/scrm/serverRequest': { default: api }, '../utils/index': { cdnDownloadImg3: async (image) => { events.push(`download:${image.aes_key}`) if (image.aes_key === 'bad') throw new Error('download failed') return `${image.aes_key}-temp.png` } }, '../utils/compressImage': { compressImage: async (file) => { events.push(`compress:${file}`) return `${file}.upload.jpg` } }, fs: { default: { promises: { stat: async () => ({ size: 1234 }), unlink: async (file) => events.push(`delete:${file}`) } } }, path: { default: path } }, { log: (label, details) => { if (label === '[图片队列积压]') backlogSizes.push(JSON.parse(details).pending) }, error: (...args) => errors.push(args) }) const flush = () => new Promise((resolve) => setImmediate(resolve)) for (const id of ['first', 'bad', 'last']) { await service.formatAndSaveMsg({ msg_id: id, msgtype: 9, content: {} }) } await flush() assert.equal(events.filter((event) => event.startsWith('download:')).join(','), 'download:first') pending[0](true) await flush() assert.equal(events.filter((event) => event.startsWith('download:')).join(','), 'download:first,download:bad,download:last') assert.ok(events.indexOf('download:bad') > events.indexOf('update:first')) for (const id of ['first', 'last']) { const upload = events.indexOf(`upload:${id}-temp.png.upload.jpg`) const cleanup = events.indexOf(`delete:${id}-temp.png.upload.jpg`) const originalCleanup = events.indexOf(`delete:${id}-temp.png`) const update = events.indexOf(`update:${id}`) assert.ok(upload >= 0 && upload < cleanup && cleanup < originalCleanup && originalCleanup < update) } assert.equal(events.at(-1), 'update:last') // 回写尚未完成时最多接收 100 张待处理图片,超出的消息明确报错。 for (let i = 0; i < 101; i++) { await service.formatAndSaveMsg({ msg_id: `queued-${i}`, msgtype: 9, content: {} }) } await flush() assert.equal(errors.filter((args) => args[0] === '[图片队列已满]').length, 1) assert.deepEqual(backlogSizes, [20, 40, 60, 80, 100]) api.updateMsg = async () => true pending[1](true) await flush() const downloads = events.filter((event) => event.startsWith('download:queued-')) assert.equal(downloads.length, 100) assert.ok(!events.includes('download:queued-100')) await service.formatAndSaveMsg({ msg_id: 'after-drain', msgtype: 9, content: {} }) await flush() assert.ok(events.includes('download:after-drain')) })