/* 附录B真实TCP验收:主站独立构造报文和核对字节,不借用被测库的编解码。 * 两次运行共享同一持久存储,模拟校时不修改宿主系统时间;产物全部位于本目录.build。 */ 'use strict'; const assert = require('node:assert/strict'); const net = require('node:net'); const fs = require('node:fs'); const path = require('node:path'); const { spawn } = require('node:child_process'); const { once } = require('node:events'); const { setTimeout: delay } = require('node:timers/promises'); const executable = process.argv[2]; if (!executable) throw new Error('Usage: node history_loopback_test.cjs '); const project = path.resolve(__dirname, '..'); const artifact = path.join(project, '.build'); fs.mkdirSync(artifact, { recursive: true }); const store = fs.mkdtempSync(path.join(artifact, 'history-loopback-')); /* 按APDU长度拆包,串行维护收发序号;每个收到的I帧立即确认,避免窗口阻塞影响内容验收。 */ class Master { constructor(socket) { this.socket = socket; this.buffer = Buffer.alloc(0); this.frames = []; this.waiters = []; this.ns = 0; this.nr = 0; socket.on('data', bytes => { this.buffer = Buffer.concat([this.buffer, bytes]); try { while (this.buffer.length >= 2) { assert.equal(this.buffer[0], 0x68); const size = this.buffer[1] + 2; assert(size >= 6 && size <= 255); if (this.buffer.length < size) break; const frame = this.buffer.subarray(0, size); this.buffer = this.buffer.subarray(size); const waiter = this.waiters.shift(); if (waiter) { clearTimeout(waiter.timer); waiter.resolve(frame); } else this.frames.push(frame); } } catch (error) { this.fail(error); } }); socket.on('error', error => this.fail(error)); socket.on('close', () => this.fail(new Error('TCP closed'))); } fail(error) { this.error = error; for (const waiter of this.waiters.splice(0)) { clearTimeout(waiter.timer); waiter.reject(error); } } next() { if (this.frames.length) return Promise.resolve(this.frames.shift()); if (this.error) return Promise.reject(this.error); return new Promise((resolve, reject) => { const waiter = { resolve, reject }; waiter.timer = setTimeout(() => { this.waiters.splice(this.waiters.indexOf(waiter), 1); reject(new Error('TCP response timeout')); }, 10000); this.waiters.push(waiter); }); } send(asdu) { const frame = Buffer.alloc(asdu.length + 6); frame[0] = 0x68; frame[1] = asdu.length + 4; frame.writeUInt16LE(this.ns++ << 1, 2); frame.writeUInt16LE(this.nr << 1, 4); Buffer.from(asdu).copy(frame, 6); this.socket.write(frame); } async read() { for (;;) { const frame = await this.next(); if (frame[2] === 1) continue; assert.equal(frame[2] & 1, 0); assert.equal(frame.readUInt16LE(2) >> 1, this.nr++); assert((frame.readUInt16LE(4) >> 1) <= this.ns); const ack = Buffer.from([0x68, 4, 1, 0, 0, 0]); ack.writeUInt16LE(this.nr << 1, 4); this.socket.write(ack); return frame.subarray(6); } } async receive(type, operation) { for (let i = 0; i < 100; ++i) { const asdu = await this.read(); if (asdu[0] !== type) { assert([1, 3, 11, 30, 31, 35].includes(asdu[0]), `Unexpected TI ${asdu[0]}`); continue; } if (operation !== undefined) assert.equal(asdu[10], operation); return asdu; } throw new Error('Expected ASDU absent'); } } const u32 = value => { const out = Buffer.alloc(4); out.writeUInt32LE(value); return out; }; const named = value => { const bytes = Buffer.from(value, 'utf8'); return Buffer.concat([Buffer.from([bytes.length]), bytes]); }; const fileHead = (operation, cause) => Buffer.from([210, 1, cause, 0x41, 7, 0, 0, 0, 0, 2, operation]); const cp56 = (day, hour = 0, minute = 0) => Buffer.from([0, 0, minute, hour, day, 1, 90]); /* 在随机端口启动独立子进程,完成START/初始化/站总召后才允许IDLE文件数据推进。 * 返回的stop强制结束进程,用于验证恢复不依赖正常退出的收尾路径。 */ async function start() { const child = spawn(executable, ['--port', '0', '--ca', '7', '--run-ms', '60000', '--history', store, '--events', '0', '--background-ms', '0', '--cyclic-ms', '0', '--no-parameter'], { cwd: project, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); let output = '', errors = ''; child.stdout.on('data', b => { output += b; }); child.stderr.on('data', b => { errors += b; }); const exited = once(child, 'exit'); const deadline = setTimeout(() => child.kill(), 65000); let socket; try { let port; for (let i = 0; i < 1000; ++i) { const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/); if (match) { port = Number(match[1]); break; } if (child.exitCode !== null) break; await delay(10); } assert(port, `No listener: ${output}\n${errors}`); socket = net.connect({ host: '127.0.0.1', port }); const master = new Master(socket); await once(socket, 'connect'); socket.write(Buffer.from([0x68, 4, 7, 0, 0, 0])); assert.deepEqual([...(await master.next())], [0x68, 4, 11, 0, 0, 0]); const initialization = await master.read(); assert.equal(initialization[0], 70); master.send([100, 1, 6, 0x40, 7, 0, 0, 0, 0, 20]); for (let i = 0; i < 40; ++i) { const asdu = await master.read(); if (asdu[0] === 100 && asdu[2] === 10) break; if (i === 39) throw new Error('Startup GI not completed'); } return { master, async stop() { socket.destroy(); /* Force process termination: recovery must not depend on graceful shutdown. */ child.kill(); await exited; clearTimeout(deadline); assert.equal(errors, '', errors); } }; } catch (error) { clearTimeout(deadline); if (socket) socket.destroy(); child.kill(); await exited; error.message += `\n${output}\n${errors}`; throw error; } } /* 逐个冻结时段推进应用模拟时钟,确认后留出同轮观测执行时间,不跳过中间96节。 */ async function setTime(master, day, hour, minute) { master.send(Buffer.concat([Buffer.from([103, 1, 6, 0x40, 7, 0, 0, 0, 0]), cp56(day, hour, minute)])); const response = await master.receive(103); assert.equal(response[2], 7); await delay(10); // Permit the application's same-cycle observation to complete. } /* 非零请求目录ID只作为兼容输入;目录名确定资源,响应保留字段仍必须为零。 * range同时覆盖带时间筛选和无筛选两种目录召唤,按后续帧标志拼接所有条目。 */ async function directory(master, name, id = 0, range = null) { const filter = range ? Buffer.concat([Buffer.from([1]), range[0], range[1]]) : Buffer.alloc(15); master.send(Buffer.concat([fileHead(1, 5), u32(id), named(name), filter])); const entries = []; for (let page = 0; page < 30; ++page) { const response = await master.receive(210, 2); assert.equal(response[2], 5); assert.equal(response[11], 0); assert.equal(response.readUInt32LE(12), 0, 'Reserved ID must be zero even with a nonzero directory request'); let cursor = 18; for (let i = 0; i < response[17]; ++i) { const size = response[cursor++]; const filename = response.subarray(cursor, cursor + size).toString('utf8'); cursor += size; assert.equal(response[cursor++], 0); const bytes = response.readUInt32LE(cursor); cursor += 4; const time = Buffer.from(response.subarray(cursor, cursor + 7)); cursor += 7; entries.push({ name: filename, size: bytes, time }); } assert.equal(cursor, response.length); if (response[16] === 0) return entries; assert.equal(response[16], 1); } throw new Error('Directory pagination did not finish'); } /* 逐段检查激活名称、声明大小、偏移、模和与末段总长度,成功后才交付完整文件字节。 */ async function readFile(master, entry) { master.send(Buffer.concat([fileHead(3, 6), named(entry.name)])); const activation = await master.receive(210, 4); assert.equal(activation[2], 7); assert.equal(activation[11], 0); const idOffset = 13 + activation[12]; assert.equal(activation.subarray(13, idOffset).toString('utf8'), entry.name); assert.equal(activation.readUInt32LE(idOffset), 0); assert.equal(activation.readUInt32LE(idOffset + 4), entry.size); const chunks = []; let offset = 0; for (let segment = 0; segment < 1000; ++segment) { const response = await master.receive(210, 5); assert.equal(response[2], 5); assert.equal(response.readUInt32LE(11), 0); assert.equal(response.readUInt32LE(15), offset); const content = response.subarray(20, -1); assert.equal(response[response.length - 1], content.reduce((sum, byte) => (sum + byte) & 255, 0)); chunks.push(content); offset += content.length; if (response[19] === 0) { assert.equal(offset, entry.size); master.send(Buffer.concat([fileHead(6, 5), u32(0), response.subarray(15, 19), Buffer.from([0])])); return Buffer.concat(chunks); } assert.equal(response[19], 1); } throw new Error('File transfer did not finish'); } /* 分别覆盖选择、执行和撤销;执行还必须收到结束帧,不能把激活确认当最终完成。 */ async function control(master, ioa, select, cause = 6) { master.send([45, 1, cause, 0x35, 7, 0, ioa & 255, ioa >> 8, 0, select ? 0x81 : 1]); let response = await master.receive(45); assert.equal(response[2], cause === 8 ? 9 : 7); if (!select && cause === 6) { response = await master.receive(45); assert.equal(response[2], 10); } } /* 第一轮生成真实操作历史和完整日文件,第二轮重开相同存储逐字节比对四类下载。 * XML内容断言与线上传输断言分开,防止“传输成功”掩盖条数或时间归属错误。 */ async function run() { const downloads = new Map(); let session = await start(); try { const { master } = session; await setTime(master, 2, 0, 15); await control(master, 0x6001, true); await control(master, 0x6001, false); await control(master, 0x6002, true); await control(master, 0x6002, true, 8); for (let slot = 2; slot <= 96; ++slot) { const minutes = slot * 15; await setTime(master, minutes === 1440 ? 3 : 2, Math.floor(minutes / 60) % 24, minutes % 60); } const expected = [ ['HISTORY/SOE', 'HISTORY/SOE/soe.xml'], ['HISTORY/CO', 'HISTORY/CO/co.xml'], ['HISTORY/EXV', 'HISTORY/EXV/exv20900102.xml'], ['HISTORY/FIXPT', 'HISTORY/FIXPT/fixpt20900102.xml'] ]; for (let index = 0; index < expected.length; ++index) { const [name, filename] = expected[index]; const entries = await directory(master, name, index + 1); const entry = entries.find(item => item.name === filename); assert(entry, `${filename} missing: ${JSON.stringify(entries)}`); const content = await readFile(master, entry); downloads.set(filename, content); const xml = content.toString('utf8'); assert.match(xml, /<\?xml version="1\.0" encoding="UTF-8"\?>/); assert.match(xml, //); assert.match(xml, /<\/DataFile>/); assert.match(xml, /fileVer="1\.00"/); if (index === 0) { assert.match(xml, //); assert.match(xml, /ioa="1001"/); } else if (index === 1) { assert.match(xml, //); for (const command of ['select', 'oper', 'cancel']) assert(xml.includes(`cmd="${command}"`)); } else if (index === 2) { assert.equal((xml.match(/ max="/g) || []).length, 8); assert.equal((xml.match(/ min="/g) || []).length, 8); } else { assert.match(xml, /sectNum="96"/); assert.match(xml, /interval="15min"/); assert.equal((xml.match(/