/* 主示例标准参数、远程定值和TEMP持久化的真实进程/TCP回归;独立核对存储格式和内容。 * 用法:node test/parameter_config_loopback_test.cjs <.build内的示例exe> * 所有配置及故障注入文件都在exe旁新建的独占临时目录内,结束时只清理该目录。 * 不传--config的旧回环仍由slave_example_loopback_test.cjs覆盖;这里额外检查邻近配置不会被自动加载。 */ 'use strict'; const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const net = require('node:net'); const { spawn } = require('node:child_process'); const { once } = require('node:events'); const { setTimeout: delay } = require('node:timers/promises'); const { Master, parameterRequest } = require('./slave_example_loopback_test.cjs'); const executable = path.resolve(process.argv[2]); const buildRoot = path.resolve(__dirname, '..', '.build'); const inside = (parent, target) => { const relative = path.relative(parent, target); return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative); }; assert(inside(buildRoot, executable), 'The test executable must be inside IEC60870-Slave/.build'); const directory = fs.mkdtempSync(path.join(path.dirname(executable), 'parameter-config-')); const configuration = path.join(directory, 'parameters.ini'); const processes = [], sockets = []; const listeners = new Map(); /* 进程通过--run-ms正常退出,测试不会把Windows强制终止当成退出保存成功。 * kill只用于失败收尾/总期限保护;close事件保证stdout/stderr已全部交付再核对诊断。 */ function launch(config, runMs = 1800, options = []) { const args = ['--port', '0', '--ca', '7', '--events', '0', '--background-ms', '0', '--run-ms', String(runMs)]; if (config !== null) args.push('--config', config); args.push(...options); const child = spawn(executable, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); const process = { child, output: '', errors: '', finished: false, parameters: !options.includes('--no-parameter') }; child.stdout.on('data', data => { process.output += data; }); child.stderr.on('data', data => { process.errors += data; }); process.exit = once(child, 'close').then(([code, signal]) => { process.finished = true; return { code, signal }; }); process.exit.catch(() => {}); // 由finish或总收尾统一报告,避免先于await的拒绝成为未处理异常。 process.timer = setTimeout(() => child.kill(), runMs + 5000); processes.push(process); return process; } async function waitFor(predicate, description, timeout = 2200) { const deadline = Date.now() + timeout; while (!predicate()) { assert(Date.now() < deadline, description); await delay(20); } } async function listening(process) { await waitFor(() => process.finished || /LISTEN 127\.0\.0\.1:(\d+) CA=7/.test(process.output), `Missing listener: ${process.output}\n${process.errors}`); const match = process.output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/); assert(match, `${process.output}\n${process.errors}`); const port = Number(match[1]); listeners.set(port, process.parameters); return port; } async function connect(port, coi = 0) { const socket = net.connect({ host: '127.0.0.1', port }); sockets.push(socket); const master = new Master(socket); master.asynchronous = true; assert(listeners.has(port), 'Missing launch metadata for parameter interrogation'); master.parameters = listeners.get(port); master.startupComplete = false; await once(socket, 'connect'); await master.control(7, 0x0b); assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, coi]); return master; } async function until(master, predicate) { for (let i = 0; i < 256; ++i) { const asdu = await master.readASDU(); if (predicate(asdu)) return asdu; // 参数上下限改变可能即时产生合法品质变位,不能把它误认成装载确认。 assert(asdu[0] === 11 && asdu[2] === 3, `Unexpected response: ${asdu.toString('hex')}`); } throw new Error('Missing expected response'); } async function writeParameter(master, type, ioa, value, kpa, cause = 6, expectedCause = 7, running = value) { const request = parameterRequest(type, ioa, value, kpa, cause); const expected = Buffer.from(request); expected[2] = expectedCause; if (type === 112) expected.writeFloatLE(running, 9); else expected.writeInt16LE(running, 9); await master.send(request); assert.deepEqual(await until(master, a => a[0] === type), expected); } async function interrogate(master) { const request = Buffer.from([100, 1, 6, 0x72, 7, 0, 0, 0, 0, 20]); await master.send(request); const confirmation = Buffer.from(request); confirmation[2] = 7; assert.deepEqual(await until(master, a => a[0] === 100), confirmation); const values = new Map(); let ordinary = 0; for (let i = 0; i < 256; ++i) { const asdu = await master.readASDU(); if (asdu[2] === 3) { assert.equal(asdu[0], 11); continue; } if (asdu[0] === 100) { const termination = Buffer.from(request); termination[2] = 10; assert.deepEqual(asdu, termination); assert.equal(values.size, master.parameters ? 32 : 0); assert.equal(ordinary, 24); // 只有真实QOI20结束帧已收到,文件IDLE帧才具备启动放行条件。 master.startupComplete = true; return values; } assert.equal(asdu[2], 20); assert.equal(asdu[3], 0x72); assert.equal(asdu.readUInt16LE(4), 7); if (asdu[0] >= 110 && asdu[0] <= 112) { assert.equal(asdu[1], 1); const ioa = asdu.readUIntLE(6, 3); assert(!values.has(ioa)); values.set(ioa, asdu[0] === 112 ? asdu.readFloatLE(9) : asdu.readInt16LE(9)); } else { assert([1, 3, 11].includes(asdu[0])); ordinary += asdu[1] & 127; } } throw new Error('Missing interrogation termination'); } async function measurement(master) { await master.send([102, 1, 5, 0x73, 7, 0, 0x01, 0x40, 0]); return until(master, a => a[0] === 11 && a[2] === 5 && a[3] === 0x73); } async function finish(process, code = 0, allowErrors = false) { const actual = await process.exit; clearTimeout(process.timer); assert.equal(actual.signal, null, `Process was killed: ${process.output}\n${process.errors}`); assert.equal(actual.code, code, `${process.output}\n${process.errors}`); if (!allowErrors) assert.equal(process.errors, ''); } /* 独立解析子站保存的INI,再按主示例公开点表验证身份;不调用被测C解析器。 * Type110保持线上原始整数;Type112先转换为binary32再比较,避免9位十进制回写的 * Number值与实际float值在最后几位存在正常差异。未知/重复字段在测试端也不会被静默覆盖。 */ function parseIni(bytes) { const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes), sections = new Map(); let section; for (const original of text.split(/\r?\n/)) { const line = original.split(/[;#]/, 1)[0].trim(); if (!line) continue; const heading = line.match(/^\[([a-z_0-9]+)\]$/); if (heading) { assert(!sections.has(heading[1]), `Duplicate section ${heading[1]}`); section = new Map(); sections.set(heading[1], section); continue; } const field = line.match(/^([a-z_0-9]+)\s*=\s*(\S+)$/); assert(field && section, `Invalid INI line: ${line}`); assert(!section.has(field[1]), `Duplicate key ${field[1]}`); section.set(field[1], field[2]); } return sections; } function decodeFile(file) { const bytes = fs.readFileSync(file), sections = parseIni(bytes); const config = sections.get('config'); assert(config); assert.deepEqual([...config.keys()].sort(), ['common_address', 'point_count', 'version']); assert.equal(config.get('version'), '2'); assert.equal(config.get('common_address'), '7'); assert.equal(config.get('point_count'), '32'); assert.equal(sections.size, 40); const values = new Map(); for (let group = 0; group < 4; ++group) for (let i = 0; i < 8; ++i) { const ioa = 0x8601 + group * 0x10 + i, type = group === 3 ? 112 : group === 0 && i >= 4 ? 110 : 111; const row = sections.get(`parameter_${ioa}`); assert(row, `Missing IOA ${ioa}`); assert.deepEqual([...row.keys()].sort(), ['kpa', 'type', 'value']); assert.equal(Number(row.get('type')), type); assert.equal(Number(row.get('kpa')), [1, 3, 4, 2][group]); const number = Number(row.get('value')); assert(Number.isFinite(number)); if (type !== 112) assert(Number.isInteger(number) && number >= -32768 && number <= 32767); values.set(ioa, type === 112 ? Math.fround(number) : number); } const remoteSection = sections.get('remote'); assert(remoteSection); assert.deepEqual([...remoteSection.keys()].sort(), ['current_area', 'deadband']); const remote = { current_area: Number(remoteSection.get('current_area')), deadband: Number(remoteSection.get('deadband')), areas: [] }; assert(Number.isInteger(remote.current_area) && remote.current_area >= 0 && remote.current_area < 5); assert(Number.isFinite(remote.deadband) && remote.deadband >= 0 && remote.deadband <= 10); for (let area = 0; area < 5; ++area) { const row = sections.get(`area_${area}`); assert(row); assert.deepEqual([...row.keys()].sort(), ['reset_seconds', 'x_time']); const reset_seconds = Number(row.get('reset_seconds')), x_time = Number(row.get('x_time')); assert(Number.isInteger(reset_seconds) && reset_seconds >= 0 && reset_seconds <= 3600); assert(Number.isFinite(x_time) && x_time >= 0 && x_time <= 100); remote.areas.push({ reset_seconds, x_time }); } const row = sections.get('temp'); assert(row); assert(['0', '1'].includes(row.get('present'))); let temp = { present: false }; if (row.get('present') === '0') assert.deepEqual([...row.keys()], ['present']); else { const size = Number(row.get('size')), name = row.get('name'); assert(Number.isInteger(size) && size >= 0 && size <= 4096); assert.match(name, /^TEMP\/[A-Za-z0-9_-][A-Za-z0-9_.-]*$/); assert.match(row.get('time'), /^[0-9a-f]{14}$/i); assert.match(row.get('crc32'), /^[0-9a-f]{8}$/i); const chunks = []; for (let index = 0; index < Math.ceil(size / 128); ++index) { const hex = row.get(`data_${index}`); assert.match(hex, /^[0-9a-f]+$/i); assert.equal(hex.length, Math.min(128, size - index * 128) * 2); chunks.push(Buffer.from(hex, 'hex')); } assert.equal(row.size, 5 + chunks.length); temp = { present: true, name, size, time: Buffer.from(row.get('time'), 'hex'), data: Buffer.concat(chunks) }; const legacy = legacyTempSnapshot(name, temp.data, temp.time); assert.equal(parseInt(row.get('crc32'), 16), legacy.readUInt32LE(legacy.length - 4)); } return { bytes, values, remote, temp }; } function defaultExtensions() { const lines = ['[remote]', 'current_area=0', 'deadband=0', '']; for (let area = 0; area < 5; ++area) lines.push(`[area_${area}]`, `reset_seconds=${30 * (area + 1)}`, `x_time=${area + 1}`, ''); lines.push('[temp]', 'present=0'); return lines.join('\n'); } /* 以独立点表构造人工可编辑的输入,格式故障注入只改这一份标准文本。 * 这里没有CRC或被测序列化器,文本编辑后的正确值须直接通过真实子站加载。 */ function fixtureText(values) { const lines = ['[config]', 'version=1', 'common_address=7', 'point_count=32', '']; for (let group = 0; group < 4; ++group) for (let i = 0; i < 8; ++i) { const ioa = 0x8601 + group * 0x10 + i, type = group === 3 ? 112 : group === 0 && i >= 4 ? 110 : 111; lines.push(`[parameter_${ioa}]`, `type=${type}`, `kpa=${[1, 3, 4, 2][group]}`, `value=${values.get(ioa)}`, ''); } return lines.join('\n'); } function replaceField(text, section, key, value) { const pattern = new RegExp(`(\\[${section}\\]\\n[^[]*?^${key}=)[^\\n]*`, 'm'); assert(pattern.test(text), `Missing fixture field ${section}.${key}`); return text.replace(pattern, (_, prefix) => prefix + value); } async function createAndPersist() { const process = launch(configuration, 2600); const master = await connect(await listening(process)); assert.match(process.output, /^CONFIG CREATED$/m); const initial = decodeFile(configuration).values; assert.equal(initial.get(0x8601), 200); assert.equal(initial.get(0x8605), 655); assert.equal(initial.get(0x8611), -10000); assert.equal(initial.get(0x8621), 10000); const defaults = decodeFile(configuration); assert.deepEqual(defaults.temp, { present: false }); assert.deepEqual(defaults.remote, { current_area: 0, deadband: 0, areas: Array.from({ length: 5 }, (_, area) => ({ reset_seconds: 30 * (area + 1), x_time: area + 1 })) }); assert(!fs.existsSync(`${configuration}.remote.ini`) && !fs.existsSync(`${configuration}.temp.bin`)); assert.match(fs.readFileSync(configuration, 'utf8'), /^[;#]/m, 'Generated INI needs editing guidance'); await writeParameter(master, 111, 0x8601, 350, 1); await writeParameter(master, 110, 0x8605, 16384, 1); await writeParameter(master, 112, 0x8631, 1.5, 2); await writeParameter(master, 111, 0x8611, 2400, 3); await writeParameter(master, 111, 0x8621, 9000, 4); await waitFor(() => { if (!/^CONFIG SAVED$/m.test(process.output)) return false; const stored = decodeFile(configuration).values; return [[0x8601, 350], [0x8605, 16384], [0x8631, 1.5], [0x8611, 2400], [0x8621, 9000]] .every(([ioa, value]) => stored.get(ioa) === value); }, 'Configuration was not saved'); const saved = decodeFile(configuration); for (const [ioa, value] of [[0x8601, 350], [0x8605, 16384], [0x8631, 1.5], [0x8611, 2400], [0x8621, 9000]]) { assert.equal(saved.values.get(ioa), value); } // TEST、否定和同值请求不会改运行值,也不应重新替换配置文件;mtime检查发现无意义重复保存。 const modified = fs.statSync(configuration).mtimeMs; await writeParameter(master, 111, 0x8601, -1, 1, 6, 0x47, 350); await writeParameter(master, 111, 0x8601, 10, 1, 0x86, 0x87, 350); await writeParameter(master, 112, 0x8631, 61, 2, 6, 0x47, 1.5); await writeParameter(master, 111, 0x8601, 350, 1); await master.close(); await finish(process); assert.deepEqual(fs.readFileSync(configuration), saved.bytes); assert.equal(fs.statSync(configuration).mtimeMs, modified); } async function reloadAndReset() { const process = launch(configuration, 2200); const port = await listening(process); let master = await connect(port); assert.match(process.output, /^CONFIG LOADED$/m); const loaded = await interrogate(master); for (const [ioa, value] of [[0x8601, 350], [0x8605, 16384], [0x8631, 1.5], [0x8611, 2400], [0x8621, 9000]]) { assert.equal(loaded.get(ioa), value); } const measured = await measurement(master); assert.equal(measured.readInt16LE(9), 2300); assert.equal(measured[11], 1); // 已加载下限2400立即参与测量品质,证明恢复的不只是总召显示值。 // 写入后立即QRP1;即便500ms合并保存尚未到期,协议重建也必须保留最新内存参数。 await writeParameter(master, 111, 0x8601, 360, 1); const closed = once(master.socket, 'close'); await master.send([105, 1, 6, 0x74, 7, 0, 0, 0, 0, 1]); assert.deepEqual([...(await until(master, a => a[0] === 105))], [105, 1, 7, 0x74, 7, 0, 0, 0, 0, 1]); await closed; await delay(60); master = await connect(port, 2); assert.equal((await interrogate(master)).get(0x8601), 360); await master.close(); await finish(process); assert.equal(decodeFile(configuration).values.get(0x8601), 360); } async function manualEditing() { const file = path.join(directory, 'manual.ini'); const expected = decodeFile(configuration).values; expected.set(0x8601, 275); expected.set(0x8605, 12345); expected.set(0x8631, Math.fround(1.23456789)); expected.set(0x8632, Math.fround(1.40129846e-45)); expected.set(0x8633, -0); expected.set(0x8634, 60); // 人工文件采用逆序节/键、config置末、BOM、CRLF、中文注释以及无末尾换行。 // 首注释恰511字节,证明合法边界不会与下面512字节的拒绝用例混淆。 const lines = [';' + 'x'.repeat(510), '; \u624b\u5de5\u914d\u7f6e', '']; for (let group = 3; group >= 0; --group) for (let i = 7; i >= 0; --i) { const ioa = 0x8601 + group * 0x10 + i, type = group === 3 ? 112 : group === 0 && i >= 4 ? 110 : 111; const value = ioa === 0x8631 ? '1.23456789e0' : ioa === 0x8632 ? '1.40129846e-45' : ioa === 0x8633 ? '-0.0' : ioa === 0x8634 ? '+6.0E1' : String(expected.get(ioa)); lines.push(` [parameter_${ioa}] ; row`, ` value = ${value} # \u624b\u5de5\u503c`, ` kpa = ${[1, 3, 4, 2][group]}`, ` type = ${type}`, ''); } lines.push(defaultExtensions(), '', '[config] # metadata last', 'point_count = 32', 'common_address = 7', 'version = 2'); const manual = Buffer.from('\ufeff' + lines.join('\r\n'), 'utf8'); fs.writeFileSync(file, manual); const process = launch(file, 1800); const master = await connect(await listening(process)); assert.match(process.output, /^CONFIG LOADED$/m); assert.deepEqual(await interrogate(master), expected); assert.deepEqual(fs.readFileSync(file), manual, 'Loading alone must not rewrite manually formatted INI'); // 改一个整数参数触发整份保存;另外的float必须完整往返,尤其是subnormal和负零。 await writeParameter(master, 111, 0x8601, 276, 1); expected.set(0x8601, 276); await waitFor(() => /^CONFIG SAVED$/m.test(process.output), 'Edited INI was not saved'); assert.deepEqual(decodeFile(file).values, expected); await master.close(); await finish(process); const reloaded = launch(file, 700); const next = await connect(await listening(reloaded)); assert.deepEqual(await interrogate(next), expected); await next.close(); await finish(reloaded); } async function optionalAndInvalid() { const memory = launch(null, 500); const master = await connect(await listening(memory)); const values = await interrogate(master); assert.equal(values.get(0x8601), 200); assert.equal(values.get(0x8605), 655); assert.equal(values.get(0x8631), 0); assert.equal(values.get(0x8611), -10000); await master.close(); await finish(memory); assert(!/^CONFIG /m.test(memory.output)); const good = fs.readFileSync(configuration); const conflict = launch(configuration, 100, ['--no-parameter']); await finish(conflict, 1, true); assert(!/LISTEN /.test(conflict.output)); assert.deepEqual(fs.readFileSync(configuration), good); const missing = launch(path.join(directory, 'missing-parent', 'params.ini'), 100); await finish(missing, 1, true); assert(!/LISTEN /.test(missing.output)); // 每例使用独立路径;失败后逐字节比较,禁止“校验失败就用默认值覆盖坏文件”。 // 输入从独立模板构造,覆盖格式、必填/唯一性、身份和值域;旧BIN也不可悄悄覆盖成INI。 const fixture = fixtureText(decodeFile(configuration).values); const cases = [ ['legacy-bin', () => Buffer.concat([Buffer.from('IECPCFG1'), Buffer.alloc(396)])], ['empty', () => ''], ['embedded-nul', s => s + '\0'], ['version', s => replaceField(s, 'config', 'version', '3')], ['count', s => replaceField(s, 'config', 'point_count', '31')], ['ca', s => replaceField(s, 'config', 'common_address', '8')], ['signed-metadata', s => replaceField(s, 'config', 'common_address', '+7')], ['metadata-overflow', s => replaceField(s, 'config', 'common_address', '18446744073709551616')], ['missing-config', s => s.replace(/\[config\][^[]*/, '')], ['missing-version', s => s.replace('version=1\n', '')], ['missing-section', s => s.replace(/\[parameter_34305\][^[]*/, '')], ['missing-value', s => s.replace('value=360\n', '')], ['duplicate-config', s => s + '\n[config]\nversion=1\ncommon_address=7\npoint_count=32\n'], ['duplicate-section', s => s + '\n[parameter_34305]\ntype=111\nkpa=1\nvalue=360\n'], ['duplicate-key', s => s.replace('version=1\n', 'version=1\nversion=1\n')], ['duplicate-value', s => s.replace('value=360\n', 'value=360\nvalue=360\n')], ['unknown-section', s => s + '\n[other]\nvalue=1\n'], ['unknown-key', s => s.replace('version=1\n', 'version=1\nspelling_error=1\n')], ['misplaced-key', s => 'version=1\n' + s], ['case-sensitive', s => s.replace('[config]', '[Config]')], ['section-trailing', s => s.replace('[config]', '[config]garbage')], ['section-bracket', s => s.replace('[config]', '[config')], ['ioa', s => s.replace('[parameter_34305]', '[parameter_5999]')], ['legacy-ioa', s => s.replace('[parameter_34305]', '[parameter_5001]')], ['type', s => replaceField(s, 'parameter_34305', 'type', '112')], ['kind', s => replaceField(s, 'parameter_34305', 'kpa', '3')], ['int16-range', s => replaceField(s, 'parameter_34305', 'value', '65535')], ['integer-fraction', s => replaceField(s, 'parameter_34305', 'value', '200.5')], ['integer-suffix', s => replaceField(s, 'parameter_34305', 'value', '200oops')], ['negative-threshold', s => replaceField(s, 'parameter_34305', 'value', '-1')], ['reversed-range', s => replaceField(s, 'parameter_34321', 'value', '9500')], ['smoothing-range', s => replaceField(s, 'parameter_34353', 'value', '61')], ['nan', s => replaceField(s, 'parameter_34353', 'value', 'NaN')], ['infinity', s => replaceField(s, 'parameter_34353', 'value', 'Inf')], ['float-overflow', s => replaceField(s, 'parameter_34353', 'value', '1e100')], ['float-underflow', s => replaceField(s, 'parameter_34353', 'value', '1e-100')], ['float-comma', s => replaceField(s, 'parameter_34353', 'value', '1,5')], ['float-hex', s => replaceField(s, 'parameter_34353', 'value', '0x1p0')], ['float-suffix', s => replaceField(s, 'parameter_34353', 'value', '1.5seconds')], ['long-line', s => ';' + 'x'.repeat(511) + '\n' + s], ['oversize-file', s => ';x\n'.repeat(22000) + s] ]; for (const [name, mutate] of cases) { const file = path.join(directory, `${name}.ini`); const bad = Buffer.from(mutate(fixture)); assert(!bad.equals(Buffer.from(fixture)), `${name}: mutation did not change fixture`); fs.writeFileSync(file, bad); const process = launch(file, 100); await finish(process, 1, true); assert(!/LISTEN /.test(process.output), `${name}: invalid configuration started listening`); assert.match(process.errors, /CONFIG /, name); assert.deepEqual(fs.readFileSync(file), bad, `${name}: invalid configuration was overwritten`); } } async function saveFailureAndRetry() { const file = path.join(directory, 'readonly.ini'); const good = fs.readFileSync(configuration); fs.writeFileSync(file, good); // Windows chmod去除写位设置只读属性:读仍成功,但替换只读目标失败。 // 只修改本测试创建的文件属性;恢复后观察后台重试,无需重新发送参数命令。 fs.chmodSync(file, 0o444); try { const process = launch(file, 7200); const master = await connect(await listening(process)); await writeParameter(master, 111, 0x8601, 550, 1); await waitFor(() => /CONFIG save failed:/.test(process.errors), 'Missing save failure diagnostic'); assert.deepEqual(fs.readFileSync(file), good); assert.equal((await interrogate(master)).get(0x8601), 550); fs.chmodSync(file, 0o666); await waitFor(() => /^CONFIG SAVED$/m.test(process.output), 'Save retry did not recover', 6200); assert.equal(decodeFile(file).values.get(0x8601), 550); assert.equal((process.errors.match(/CONFIG save failed:/g) || []).length, 1); await master.close(); await finish(process, 0, true); assert(!/CONFIG unsaved parameters at exit/.test(process.errors)); // 正常运行结束前仍不能保存,退出码必须失败;旧文件仍是上一次成功保存的550。 const retained = fs.readFileSync(file); fs.chmodSync(file, 0o444); const unsaved = launch(file, 1200); const next = await connect(await listening(unsaved)); await writeParameter(next, 111, 0x8601, 560, 1); await next.close(); await finish(unsaved, 1, true); assert.match(unsaved.errors, /CONFIG unsaved parameters at exit/); assert.deepEqual(fs.readFileSync(file), retained); } finally { fs.chmodSync(file, 0o666); } } /* 扩展服务使用独立线格式期望;不调用C侧持久化编解码器,也不借用业务实现生成报文。 */ const unsigned16 = value => { const bytes = Buffer.alloc(2); bytes.writeUInt16LE(value); return bytes; }; const unsigned32 = value => { const bytes = Buffer.alloc(4); bytes.writeUInt32LE(value); return bytes; }; const float32 = value => { const bytes = Buffer.alloc(4); bytes.writeFloatLE(value); return bytes; }; const ioAddress = value => Buffer.from([value & 255, (value >> 8) & 255, (value >> 16) & 255]); const remoteHead = (type, count, cause = 6) => Buffer.from([type, count, cause, 0x72, 7, 0]); const remoteElement = (ioa, tag, value) => Buffer.concat([ioAddress(ioa), Buffer.from([tag, value.length]), value]); const remotePreset = (area, elements, test = false) => Buffer.concat([ remoteHead(203, elements.length, test ? 0x86 : 6), unsigned16(area), Buffer.from([0x80]), ...elements]); const remoteEnd = (area, cancel = false, test = false) => Buffer.concat([ remoteHead(203, 0, (cancel ? 8 : 6) | (test ? 0x80 : 0)), unsigned16(area), Buffer.from([0])]); const remoteSwitch = (area, test = false) => Buffer.concat([ remoteHead(200, 1, test ? 0x86 : 6), ioAddress(0), unsigned16(area)]); async function remoteMirror(master, request, cause = 7, cancel = false) { const expected = Buffer.from(request); expected[2] = cause | (request[2] & 0x80); if (cancel) expected[8] = 0x40; await master.send(request); assert.deepEqual(await until(master, a => a[0] === request[0]), expected); } async function remoteValues(master, area, addresses) { await master.send(Buffer.concat([remoteHead(202, addresses.length), unsigned16(area), ...addresses.map(ioAddress)])); const values = []; for (let count = 0; count < 8; ++count) { const frame = await until(master, a => a[0] === 202); assert.equal(frame[2], 7); assert.equal(frame.readUInt16LE(6), area); assert.deepEqual([...frame.subarray(3, 6)], [0x72, 7, 0]); let cursor = 9; for (let index = 0; index < frame[1]; ++index) { const ioa = frame.readUIntLE(cursor, 3), tag = frame[cursor + 3], length = frame[cursor + 4]; assert.equal(ioa, addresses[values.length]); assert.equal(tag, ioa === 0x8221 ? 45 : 38); assert.equal(length, tag === 45 ? 2 : 4); values.push(tag === 45 ? frame.readUInt16LE(cursor + 5) : frame.readFloatLE(cursor + 5)); cursor += 5 + length; } assert.equal(cursor, frame.length); if (frame[8] === 0) { assert.equal(values.length, addresses.length); return values; } assert.equal(frame[8], 1); } throw new Error('Remote parameter read did not terminate'); } async function remoteArea(master, expected) { await master.send(Buffer.concat([remoteHead(201, 1), ioAddress(0)])); assert.deepEqual(await until(master, a => a[0] === 201), Buffer.from([201, 1, 7, 0x72, 7, 0, 0, 0, 0, expected, 0, 0, 0, 4, 0])); } function checkRemoteSnapshot(file) { assert.deepEqual(decodeFile(file).remote, { current_area: 3, deadband: 2.5, areas: Array.from({ length: 5 }, (_, area) => ({ reset_seconds: 40 + area, x_time: 1.25 + area })) }); } const fileHead = (op, cause) => Buffer.from([210, 1, cause, 0x41, 7, 0, 0, 0, 0, 2, op]); const fileName = name => { const bytes = Buffer.from(name, 'ascii'); return Buffer.concat([Buffer.from([bytes.length]), bytes]); }; function crc32(bytes) { let crc = 0xffffffff; for (const byte of bytes) { crc ^= byte; for (let bit = 0; bit < 8; ++bit) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0); } return (crc ^ 0xffffffff) >>> 0; } assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926); function legacyTempSnapshot(name, content, time = Buffer.from([0, 0, 0, 12, 10, 11, 26]), ca = 7) { const header = Buffer.alloc(23); header.write('IEC104TP'); header[8] = 1; header.writeUInt16LE(ca, 9); header[11] = Buffer.byteLength(name); header.writeUInt32LE(content.length, 12); time.copy(header, 16); const bytes = Buffer.concat([header, Buffer.from(name, 'ascii'), content]); return Buffer.concat([bytes, unsigned32(crc32(bytes))]); } async function fileResponse(master, op) { const frame = await until(master, a => a[0] === 210); assert.equal(frame[1], 1); assert.equal(frame[3], 0x41); assert.equal(frame.readUInt16LE(4), 7); assert.equal(frame.readUIntLE(6, 3), 0); assert.equal(frame[9], 2); assert.equal(frame[10], op); return frame; } async function fileWrite(master, name, bytes, result = 0, test = false) { await master.send(Buffer.concat([fileHead(7, test ? 0x86 : 6), fileName(name), unsigned32(17), unsigned32(bytes.length)])); const activation = await fileResponse(master, 8); assert.equal(activation[2], test ? 0x87 : 7); assert.equal(activation[11], 0); let lastOffset = 0; for (let offset = 0; offset < bytes.length; offset += 228) { const data = bytes.subarray(offset, offset + 228); lastOffset = offset; await master.send(Buffer.concat([fileHead(9, test ? 0x85 : 5), unsigned32(17), unsigned32(offset), Buffer.from([offset + data.length < bytes.length ? 1 : 0]), data, Buffer.from([data.reduce((sum, byte) => (sum + byte) & 255, 0)])])); } assert.deepEqual(await fileResponse(master, 10), Buffer.concat([ fileHead(10, (result === 0 ? 7 : 0x47) | (test ? 0x80 : 0)), unsigned32(0), unsigned32(lastOffset), Buffer.from([result])])); } async function fileRead(master, name) { // 重连后的Master重新等待启动;无标准参数时总召只含24个普通点。 if (!master.startupComplete) await interrogate(master); await master.send(Buffer.concat([fileHead(3, 6), fileName(name)])); const activation = await fileResponse(master, 4); assert.equal(activation[2], 7); assert.equal(activation[11], 0); const idOffset = 13 + activation[12]; assert.equal(activation.subarray(13, idOffset).toString('ascii'), name); assert.equal(activation.readUInt32LE(idOffset), 0); const size = activation.readUInt32LE(idOffset + 4), chunks = []; let offset = 0; for (let count = 0; count < 24; ++count) { const frame = await fileResponse(master, 5), data = frame.subarray(20, -1); assert.equal(frame[2], 5); assert.equal(frame.readUInt32LE(11), 0); assert.equal(frame.readUInt32LE(15), offset); assert.equal(frame.at(-1), data.reduce((sum, byte) => (sum + byte) & 255, 0)); chunks.push(data); offset += data.length; if (frame[19] === 0) { assert.equal(offset, size); return Buffer.concat(chunks); } assert.equal(frame[19], 1); } throw new Error('Persistent file read did not terminate'); } async function tempDirectory(master) { if (!master.startupComplete) await interrogate(master); await master.send(Buffer.concat([fileHead(1, 5), unsigned32(0), fileName('TEMP'), Buffer.alloc(15)])); const frame = await fileResponse(master, 2); assert.equal(frame[2], 5); assert.equal(frame[11], 0); assert.equal(frame[16], 0); return frame; // 包含名称、长度和CP56,重启后必须逐字节保持。 } async function remotePersistence() { const config = path.join(directory, 'remote.ini'); const options = ['--no-parameter', '--remote-parameter']; const process = launch(config, 3800, options), port = await listening(process); let master = await connect(port); for (let area = 0; area < 5; ++area) { await remoteMirror(master, remotePreset(area, [remoteElement(0x8221, 45, unsigned16(40 + area)), remoteElement(0x8224, 38, float32(1.25 + area))])); await remoteMirror(master, remoteEnd(area)); } await remoteMirror(master, remotePreset(0, [remoteElement(0x8020, 38, float32(2.5))])); await remoteMirror(master, remoteEnd(0)); await remoteMirror(master, remoteSwitch(3)); const saved = fs.readFileSync(config), modified = fs.statSync(config).mtimeMs; checkRemoteSnapshot(config); await remoteMirror(master, remotePreset(1, [remoteElement(0x8221, 45, unsigned16(99))])); assert.deepEqual(fs.readFileSync(config), saved); await remoteMirror(master, remoteEnd(1, true), 9, true); await remoteMirror(master, remotePreset(1, [remoteElement(0x8221, 45, unsigned16(98))], true)); await remoteMirror(master, remoteEnd(1, false, true)); await remoteMirror(master, remoteSwitch(4, true)); assert.deepEqual(fs.readFileSync(config), saved); assert.equal(fs.statSync(config).mtimeMs, modified); const closed = once(master.socket, 'close'); await remoteMirror(master, Buffer.from([105, 1, 6, 0x72, 7, 0, 0, 0, 0, 1])); await closed; await delay(80); master = await connect(port, 2); await remoteArea(master, 3); assert.deepEqual(await remoteValues(master, 0, [0x8020]), [2.5]); assert.deepEqual(await remoteValues(master, 1, [0x8221, 0x8224]), [41, 2.25]); await master.close(); await finish(process); assert(!fs.existsSync(`${config}.remote.ini`) && !fs.existsSync(`${config}.temp.bin`)); const restarted = launch(config, 1800, options), next = await connect(await listening(restarted)); await remoteArea(next, 3); for (let area = 0; area < 5; ++area) { assert.deepEqual(await remoteValues(next, area, [0x8221, 0x8224]), [40 + area, 1.25 + area]); } assert.deepEqual(await remoteValues(next, 0, [0x8020]), [2.5]); await next.close(); await finish(restarted); assert.deepEqual(fs.readFileSync(config), saved); fs.chmodSync(config, 0o444); try { const failed = launch(config, 1800, options), rejected = await connect(await listening(failed)); await remoteMirror(rejected, remoteSwitch(4), 0x47); await remoteArea(rejected, 3); await remoteMirror(rejected, remotePreset(1, [remoteElement(0x8221, 45, unsigned16(123))])); await remoteMirror(rejected, remoteEnd(1), 0x47); assert.deepEqual(await remoteValues(rejected, 1, [0x8221, 0x8224]), [41, 2.25]); assert.deepEqual(fs.readFileSync(config), saved); await remoteMirror(rejected, remoteEnd(1, true), 9, true); await rejected.close(); await finish(failed, 0, true); } finally { fs.chmodSync(config, 0o666); } } async function filePersistence() { const config = path.join(directory, 'files.ini'); const options = ['--no-parameter', '--file-service'], name = 'TEMP/persist.bin'; const content = Buffer.alloc(4096); for (let i = 0; i < content.length; ++i) content[i] = (i * 31 + 7) & 255; const process = launch(config, 2200, options), master = await connect(await listening(process)); await fileWrite(master, name, content); assert.deepEqual(await fileRead(master, name), content); const listing = await tempDirectory(master), saved = fs.readFileSync(config), modified = fs.statSync(config).mtimeMs; assert.equal(decodeFile(config).temp.name, name); assert.deepEqual(decodeFile(config).temp.data, content); await fileWrite(master, 'TEMP/test.bin', Buffer.from('test-only'), 0, true); assert.deepEqual(fs.readFileSync(config), saved); assert.equal(fs.statSync(config).mtimeMs, modified); await master.close(); await finish(process); assert(!fs.existsSync(`${config}.remote.ini`) && !fs.existsSync(`${config}.temp.bin`)); const restarted = launch(config, 1800, options), next = await connect(await listening(restarted)); assert.deepEqual(await tempDirectory(next), listing); assert.deepEqual(await fileRead(next, name), content); await next.close(); await finish(restarted); fs.chmodSync(config, 0o444); try { const failed = launch(config, 1800, options), rejected = await connect(await listening(failed)); await fileWrite(rejected, 'TEMP/replacement.bin', Buffer.from('must not publish'), 1); assert.deepEqual(fs.readFileSync(config), saved); assert.deepEqual(await tempDirectory(rejected), listing); assert.deepEqual(await fileRead(rejected, name), content); await rejected.close(); await finish(failed, 0, true); } finally { fs.chmodSync(config, 0o666); } return { config, options, saved }; } async function unifiedValidation(state) { const baseline = decodeFile(state.config); const wrongCa = launch(state.config, 100, [...state.options, '--ca', '8']); await finish(wrongCa, 1, true); assert(!wrongCa.output.includes('LISTEN ')); assert.deepEqual(fs.readFileSync(state.config), state.saved); const text = state.saved.toString('utf8'); const metadata = (key, value) => { let invalid = replaceField(text, 'temp', key, value); const row = parseIni(Buffer.from(invalid)).get('temp'), chunks = []; for (let index = 0; row.has(`data_${index}`); ++index) chunks.push(Buffer.from(row.get(`data_${index}`), 'hex')); const snapshot = legacyTempSnapshot(row.get('name'), Buffer.concat(chunks), Buffer.from(row.get('time'), 'hex')); snapshot.writeUInt32LE(Number(row.get('size')), 12); return replaceField(invalid, 'temp', 'crc32', crc32(snapshot.subarray(0, -4)).toString(16).padStart(8, '0')); }; const genTime = Buffer.from(baseline.temp.time), weekdayTime = Buffer.from(baseline.temp.time); genTime[2] ^= 0x40; weekdayTime[4] = (weekdayTime[4] & 0x1f) | ((((weekdayTime[4] >> 5) % 7) + 1) << 5); const alternateTimes = [genTime.toString('hex'), weekdayTime.toString('hex')]; const damages = [Buffer.alloc(0), state.saved.subarray(0, Math.floor(state.saved.length / 2)), Buffer.concat([state.saved, Buffer.from([0xff])]), Buffer.from(replaceField(text, 'remote', 'current_area', '5')), Buffer.from(replaceField(text, 'area_0', 'reset_seconds', '3601')), Buffer.from(replaceField(text, 'remote', 'deadband', 'NaN')), Buffer.from(text.replace(/^current_area=.*\n/m, '')), Buffer.from(text.replace(/^current_area=.*$/m, 'current_area=0\ncurrent_area=0')), Buffer.from(`${text}\n[area_0]\nreset_seconds=40\nx_time=1.25\n`), Buffer.from(text.replace(/\[temp\][^[]*/, '')), Buffer.from(replaceField(text, 'temp', 'present', '0')), Buffer.from(replaceField(text, 'temp', 'crc32', '00000000')), Buffer.from(text.replace(/^(data_0=)./m, '$1g')), Buffer.from(text.replace(/^data_0=.*\n/m, '')), Buffer.from(text.replace(/^data_0=(.)/m, 'data_0=$1$1')), Buffer.from(metadata('name', '../bad.bin')), Buffer.from(metadata('size', '4097')), Buffer.from(metadata('time', '00000000000000')), ...alternateTimes.map(time => Buffer.from(replaceField(text, 'temp', 'time', time)))]; for (const damaged of damages) { assert(!damaged.equals(state.saved), 'Corruption fixture must change the saved bytes'); fs.writeFileSync(state.config, damaged); // 仅启用标准参数,仍必须验证被禁用的remote/temp节,不能丢弃坏节后重建默认值。 const failed = launch(state.config, 100); await finish(failed, 1, true); assert(!failed.output.includes('LISTEN ')); assert.deepEqual(fs.readFileSync(state.config), damaged); } const invalidStandard = Buffer.from(replaceField(text, 'parameter_34305', 'value', '-1')); fs.writeFileSync(state.config, invalidStandard); const disabledStandard = launch(state.config, 100, ['--no-parameter', '--file-service']); await finish(disabledStandard, 1, true); assert(!disabledStandard.output.includes('LISTEN ')); assert.deepEqual(fs.readFileSync(state.config), invalidStandard); // GEN和星期可被公共时间解码规范化,但CRC必须先覆盖原始七字节; // 同样的合法时间变体补齐CRC后须能加载,下一次保存再规范化并更新CRC。 for (const time of alternateTimes) { const valid = Buffer.from(metadata('time', time)); fs.writeFileSync(state.config, valid); const process = launch(state.config, 1500, ['--file-service']); const master = await connect(await listening(process)); assert.deepEqual(await fileRead(master, baseline.temp.name), baseline.temp.data); assert.deepEqual(fs.readFileSync(state.config), valid, 'Loading alone must not rewrite valid CP56 variants'); await writeParameter(master, 111, 0x8601, 777, 1); await waitFor(() => decodeFile(state.config).values.get(0x8601) === 777, 'CP56 variant save did not complete'); const normalized = decodeFile(state.config); const expectedTime = Buffer.from(time, 'hex'); expectedTime[2] &= ~0x40; // 星期0表示未携带;输入携带星期时,保存按公历日期重算,不能与原始0星期逐字节比较。 if (expectedTime[4] >> 5) { const weekday = new Date(Date.UTC(2000 + expectedTime[6], expectedTime[5] - 1, expectedTime[4] & 31)).getUTCDay(); expectedTime[4] = (expectedTime[4] & 31) | ((weekday || 7) << 5); } assert.deepEqual(normalized.temp.time, expectedTime); assert.deepEqual(normalized.temp.data, baseline.temp.data); await master.close(); await finish(process); } fs.writeFileSync(state.config, state.saved); } async function combinedPersistence(file) { const config = path.join(directory, 'combined.ini'); fs.copyFileSync(file.config, config); const options = ['--remote-parameter', '--file-service', '--software-upgrade']; const process = launch(config, 4500, options), port = await listening(process); let master = await connect(port); const before = decodeFile(config); await writeParameter(master, 111, 0x8601, 371, 1); await waitFor(() => decodeFile(config).values.get(0x8601) === 371, 'Standard change was not saved'); assert.deepEqual(decodeFile(config).remote, before.remote); assert.deepEqual(decodeFile(config).temp, before.temp); for (let area = 0; area < 5; ++area) { await remoteMirror(master, remotePreset(area, [remoteElement(0x8221, 45, unsigned16(40 + area)), remoteElement(0x8224, 38, float32(1.25 + area))])); await remoteMirror(master, remoteEnd(area)); } await remoteMirror(master, remotePreset(0, [remoteElement(0x8020, 38, float32(2.5))])); await remoteMirror(master, remoteEnd(0)); await remoteMirror(master, remoteSwitch(3)); checkRemoteSnapshot(config); assert.equal(decodeFile(config).values.get(0x8601), 371); assert.deepEqual(decodeFile(config).temp, before.temp); const remoteSaved = decodeFile(config).remote; const replacement = Buffer.from('shared file transaction'); await fileWrite(master, 'TEMP/persist.bin', replacement); assert.equal(decodeFile(config).values.get(0x8601), 371); assert.deepEqual(decodeFile(config).remote, remoteSaved); assert.deepEqual(decodeFile(config).temp.data, replacement); // 尚未到标准参数500ms合并保存期限,远程提交也必须带上最新标准运行值。 await writeParameter(master, 111, 0x8601, 372, 1); await remoteMirror(master, remoteSwitch(4)); assert.equal(decodeFile(config).values.get(0x8601), 372); await remoteMirror(master, remoteSwitch(3)); let modified = fs.statSync(config).mtimeMs; await delay(650); assert.equal(fs.statSync(config).mtimeMs, modified, 'Remote commit must clear the included standard dirty state'); await writeParameter(master, 111, 0x8601, 373, 1); await fileWrite(master, 'TEMP/persist.bin', replacement); assert.equal(decodeFile(config).values.get(0x8601), 373); modified = fs.statSync(config).mtimeMs; await delay(650); assert.equal(fs.statSync(config).mtimeMs, modified, 'TEMP commit must clear the included standard dirty state'); const saved = fs.readFileSync(config); const original = await fileRead(master, 'TEMP/persist.bin'); const command = operation => Buffer.from([211, 0, 6, 0x62, 7, 0, 0x56, 0x34, 0x12, operation === 'start' ? 0x95 : 0x15]); await remoteMirror(master, command('start')); const payload = Buffer.from('persistent services survive protocol rebuild'); await fileWrite(master, 'upgrade.bin', Buffer.concat([ Buffer.from('I104'), unsigned32(2), unsigned32(payload.length), unsigned32(crc32(payload)), payload])); const closed = once(master.socket, 'close'); await remoteMirror(master, command('end')); await closed; await delay(80); master = await connect(port, 2); await remoteArea(master, 3); assert.deepEqual(await remoteValues(master, 0, [0x8020]), [2.5]); assert.deepEqual(await remoteValues(master, 4, [0x8221, 0x8224]), [44, 5.25]); assert.deepEqual(await fileRead(master, 'TEMP/persist.bin'), original); assert.equal((await interrogate(master)).get(0x8601), decodeFile(config).values.get(0x8601)); await master.close(); await finish(process); assert.deepEqual(fs.readFileSync(config), saved); assert(!fs.existsSync(`${config}.remote.ini`) && !fs.existsSync(`${config}.temp.bin`)); // 只复制一份主文件,不携带任何旁文件,即可在新进程恢复全部三类数据。 const copied = path.join(directory, 'copied.ini'); fs.copyFileSync(config, copied); const reloaded = launch(copied, 1200, options), next = await connect(await listening(reloaded)); assert.equal((await interrogate(next)).get(0x8601), 373); await remoteArea(next, 3); assert.deepEqual(await remoteValues(next, 4, [0x8221, 0x8224]), [44, 5.25]); assert.deepEqual(await fileRead(next, 'TEMP/persist.bin'), replacement); await next.close(); await finish(reloaded); // 只开其中一个服务并保存,未启用服务的数据仍须完整保留。 const standardOnly = launch(copied, 1500), standardMaster = await connect(await listening(standardOnly)); await writeParameter(standardMaster, 111, 0x8601, 374, 1); await standardMaster.close(); await finish(standardOnly); const retained = decodeFile(copied); assert.deepEqual(retained.remote, remoteSaved); assert.deepEqual(retained.temp.data, replacement); assert.equal(retained.values.get(0x8601), 374); const remoteOnly = launch(copied, 1200, ['--no-parameter', '--remote-parameter']); const remoteMaster = await connect(await listening(remoteOnly)); await remoteMirror(remoteMaster, remoteSwitch(2)); await remoteMaster.close(); await finish(remoteOnly); assert.deepEqual(decodeFile(copied).values, retained.values); assert.deepEqual(decodeFile(copied).temp, retained.temp); const fileOnly = launch(copied, 1200, ['--no-parameter', '--file-service']); const fileMaster = await connect(await listening(fileOnly)); await fileWrite(fileMaster, 'TEMP/disabled.bin', Buffer.from('kept')); await fileMaster.close(); await finish(fileOnly); assert.deepEqual(decodeFile(copied).values, retained.values); assert.equal(decodeFile(copied).remote.current_area, 2); return { config }; } async function combinedSaveFailure(state) { const before = decodeFile(state.config); fs.chmodSync(state.config, 0o444); try { const process = launch(state.config, 7200, ['--remote-parameter', '--file-service']); const master = await connect(await listening(process)); await writeParameter(master, 111, 0x8601, 480, 1); await remoteMirror(master, remoteSwitch(4), 0x47); await remoteMirror(master, remotePreset(1, [remoteElement(0x8221, 45, unsigned16(222))])); await remoteMirror(master, remoteEnd(1), 0x47); await remoteMirror(master, remoteEnd(1, true), 9, true); await fileWrite(master, 'TEMP/rejected.bin', Buffer.from('do not publish'), 1); assert.equal((await interrogate(master)).get(0x8601), 480); await remoteArea(master, 3); assert.deepEqual(await remoteValues(master, 1, [0x8221, 0x8224]), [41, 2.25]); assert.deepEqual(await fileRead(master, before.temp.name), before.temp.data); assert.deepEqual(fs.readFileSync(state.config), before.bytes); await waitFor(() => /CONFIG save failed:/.test(process.errors), 'Standard dirty save must remain pending'); fs.chmodSync(state.config, 0o666); await waitFor(() => decodeFile(state.config).values.get(0x8601) === 480, 'Standard retry lost after failed remote/TEMP commit', 6200); const recovered = decodeFile(state.config); assert.deepEqual(recovered.remote, before.remote); assert.deepEqual(recovered.temp, before.temp); await master.close(); await finish(process, 0, true); assert(!/CONFIG unsaved parameters at exit/.test(process.errors)); } finally { fs.chmodSync(state.config, 0o666); } } function legacyRemoteSnapshot(ca = 7) { const lines = ['[remote]', 'version=1', `common_address=${ca}`, 'current_area=3', 'deadband=2.5']; for (let area = 0; area < 5; ++area) lines.push('', `[area_${area}]`, `reset_seconds=${40 + area}`, `x_time=${1.25 + area}`); return Buffer.from(lines.join('\n') + '\n'); } async function legacyMigration() { const values = decodeFile(configuration).values, legacy = Buffer.from(fixtureText(values)); const remote = legacyRemoteSnapshot(), content = Buffer.from('legacy\0file bytes'), name = 'TEMP/migrated.bin'; const temporary = legacyTempSnapshot(name, content); for (const withMain of [true, false]) { const config = path.join(directory, withMain ? 'legacy-v1.ini' : 'legacy-side-only.ini'); if (withMain) fs.writeFileSync(config, legacy); fs.writeFileSync(`${config}.remote.ini`, remote); fs.writeFileSync(`${config}.temp.bin`, temporary); const remoteTime = fs.statSync(`${config}.remote.ini`).mtimeMs, tempTime = fs.statSync(`${config}.temp.bin`).mtimeMs; // 即使remote/file未启用,启动也必须合并全部旧档;主文件缺失时保留32项默认值。 const migrated = launch(config, 1200), first = await connect(await listening(migrated)); assert.match(migrated.output, /^CONFIG MIGRATED$/m); const expected = withMain ? values.get(0x8601) : 200; assert.equal((await interrogate(first)).get(0x8601), expected); checkRemoteSnapshot(config); assert.deepEqual(decodeFile(config).temp.data, content); await first.close(); await finish(migrated); const reloaded = launch(config, 1500, ['--remote-parameter', '--file-service']); const next = await connect(await listening(reloaded)); await remoteArea(next, 3); assert.deepEqual(await fileRead(next, name), content); await writeParameter(next, 111, 0x8601, expected + 1, 1); await next.close(); await finish(reloaded); assert.deepEqual(fs.readFileSync(`${config}.remote.ini`), remote); assert.deepEqual(fs.readFileSync(`${config}.temp.bin`), temporary); assert.equal(fs.statSync(`${config}.remote.ini`).mtimeMs, remoteTime); assert.equal(fs.statSync(`${config}.temp.bin`).mtimeMs, tempTime); // v2主文件已完整存在,损坏旧旁文件也不得再参与启动或保存。 const saved = fs.readFileSync(config), stale = Buffer.from('stale invalid legacy data'); fs.writeFileSync(`${config}.remote.ini`, stale); fs.writeFileSync(`${config}.temp.bin`, stale); const ignored = launch(config, 1200, ['--remote-parameter', '--file-service']); const active = await connect(await listening(ignored)); assert.equal((await interrogate(active)).get(0x8601), expected + 1); await remoteArea(active, 3); assert.deepEqual(await fileRead(active, name), content); await active.close(); await finish(ignored); assert.deepEqual(fs.readFileSync(config), saved); assert.deepEqual(fs.readFileSync(`${config}.remote.ini`), stale); assert.deepEqual(fs.readFileSync(`${config}.temp.bin`), stale); } // 任一旧档损坏或身份错误,不创建v2、不替换原主文件,也不更改旧旁文件。 const damagedTemp = Buffer.from(temporary); damagedTemp[damagedTemp.length - 1] ^= 1; const invalidCases = [ ['main-invalid', Buffer.from('invalid main'), remote, temporary], ['remote-invalid', legacy, Buffer.from('invalid remote'), temporary], ['temp-invalid', legacy, remote, damagedTemp], ['remote-ca', legacy, legacyRemoteSnapshot(8), temporary], ['temp-ca', legacy, remote, legacyTempSnapshot(name, content, undefined, 8)], ['missing-main-invalid', null, Buffer.from('invalid remote'), temporary] ]; for (const [label, main, remoteBytes, tempBytes] of invalidCases) { const config = path.join(directory, `${label}.ini`); if (main !== null) fs.writeFileSync(config, main); fs.writeFileSync(`${config}.remote.ini`, remoteBytes); fs.writeFileSync(`${config}.temp.bin`, tempBytes); const rejected = launch(config, 100, ['--no-parameter', '--file-service']); await finish(rejected, 1, true); assert(!rejected.output.includes('LISTEN ')); if (main === null) assert(!fs.existsSync(config)); else assert.deepEqual(fs.readFileSync(config), main); assert.deepEqual(fs.readFileSync(`${config}.remote.ini`), remoteBytes); assert.deepEqual(fs.readFileSync(`${config}.temp.bin`), tempBytes); } } async function extendedPersistence() { await remotePersistence(); const file = await filePersistence(); await unifiedValidation(file); const combined = await combinedPersistence(file); await combinedSaveFailure(combined); await legacyMigration(); // 空文件也有名称和时标;新进程须恢复已提交空文件,不能误当成“无文件”。 const empty = launch(file.config, 1200, file.options), master = await connect(await listening(empty)); await fileWrite(master, 'TEMP/empty.bin', Buffer.alloc(0)); await master.close(); await finish(empty); const reloaded = launch(file.config, 1200, file.options), next = await connect(await listening(reloaded)); assert.deepEqual(await fileRead(next, 'TEMP/empty.bin'), Buffer.alloc(0)); const listing = await tempDirectory(next); assert.equal(listing[17], 1); await next.close(); await finish(reloaded); console.log('Unified persistence loopback: passed (one INI, remote five areas/current/deadband, QRP1/Type211 rebuild, TEMP 4KB/empty/CRC, copy/restart, TEST/cancel, transactional failure/dirty retry, full validation with disabled services, cross-service preservation, v1/sidecar migration and stale-sidecar isolation)'); } async function main() { try { await createAndPersist(); await reloadAndReset(); await manualEditing(); await optionalAndInvalid(); await saveFailureAndRetry(); await extendedPersistence(); console.log('Parameter config loopback: passed (INI create, three types, restart/GI/quality, QRP1, manual editing/BOM/CRLF/order/float roundtrip, optional mode, invalid-file preservation, save failure/retry/exit)'); } finally { for (const socket of sockets) socket.destroy(); for (const process of processes) { clearTimeout(process.timer); if (!process.finished) process.child.kill(); } await Promise.allSettled(processes.map(process => process.exit)); // 递归清理前再次校验规范绝对路径;这里只删除本次mkdtemp成功创建的独占目录。 const absolute = fs.realpathSync(directory); assert(inside(fs.realpathSync(buildRoot), absolute)); assert(path.basename(absolute).startsWith('parameter-config-')); fs.rmSync(absolute, { recursive: true, force: true }); } } main().catch(error => { console.error(error); process.exitCode = 1; });