770 lines
55 KiB
JavaScript
770 lines
55 KiB
JavaScript
|
|
import test from 'node:test';
|
||
|
|
import assert from 'node:assert/strict';
|
||
|
|
import http from 'node:http';
|
||
|
|
import { spawn } from 'node:child_process';
|
||
|
|
import { randomBytes, createHash } from 'node:crypto';
|
||
|
|
import { mkdtemp, writeFile, readFile, readdir, stat, unlink } from 'node:fs/promises';
|
||
|
|
import { tmpdir } from 'node:os';
|
||
|
|
import { dirname, resolve, join } from 'node:path';
|
||
|
|
import { fileURLToPath } from 'node:url';
|
||
|
|
import { setTimeout as delay } from 'node:timers/promises';
|
||
|
|
import { MjpegParser, boundaryFromContentType } from './support/preview-pipeline.js';
|
||
|
|
|
||
|
|
// This suite only uses the native executable's explicit mock mode on 18889.
|
||
|
|
// Fixture images and export files are never evidence of real scanner output.
|
||
|
|
const workspace = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
|
||
|
|
const executable = process.env.FREESCAN_TEST_EXECUTABLE
|
||
|
|
? resolve(process.env.FREESCAN_TEST_EXECUTABLE)
|
||
|
|
: join(workspace, 'FreeScanViewer', 'FreeScanCpp.exe');
|
||
|
|
const base = 'http://127.0.0.1:18889';
|
||
|
|
const key = randomBytes(32).toString('hex');
|
||
|
|
const sockets = new Set();
|
||
|
|
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
||
|
|
|
||
|
|
function request(path, { method = 'GET', body, raw, authenticated = true, headers = {}, timeout = 5000 } = {}) {
|
||
|
|
const payload = raw ?? (body === undefined ? undefined : Buffer.from(JSON.stringify(body)));
|
||
|
|
return new Promise((resolveReply, reject) => {
|
||
|
|
const req = http.request(base + path, {
|
||
|
|
method, agent: false,
|
||
|
|
headers: {
|
||
|
|
...(authenticated ? { Authorization: `Bearer ${key}` } : {}),
|
||
|
|
...(payload !== undefined ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {}),
|
||
|
|
...headers,
|
||
|
|
},
|
||
|
|
}, res => {
|
||
|
|
const chunks = [];
|
||
|
|
res.on('data', chunk => chunks.push(chunk));
|
||
|
|
res.on('end', () => {
|
||
|
|
const bytes = Buffer.concat(chunks); let json;
|
||
|
|
try { json = JSON.parse(bytes.toString('utf8')); } catch { }
|
||
|
|
resolveReply({ status: res.statusCode, headers: res.headers, bytes, json });
|
||
|
|
});
|
||
|
|
res.on('error', reject);
|
||
|
|
});
|
||
|
|
req.on('error', reject);
|
||
|
|
req.setTimeout(timeout, () => req.destroy(new Error(`HTTP timeout ${method} ${path}`)));
|
||
|
|
if (payload !== undefined) req.write(payload);
|
||
|
|
req.end();
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
async function until(probe, message, timeout = 10000) {
|
||
|
|
const deadline = Date.now() + timeout; let failure;
|
||
|
|
while (Date.now() < deadline) {
|
||
|
|
try { const value = await probe(); if (value) return value; } catch (error) { failure = error; }
|
||
|
|
await delay(35);
|
||
|
|
}
|
||
|
|
throw new Error(message, { cause: failure });
|
||
|
|
}
|
||
|
|
|
||
|
|
async function state() { const result = await request('/api/v1/status'); assert.equal(result.status, 200); return result.json; }
|
||
|
|
function assertUnknownBattery(battery) {
|
||
|
|
assert.equal(battery.source, 'sdkDeviceStatus');
|
||
|
|
assert.equal(battery.freshnessLimitMs, 30000);
|
||
|
|
assert.deepEqual(battery.scanner, {
|
||
|
|
percent: null, rawValue: null, available: false, fresh: false, updatedUtc: null,
|
||
|
|
}, 'An HTTP mock without actual SDK battery reports cannot fabricate a scanner percentage or timestamp.');
|
||
|
|
assert.deepEqual(battery.tracker, { channels: [] }, 'Tracker channels appear only after actual callback reports.');
|
||
|
|
}
|
||
|
|
function confirmation(status) {
|
||
|
|
return { confirm: true, expectedSessionId: status.sessionId ?? null, expectedProjectId: status.projectId ?? null, discardProject: !!status.projectReady };
|
||
|
|
}
|
||
|
|
|
||
|
|
async function submit(path, body = {}) {
|
||
|
|
const accepted = await request(path, { method: 'POST', body });
|
||
|
|
assert.equal(accepted.status, 202, JSON.stringify(accepted.json));
|
||
|
|
assert.match(accepted.json.taskId, /^[a-f0-9]{32}$/);
|
||
|
|
assert.equal(accepted.json.statusUrl, `/api/v1/tasks/${accepted.json.taskId}`);
|
||
|
|
assert.equal(accepted.headers.location, accepted.json.statusUrl);
|
||
|
|
return accepted.json;
|
||
|
|
}
|
||
|
|
|
||
|
|
async function terminal(task, expected = 'succeeded', timeout = 20000) {
|
||
|
|
const result = await until(async () => {
|
||
|
|
const reply = await request(task.statusUrl);
|
||
|
|
assert.equal(reply.status, 200);
|
||
|
|
return ['succeeded', 'failed'].includes(reply.json.state) ? reply.json : null;
|
||
|
|
}, `Task ${task.taskId} did not finish`, timeout);
|
||
|
|
assert.equal(result.state, expected, JSON.stringify(result));
|
||
|
|
for (const name of ['taskId', 'action', 'state', 'createdUtc', 'startedUtc', 'finishedUtc', 'result', 'error']) assert.ok(Object.hasOwn(result, name), `Missing task field ${name}`);
|
||
|
|
for (const name of ['createdUtc', 'startedUtc', 'finishedUtc']) assert.ok(Number.isFinite(Date.parse(result[name])));
|
||
|
|
return result;
|
||
|
|
}
|
||
|
|
async function command(path, body = {}) { return terminal(await submit(path, body)); }
|
||
|
|
|
||
|
|
function jpegDimensions(bytes) {
|
||
|
|
assert.equal(bytes.readUInt16BE(0), 0xffd8, 'The mock preview must be a valid JPEG, not a JSON or PNG placeholder.');
|
||
|
|
let offset = 2;
|
||
|
|
while (offset + 4 < bytes.length) {
|
||
|
|
assert.equal(bytes[offset++], 0xff);
|
||
|
|
while (bytes[offset] === 0xff) offset++;
|
||
|
|
const marker = bytes[offset++];
|
||
|
|
if (marker === 0xd9 || marker === 0xda) break;
|
||
|
|
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
|
||
|
|
const length = bytes.readUInt16BE(offset);
|
||
|
|
if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)) return { width: bytes.readUInt16BE(offset + 5), height: bytes.readUInt16BE(offset + 3) };
|
||
|
|
assert.ok(length >= 2 && offset + length <= bytes.length); offset += length;
|
||
|
|
}
|
||
|
|
throw new Error('JPEG has no supported SOF marker.');
|
||
|
|
}
|
||
|
|
|
||
|
|
function openStream() {
|
||
|
|
return new Promise((resolveStream, reject) => {
|
||
|
|
const req = http.get(base + '/api/v1/preview/stream', { agent: false, headers: { Authorization: `Bearer ${key}` } }, res => {
|
||
|
|
if (res.statusCode !== 200) {
|
||
|
|
const chunks = []; res.on('data', b => chunks.push(b)); res.on('end', () => reject(new Error(`Stream returned ${res.statusCode}: ${Buffer.concat(chunks)}`))); return;
|
||
|
|
}
|
||
|
|
const stream = { req, res, count: 0, frames: [], error: null, closed: false, close() { this.closed = true; sockets.delete(this); req.destroy(); res.destroy(); } };
|
||
|
|
const parser = new MjpegParser(boundaryFromContentType(res.headers['content-type']), frame => { stream.count++; stream.frames.push(frame); if (stream.frames.length > 3) stream.frames.shift(); });
|
||
|
|
res.on('data', chunk => {
|
||
|
|
try {
|
||
|
|
// Exercise the actual shared browser/relay parser with unrelated
|
||
|
|
// network fragmentation, after Node removes HTTP chunk framing.
|
||
|
|
let offset = 0, index = 0; const sizes = [1, 7, 311, 4096];
|
||
|
|
while (offset < chunk.length) { const end = Math.min(chunk.length, offset + sizes[index++ % sizes.length]); parser.push(chunk.subarray(offset, end)); offset = end; }
|
||
|
|
} catch (error) { stream.error = error; stream.close(); }
|
||
|
|
});
|
||
|
|
res.on('error', error => { if (!stream.closed) stream.error = error; });
|
||
|
|
sockets.add(stream); resolveStream(stream);
|
||
|
|
});
|
||
|
|
req.on('error', reject); req.setTimeout(7000, () => req.destroy(new Error('MJPEG stream fixture timed out.')));
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
function slowBody() {
|
||
|
|
let requestHandle; const started = Date.now();
|
||
|
|
const done = new Promise((resolveReply, reject) => {
|
||
|
|
let settled = false;
|
||
|
|
requestHandle = http.request(base + '/api/v1/device/connect', {
|
||
|
|
method: 'POST', agent: false, headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', 'Content-Length': 100 },
|
||
|
|
}, res => {
|
||
|
|
const chunks = []; res.on('data', b => chunks.push(b)); res.on('end', () => { settled = true; resolveReply({ status: res.statusCode, json: JSON.parse(Buffer.concat(chunks).toString('utf8')), elapsed: Date.now() - started }); }); res.on('error', reject);
|
||
|
|
});
|
||
|
|
requestHandle.on('error', error => { if (!settled) reject(error); });
|
||
|
|
requestHandle.setTimeout(13000, () => requestHandle.destroy(new Error('Slow-body fixture exceeded 13 seconds.')));
|
||
|
|
requestHandle.flushHeaders(); requestHandle.write('{');
|
||
|
|
});
|
||
|
|
return { done, close: () => requestHandle.destroy() };
|
||
|
|
}
|
||
|
|
|
||
|
|
async function filesUnder(directory) {
|
||
|
|
const found = [];
|
||
|
|
for (const item of await readdir(directory, { withFileTypes: true })) {
|
||
|
|
const path = join(directory, item.name);
|
||
|
|
if (item.isDirectory()) found.push(...await filesUnder(path)); else if (item.isFile()) found.push(path);
|
||
|
|
}
|
||
|
|
return found;
|
||
|
|
}
|
||
|
|
|
||
|
|
test('native C++ HTTP API with explicit simulated SDK fixture on isolated port 18889', { skip: process.platform !== 'win32', timeout: 240000 }, async t => {
|
||
|
|
assert.ok((await stat(executable)).isFile(), 'Build FreeScanViewer/FreeScanCpp.exe before running native API tests.');
|
||
|
|
let occupied = false;
|
||
|
|
try { await request('/', { authenticated: false, timeout: 400 }); occupied = true; } catch { }
|
||
|
|
assert.equal(occupied, false, 'Port 18889 is occupied; this test will not stop an unrelated service.');
|
||
|
|
const directory = await mkdtemp(join(tmpdir(), 'freescan-native-offline-'));
|
||
|
|
await writeFile(join(directory, 'api-settings.json'), JSON.stringify({ enabled: true, prefix: base + '/', apiKey: key, previewFps: 20, previewMaxWidth: 1280, previewJpegQuality: 75,
|
||
|
|
sdkPath: join(directory, 'NO_REAL_SDK', 'SDKCWrapper.dll'), bridgePath: join(directory, 'NO_REAL_BRIDGE.dll') }));
|
||
|
|
const child = spawn(executable, ['--data-root', directory, '--mock', '--api-no-auto-connect'], { cwd: directory, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
|
|
let output = '', spawnError; const append = bytes => { output = (output + bytes.toString('utf8')).slice(-32000); };
|
||
|
|
child.stdout.on('data', append); child.stderr.on('data', append); child.on('error', error => { spawnError = error; });
|
||
|
|
const exited = new Promise(resolveExit => child.once('exit', (code, signal) => resolveExit({ code, signal })));
|
||
|
|
t.diagnostic(`OFFLINE TEST ONLY: ${directory}`);
|
||
|
|
let savedExport, savedBytes, connectedTask, exportTask, disconnectTask;
|
||
|
|
try {
|
||
|
|
await until(async () => {
|
||
|
|
if (spawnError) throw spawnError;
|
||
|
|
if (child.exitCode !== null) throw new Error(`Native mock exited ${child.exitCode}: ${output}`);
|
||
|
|
const current = await state();
|
||
|
|
return current.simulated === true && !current.busy && output.includes('OFFLINE_TEST_FIXTURE') ? current : null;
|
||
|
|
}, 'Explicit native mock fixture did not become ready', 18000);
|
||
|
|
|
||
|
|
await t.test('metadata, authentication, exact host and query rules preserve the external protocol', async () => {
|
||
|
|
const metadata = await request('/', { authenticated: false }); assert.equal(metadata.status, 200); assert.equal(metadata.json.implementation, 'C++17');
|
||
|
|
const health = await request('/api/v1/health'); assert.equal(health.status, 200); assert.equal(health.json.implementation, 'C++17');
|
||
|
|
assert.equal((await request('/api/v1/health', { authenticated: false })).status, 401);
|
||
|
|
assert.equal((await request('/api/v1/health', { headers: { Authorization: 'Bearer wrong-key' } })).status, 401);
|
||
|
|
assert.equal((await request('/api/v1/health', { authenticated: false, headers: { 'X-Api-Key': key } })).status, 200);
|
||
|
|
assert.equal((await request('/api/v1/health', { headers: { Host: 'localhost:18889' } })).status, 400);
|
||
|
|
assert.equal((await request('/api/v1/health?ignored=1')).status, 400);
|
||
|
|
assert.equal((await request(`/api/v1/health?apiKey=${key}`, { authenticated: false })).status, 401);
|
||
|
|
const capabilities = await request('/api/v1/capabilities'); assert.equal(capabilities.status, 200); assert.equal(capabilities.json.implementation, 'C++17'); assert.equal(capabilities.json.simulated, true);
|
||
|
|
assert.equal((await state()).autoConnection.enabled, false, '--api-no-auto-connect preserves explicit manual operation.');
|
||
|
|
for (const route of ['POST /api/v1/device/connect', 'POST /api/v1/device/disconnect', 'POST /api/v1/device/reconnect', 'POST /api/v1/preview/start', 'POST /api/v1/preview/stop']) assert.ok(capabilities.json.routes.includes(route));
|
||
|
|
for (const [name, value] of [['x-content-type-options', 'nosniff'], ['cache-control', 'no-store']]) assert.equal(health.headers[name], value);
|
||
|
|
assert.match(health.headers['content-security-policy'], /default-src 'none'/);
|
||
|
|
assert.equal((await request('/api/v1/device/connect')).status, 405);
|
||
|
|
assert.equal((await request('/api/v1/not-an-endpoint')).status, 404);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('calibration enum choices are readable without SDK initialization and never select a mode', async () => {
|
||
|
|
const before = await state();
|
||
|
|
const reply = await request('/api/v1/capabilities');
|
||
|
|
assert.equal(reply.status, 200);
|
||
|
|
assert.equal(reply.json.initialized, false);
|
||
|
|
assert.equal(reply.json.calibration, null);
|
||
|
|
assert.deepEqual(reply.json.calibrationModes, [
|
||
|
|
{ mode: 0, modeName: '跟踪仪标定' },
|
||
|
|
{ mode: 1, modeName: '系统标定' },
|
||
|
|
{ mode: 2, modeName: '探针标定' },
|
||
|
|
{ mode: 3, modeName: 'UE Nova 激光标定' },
|
||
|
|
]);
|
||
|
|
assert.equal((await request('/api/v1/capabilities', { authenticated: false })).status, 401);
|
||
|
|
const after = await state();
|
||
|
|
for (const field of ['initialized','sessionId','projectId','projectReady','scanning','calibrationActive']) {
|
||
|
|
assert.deepEqual(after[field], before[field], `Reading enum choices must not change ${field}`);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('last calibration time uses local file metadata and mock mode never reads the actual SDK files', async () => {
|
||
|
|
const before = await state();
|
||
|
|
assert.equal(before.lastCalibrationUtc, null);
|
||
|
|
assert.equal(before.lastCalibrationSource, 'local_calibration_file_modified_time');
|
||
|
|
assert.deepEqual(before.calibrationFileTimes, []);
|
||
|
|
const after = await state();
|
||
|
|
assert.equal(after.lastCalibrationUtc, null);
|
||
|
|
assert.deepEqual(after.calibrationFileTimes, []);
|
||
|
|
for (const field of ['initialized', 'sessionId', 'calibrationActive', 'scanning', 'projectReady']) {
|
||
|
|
assert.equal(after[field], before[field], `Reading file metadata must preserve ${field}`);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('battery is an authenticated read-only query with honest unknown values before connection', async () => {
|
||
|
|
const path = '/api/v1/device/battery';
|
||
|
|
assert.equal((await request(path, { authenticated: false })).status, 401);
|
||
|
|
assert.equal((await request(path, { headers: { Authorization: 'Bearer wrong-key' } })).status, 401);
|
||
|
|
const reply = await request(path);
|
||
|
|
assert.equal(reply.status, 200);
|
||
|
|
assert.equal(reply.headers['cache-control'], 'no-store');
|
||
|
|
assertUnknownBattery(reply.json);
|
||
|
|
assert.deepEqual((await state()).battery, reply.json, 'Status embeds the same battery object as the dedicated query.');
|
||
|
|
assert.equal((await request(path, { authenticated: false, headers: { 'X-Api-Key': key } })).status, 200);
|
||
|
|
assert.equal((await request(path + '?ignored=1')).status, 400);
|
||
|
|
const mutation = await request(path, { method: 'POST', body: {} });
|
||
|
|
assert.equal(mutation.status, 405);
|
||
|
|
assert.equal(mutation.headers.allow, 'GET');
|
||
|
|
assert.equal((await state()).initialized, false, 'Reading battery never connects the SDK.');
|
||
|
|
const capabilities = await request('/api/v1/capabilities');
|
||
|
|
assert.ok(capabilities.json.routes.includes('GET /api/v1/device/battery'));
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('invalid JSON, unknown fields, depth and body limits fail before a device task is accepted', async () => {
|
||
|
|
const cases = [
|
||
|
|
['/api/v1/device/connect', { body: { deviceType: true } }, 400], ['/api/v1/device/connect', { body: { deviceType: 99 } }, 400],
|
||
|
|
['/api/v1/device/connect', { body: { unused: true } }, 400], ['/api/v1/projects', { body: { path: 'C:/not-allowed' } }, 400],
|
||
|
|
['/api/v1/preview/start', { body: { extra: true } }, 400], ['/api/v1/device/disconnect', { body: {} }, 400],
|
||
|
|
['/api/v1/device/connect', { raw: Buffer.from('[]') }, 400], ['/api/v1/device/connect', { raw: Buffer.from('{') }, 400],
|
||
|
|
['/api/v1/device/connect', { raw: Buffer.from([0xc0, 0x80]) }, 400],
|
||
|
|
['/api/v1/device/connect', { raw: Buffer.from('{"x":' + '['.repeat(40) + '0' + ']'.repeat(40) + '}') }, 400],
|
||
|
|
['/api/v1/device/connect', { raw: Buffer.alloc(16385, 0x20) }, 413], ['/api/v1/align', { raw: Buffer.alloc(1024 * 1024 + 1, 0x20) }, 413],
|
||
|
|
['/api/v1/device/connect', { raw: Buffer.from('{}'), headers: { 'Content-Type': 'text/plain' } }, 415],
|
||
|
|
];
|
||
|
|
for (const [path, options, expected] of cases) {
|
||
|
|
const reply = await request(path, { method: 'POST', ...options }); assert.equal(reply.status, expected, `${path}: ${reply.bytes}`); assert.ok(reply.json?.error?.code); assert.equal(reply.json.taskId, undefined);
|
||
|
|
}
|
||
|
|
assert.equal((await state()).initialized, false);
|
||
|
|
const unknown = await request('/api/v1/tasks/' + 'f'.repeat(32)); assert.equal(unknown.status, 404);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('an incomplete body times out after eight seconds without blocking health requests', async () => {
|
||
|
|
const slow = slowBody();
|
||
|
|
try {
|
||
|
|
await delay(200); const started = Date.now(); assert.equal((await request('/api/v1/health', { timeout: 2000 })).status, 200); assert.ok(Date.now() - started < 2000);
|
||
|
|
const result = await slow.done; assert.equal(result.status, 408); assert.equal(result.json.error.code, 'request_timeout'); assert.ok(result.elapsed >= 7000 && result.elapsed < 12000, `Slow body elapsed ${result.elapsed}ms`);
|
||
|
|
} finally { slow.close(); }
|
||
|
|
assert.equal((await state()).initialized, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('connect returns a 202 task and creating a project publishes a genuine JPEG fixture', async () => {
|
||
|
|
const accepted = await submit('/api/v1/device/connect', { deviceType: 3 }); connectedTask = accepted;
|
||
|
|
const first = await request(accepted.statusUrl); assert.equal(first.status, 200); assert.ok(['queued', 'running', 'succeeded'].includes(first.json.state));
|
||
|
|
const done = await terminal(accepted); assert.equal(done.result.simulated, true);
|
||
|
|
const connected = await state(); assert.equal(connected.initialized, true); assert.match(connected.sessionId, /^[a-f0-9]{32}$/); assert.equal(connected.projectReady, false);
|
||
|
|
assertUnknownBattery(connected.battery);
|
||
|
|
const battery = await request('/api/v1/device/battery'); assert.equal(battery.status, 200); assertUnknownBattery(battery.json);
|
||
|
|
assert.deepEqual(battery.json, connected.battery, 'A mock connection cannot turn historical or synthetic data into current battery readings.');
|
||
|
|
const created = await command('/api/v1/projects', { mode: 'trak', name: 'OFFLINE_API_Test' }); assert.equal(created.result.simulated, true);
|
||
|
|
const image = await until(async () => { const result = await request('/api/v1/preview/image'); return result.status === 200 ? result : null; }, 'Mock JPEG did not arrive');
|
||
|
|
assert.match(image.headers['content-type'], /^image\/jpeg/); assert.deepEqual(jpegDimensions(image.bytes), { width: 640, height: 360 });
|
||
|
|
assert.ok(Number(image.headers['x-frame-sequence']) > 0); assert.ok(Number.isFinite(Date.parse(image.headers['x-frame-captured-utc']))); assert.ok(Number(image.headers['x-frame-age-ms']) <= 2000);
|
||
|
|
const metrics = await request('/api/v1/preview/metrics'); assert.equal(metrics.status, 200);
|
||
|
|
assert.equal(metrics.json.encoderRunning, true);
|
||
|
|
assert.equal(metrics.json.metricSource, 'worker_encoder_cache');
|
||
|
|
assert.ok(metrics.json.offeredFrames >= metrics.json.encodedFrames);
|
||
|
|
assert.ok(metrics.json.captureDiagnostics.callbackEntries > 0);
|
||
|
|
assert.equal(metrics.json.captureDiagnostics.lastChannels, 4);
|
||
|
|
assert.equal(metrics.json.captureDiagnostics.exceptions, 0);
|
||
|
|
assert.equal(metrics.json.bufferPool.capacity, 3);
|
||
|
|
assert.ok(metrics.json.bufferPool.allocatedSlots <= 3);
|
||
|
|
assert.equal((await state()).scanning, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('framework files are bounded authenticated binary uploads and only registered IDs can be imported', async () => {
|
||
|
|
const bytes = Buffer.from('OFFLINE_TEST_FIXTURE\nThis is not a valid manufacturer framework.\n');
|
||
|
|
const upload = (raw = bytes, headers = {}, authenticated = true) => request('/api/v1/framework/files', {
|
||
|
|
method: 'POST', raw, authenticated,
|
||
|
|
headers: { 'Content-Type': 'application/octet-stream', 'X-File-Name': encodeURIComponent('离线框架.p3'), ...headers },
|
||
|
|
});
|
||
|
|
assert.equal((await request('/api/v1/framework/files')).status, 405);
|
||
|
|
assert.equal((await upload(bytes, {}, false)).status, 401);
|
||
|
|
for (const [raw, headers, status] of [
|
||
|
|
[bytes, { 'Content-Type': 'application/json' }, 415],
|
||
|
|
[bytes, { 'X-File-Name': 'model.stl' }, 415],
|
||
|
|
[bytes, { 'X-File-Name': '%2e%2e%2fescape.p3' }, 400],
|
||
|
|
[bytes, { 'X-File-Name': 'bad%xx.p3' }, 400],
|
||
|
|
[bytes, { 'X-File-Name': '%FF.p3' }, 400],
|
||
|
|
[Buffer.alloc(0), {}, 400],
|
||
|
|
[Buffer.alloc(0), { 'Content-Length': 16 * 1024 * 1024 + 1 }, 413],
|
||
|
|
]) {
|
||
|
|
const reply = await upload(raw, headers); assert.equal(reply.status, status, `${JSON.stringify(headers)}: ${reply.bytes}`);
|
||
|
|
assert.equal(reply.json.taskId, undefined);
|
||
|
|
}
|
||
|
|
const uploaded = await upload();
|
||
|
|
assert.equal(uploaded.status, 201); assert.match(uploaded.json.fileId, /^[a-f0-9]{32}$/);
|
||
|
|
assert.equal(uploaded.json.name, '离线框架.p3'); assert.equal(uploaded.json.size, bytes.length);
|
||
|
|
assert.ok(Number.isFinite(Date.parse(uploaded.json.uploadedUtc)));
|
||
|
|
assert.deepEqual(Object.keys(uploaded.json).sort(), ['fileId', 'name', 'size', 'uploadedUtc']);
|
||
|
|
assert.deepEqual(await readFile(join(directory, 'FrameworkUploads', uploaded.json.fileId + '.p3')), bytes);
|
||
|
|
assert.equal((await request('/api/v1/framework/import', { method: 'POST', body: { fileIds: [uploaded.json.fileId] } })).status, 400);
|
||
|
|
const unknown = await request('/api/v1/framework/import', { method: 'POST', body: { fileIds: ['f'.repeat(32)], confirm: true } });
|
||
|
|
assert.equal(unknown.status, 404); assert.equal(unknown.json.error.code, 'framework_file_not_found'); assert.equal(unknown.json.taskId, undefined);
|
||
|
|
const imported = await command('/api/v1/framework/import', { fileIds: [uploaded.json.fileId], confirm: true });
|
||
|
|
assert.equal(imported.result.frameworkImported, true); assert.equal(imported.result.frameworkFileCount, 1); assert.equal(imported.result.simulated, true);
|
||
|
|
const current = await state(); assert.equal(current.frameworkImported, true); assert.equal(current.scanType, 'mesh'); assert.equal(current.scanDevice, 'scanner'); assert.equal(current.scanning, false);
|
||
|
|
const blocked = await terminal(await submit('/api/v1/scan/type', { scanType: 'photogrammetry', confirm: true }), 'failed');
|
||
|
|
assert.equal(blocked.error.code, 'project_data_present');
|
||
|
|
await command('/api/v1/scan/start');
|
||
|
|
const activeImport = await terminal(await submit('/api/v1/framework/import', { fileIds: [uploaded.json.fileId], confirm: true }), 'failed');
|
||
|
|
assert.equal(activeImport.error.code, 'scan_active');
|
||
|
|
const activeType = await terminal(await submit('/api/v1/scan/type', { scanType: 'mesh' }), 'failed');
|
||
|
|
assert.equal(activeType.error.code, 'scan_active');
|
||
|
|
await command('/api/v1/scan/stop');
|
||
|
|
await command('/api/v1/projects', { mode: 'trak', name: 'OFFLINE_Photo_Test' });
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('photogrammetry selects the correct device, optimizes marker data, and saves P3 without requiring a mesh', async () => {
|
||
|
|
const missingConfirm = await terminal(await submit('/api/v1/scan/type', { scanType: 'photogrammetry' }), 'failed');
|
||
|
|
assert.equal(missingConfirm.error.code, 'confirmation_required');
|
||
|
|
const changed = await command('/api/v1/scan/type', { scanType: 'photogrammetry', device: 'tracker', confirm: true });
|
||
|
|
assert.equal(changed.result.scanType, 'photogrammetry'); assert.equal(changed.result.sdkScanDeviceType, 0); assert.equal(changed.result.sdkScanType, 0);
|
||
|
|
const ready = await state(); assert.equal(ready.scanDevice, 'tracker'); assert.equal(ready.scanning, false); assert.equal(ready.frameworkImported, false);
|
||
|
|
const empty = await terminal(await submit('/api/v1/framework/optimize'), 'failed'); assert.ok(empty.error.code);
|
||
|
|
await command('/api/v1/scan/start'); await command('/api/v1/scan/stop');
|
||
|
|
const optimized = await command('/api/v1/framework/optimize'); assert.equal(optimized.result.frameworkOptimized, true);
|
||
|
|
assert.equal((await state()).meshState, 'none');
|
||
|
|
const exported = await command('/api/v1/exports', { name: 'OFFLINE_Framework', formats: ['P3'] });
|
||
|
|
assert.equal(exported.result.simulated, true); assert.equal(exported.result.files.length, 1);
|
||
|
|
const saved = await request(exported.result.files[0].downloadUrl);
|
||
|
|
assert.match(saved.bytes.toString('utf8'), /OFFLINE_TEST_FIXTURE/); assert.match(saved.bytes.toString('utf8'), /not valid scanner geometry/);
|
||
|
|
const mixed = await terminal(await submit('/api/v1/exports', { formats: ['P3', 'STL'] }), 'failed'); assert.ok(mixed.error.code);
|
||
|
|
await command('/api/v1/scan/type', { scanType: 'mesh' }); assert.equal((await state()).scanDevice, 'tracker');
|
||
|
|
const noSwitch = await terminal(await submit('/api/v1/scan/type', { scanType: 'mesh', device: 'scanner', confirm: true }), 'failed');
|
||
|
|
assert.equal(noSwitch.error.code, 'project_data_present');
|
||
|
|
await command('/api/v1/projects', { mode: 'laser', name: 'OFFLINE_Markers_Test' });
|
||
|
|
const photo = await terminal(await submit('/api/v1/scan/type', { scanType: 'photogrammetry', confirm: true }), 'failed'); assert.equal(photo.error.code, 'unsupported_scan_type');
|
||
|
|
const markers = await command('/api/v1/scan/type', { scanType: 'markers' }); assert.equal(markers.result.sdkScanType, 3);
|
||
|
|
await command('/api/v1/projects', { mode: 'trak', name: 'OFFLINE_API_Test' });
|
||
|
|
const reset = await state(); assert.equal(reset.scanType, 'mesh'); assert.equal(reset.scanDevice, 'scanner'); assert.equal(reset.frameworkImported, false); assert.equal(reset.frameworkOptimized, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('preview controls preserve scan acquisition, and stopping scan preserves project and preview', async () => {
|
||
|
|
await command('/api/v1/scan/start'); const before = await state(); assert.equal(before.scanning, true);
|
||
|
|
await command('/api/v1/preview/stop'); const stopped = await state(); assert.equal(stopped.previewEnabled, false); assert.equal(stopped.scanning, true); assert.equal(stopped.projectId, before.projectId);
|
||
|
|
assert.equal((await request('/api/v1/preview/image')).status, 503);
|
||
|
|
await command('/api/v1/preview/start'); const resumed = await state(); assert.equal(resumed.previewEnabled, true); assert.equal(resumed.scanning, true); assert.equal(resumed.projectId, before.projectId);
|
||
|
|
await until(async () => (await request('/api/v1/preview/image')).status === 200, 'Preview did not resume');
|
||
|
|
await command('/api/v1/scan/stop'); const paused = await state(); assert.equal(paused.scanning, false); assert.equal(paused.projectReady, true); assert.equal(paused.previewEnabled, true);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('MJPEG uses the unchanged shared browser parser and enforces four independent stream slots', async () => {
|
||
|
|
const streams = [];
|
||
|
|
try {
|
||
|
|
for (let i = 0; i < 4; i++) {
|
||
|
|
const stream = await openStream(); streams.push(stream); await until(() => { if (stream.error) throw stream.error; return stream.count >= 2; }, 'MJPEG frame did not parse');
|
||
|
|
assert.deepEqual(jpegDimensions(Buffer.from(stream.frames.at(-1).bytes)), { width: 640, height: 360 });
|
||
|
|
assert.ok(Number.isFinite(Date.parse(stream.frames.at(-1).capturedUtc))); assert.ok(Number(stream.frames.at(-1).sequence) > 0);
|
||
|
|
assert.notEqual(stream.frames.at(-1).ageMs, null, 'Each production MJPEG part needs its own duration header for LAN viewers.');
|
||
|
|
assert.ok(Number(stream.frames.at(-1).ageMs) >= 0 && Number(stream.frames.at(-1).ageMs) <= 2000);
|
||
|
|
}
|
||
|
|
const fifth = await request('/api/v1/preview/stream'); assert.equal(fifth.status, 429); assert.equal(fifth.json.error.code, 'stream_limit');
|
||
|
|
assert.equal((await request('/api/v1/health')).status, 200);
|
||
|
|
const first = streams[0], previous = Number(first.frames.at(-1).sequence); await until(() => Number(first.frames.at(-1)?.sequence) > previous, 'Stream sequences did not advance');
|
||
|
|
} finally { for (const stream of streams) stream.close(); }
|
||
|
|
await delay(120); const replacement = await openStream(); try { await until(() => replacement.count >= 1, 'Stream slot was not released'); } finally { replacement.close(); }
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('opt-in snapshots pause acquisition and preserve the current project and preview', async () => {
|
||
|
|
await command('/api/v1/scan/start');
|
||
|
|
const before = await state();
|
||
|
|
const unchanged = await command('/api/v1/data/snapshots', { include: ['meshes'] });
|
||
|
|
assert.equal(unchanged.result.pauseAcquisition, false);
|
||
|
|
assert.equal(unchanged.result.scanning, true);
|
||
|
|
const stopped = await command('/api/v1/data/snapshots', { include: ['meshes'], pauseAcquisition: true });
|
||
|
|
assert.equal(stopped.result.pauseAcquisition, true);
|
||
|
|
assert.equal(stopped.result.scanning, false);
|
||
|
|
assert.equal(stopped.result.simulated, true);
|
||
|
|
const after = await state();
|
||
|
|
assert.equal(after.scanning, false);
|
||
|
|
assert.equal(after.previewEnabled, true);
|
||
|
|
assert.equal(after.projectId, before.projectId);
|
||
|
|
assert.equal(stopped.result.files.length, 1);
|
||
|
|
const manifest = await request(stopped.result.files[0].downloadUrl);
|
||
|
|
assert.equal(manifest.status, 200);
|
||
|
|
assert.equal(manifest.json.simulated, true);
|
||
|
|
assert.equal(manifest.json.available, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('the HTTP task slot rejects a second control operation while mesh is running', async () => {
|
||
|
|
const mesh = await submit('/api/v1/mesh');
|
||
|
|
const second = await request('/api/v1/scan/stop', { method: 'POST', body: {} }); assert.equal(second.status, 409); assert.equal(second.json.error.code, 'busy'); assert.equal(second.json.taskId, undefined);
|
||
|
|
await terminal(mesh); await command('/api/v1/mesh/confirm'); assert.equal((await state()).meshState, 'confirmed');
|
||
|
|
exportTask = await submit('/api/v1/exports', { name: 'OFFLINE_ONLY', formats: ['PLY'] }); const exported = await terminal(exportTask);
|
||
|
|
assert.equal(exported.result.simulated, true); assert.equal(exported.result.files.length, 1); savedExport = exported.result.files[0];
|
||
|
|
assert.match(savedExport.name, /SIMULATED_.*\.fixture\.txt$/);
|
||
|
|
const download = await request(savedExport.downloadUrl); assert.equal(download.status, 200); savedBytes = download.bytes; assert.match(savedBytes.toString('utf8'), /OFFLINE_TEST_FIXTURE/); assert.match(savedBytes.toString('utf8'), /not valid scanner geometry/);
|
||
|
|
assert.match(download.headers['content-disposition'], /attachment; filename=download; filename\*=UTF-8''/);
|
||
|
|
const disk = (await filesUnder(join(directory, 'Exports'))).find(path => path.endsWith(savedExport.name)); assert.ok(disk); assert.equal(hash(await readFile(disk)), hash(savedBytes));
|
||
|
|
assert.equal((await request(savedExport.downloadUrl, { authenticated: false })).status, 401);
|
||
|
|
assert.equal((await request('/api/v1/files/not-a-file-id')).status, 400);
|
||
|
|
assert.equal((await request('/api/v1/files/' + 'e'.repeat(32))).status, 404);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('confirmation guards reject stale targets, and worker rotations retain HTTP tasks and downloads', async () => {
|
||
|
|
const before = await state(), oldSession = before.sessionId;
|
||
|
|
const stale = await terminal(await submit('/api/v1/device/reconnect', { ...confirmation(before), expectedSessionId: '0'.repeat(32) }), 'failed'); assert.equal(stale.error.code, 'session_changed'); assert.equal((await state()).sessionId, oldSession);
|
||
|
|
const wrongProject = await terminal(await submit('/api/v1/device/disconnect', { ...confirmation(before), expectedProjectId: 'another_project' }), 'failed'); assert.equal(wrongProject.error.code, 'project_changed');
|
||
|
|
const noDiscard = await terminal(await submit('/api/v1/device/disconnect', { ...confirmation(before), discardProject: false }), 'failed'); assert.equal(noDiscard.error.code, 'project_discard_confirmation_required');
|
||
|
|
disconnectTask = await submit('/api/v1/device/disconnect', confirmation(await state())); await terminal(disconnectTask);
|
||
|
|
const disconnected = await state(); assert.equal(disconnected.initialized, false); assert.equal(disconnected.projectReady, false); assert.equal(disconnected.scanning, false); assert.equal(disconnected.previewEnabled, false); assert.equal(disconnected.sessionId, null);
|
||
|
|
assertUnknownBattery(disconnected.battery);
|
||
|
|
assertUnknownBattery((await request('/api/v1/device/battery')).json);
|
||
|
|
assert.equal((await request('/api/v1/health')).status, 200); assert.equal(hash((await request(savedExport.downloadUrl)).bytes), hash(savedBytes));
|
||
|
|
await command('/api/v1/device/reconnect', confirmation(disconnected)); const reconnected = await state();
|
||
|
|
assert.equal(reconnected.initialized, true); assert.notEqual(reconnected.sessionId, oldSession); assert.equal(reconnected.projectReady, false); assert.equal(reconnected.scanning, false);
|
||
|
|
assertUnknownBattery(reconnected.battery);
|
||
|
|
assertUnknownBattery((await request('/api/v1/device/battery')).json);
|
||
|
|
for (const accepted of [connectedTask, exportTask, disconnectTask]) assert.equal((await request(accepted.statusUrl)).json.state, 'succeeded');
|
||
|
|
assert.equal(hash((await request(savedExport.downloadUrl)).bytes), hash(savedBytes));
|
||
|
|
const metrics = await request('/api/v1/preview/metrics'); assert.equal(metrics.status, 200); assert.equal(metrics.json.implementation, 'C++17');
|
||
|
|
const record = JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8')); assert.equal(record.processId, child.pid); assert.equal(record.simulated, true); assert.equal(record.implementation, 'C++17');
|
||
|
|
});
|
||
|
|
await t.test('calibration names extend task results without changing numeric requests or existing fields', async () => {
|
||
|
|
await command('/api/v1/calibration/enter', {});
|
||
|
|
const names = ['跟踪仪标定', '系统标定', '探针标定', 'UE Nova 激光标定'];
|
||
|
|
for (let mode = 0; mode < names.length; mode++) {
|
||
|
|
for (const [path, action, body] of [
|
||
|
|
['/api/v1/calibration/setMode', 'calibrationSetMode', { mode }],
|
||
|
|
['/api/v1/calibration/applyLast', 'calibrationApplyLast', { mode, confirm: true }],
|
||
|
|
]) {
|
||
|
|
const task = await command(path, body);
|
||
|
|
assert.equal(task.action, action);
|
||
|
|
assert.equal(task.result.action, action);
|
||
|
|
assert.equal(task.result.status, 'confirmed');
|
||
|
|
assert.equal(task.result.calibrationActive, true);
|
||
|
|
assert.equal(task.result.mode, mode);
|
||
|
|
assert.equal(typeof task.result.mode, 'number');
|
||
|
|
assert.equal(task.result.modeName, names[mode]);
|
||
|
|
const caps = (await request('/api/v1/capabilities')).json;
|
||
|
|
assert.equal(caps.calibration.mode, mode);
|
||
|
|
assert.equal(caps.calibration.modeName, names[mode]);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
assert.equal((await request('/api/v1/calibration/setMode', { method: 'POST', body: { mode: '跟踪仪标定' } })).status, 400);
|
||
|
|
assert.equal((await request('/api/v1/calibration/setMode', { method: 'POST', body: { mode: 0, modeName: names[0] } })).status, 400);
|
||
|
|
assert.equal((await state()).projectReady, false);
|
||
|
|
assert.equal((await state()).scanning, false);
|
||
|
|
});
|
||
|
|
await t.test('SDK calibration calculation callbacks complete HTTP tasks with the actual result and preserve the reusable session', async () => {
|
||
|
|
const callbackFixture = join(directory, 'OFFLINE_TEST_CALIBRATION_COMPUTE_REPLY');
|
||
|
|
await command('/api/v1/calibration/setMode', { mode:1 });
|
||
|
|
await command('/api/v1/calibration/setFree', { enabled:true, confirm:true });
|
||
|
|
await command('/api/v1/calibration/capturePose', { confirm:true });
|
||
|
|
const before = await state();
|
||
|
|
const assertSessionPreserved = async () => {
|
||
|
|
const current = await state();
|
||
|
|
assert.equal(current.sessionId, before.sessionId);
|
||
|
|
assert.equal(current.initialized, true);
|
||
|
|
assert.equal(current.busy, false);
|
||
|
|
assert.equal(current.restartRequired, false);
|
||
|
|
assert.equal(current.calibrationActive, true);
|
||
|
|
};
|
||
|
|
const computeWithCallback = async (callback, expected = 'succeeded') => {
|
||
|
|
await writeFile(callbackFixture, JSON.stringify(callback));
|
||
|
|
const started = Date.now();
|
||
|
|
const result = await terminal(await submit('/api/v1/calibration/compute', { confirm:true }), expected);
|
||
|
|
assert.ok(Date.now() - started < 2000,
|
||
|
|
`A definitive SDK calculation result must finish promptly without the 300-second timeout: ${JSON.stringify(callback)}`);
|
||
|
|
assert.equal(result.action, 'calibrationCompute');
|
||
|
|
await assertSessionPreserved();
|
||
|
|
return result;
|
||
|
|
};
|
||
|
|
|
||
|
|
// Preserve the real negative callback regression: an explicit failure
|
||
|
|
// must remain failed instead of being mistaken for a successful receipt.
|
||
|
|
const rejected = await computeWithCallback({ cmd:'calibCalculateResult', type:'rep', calibTarget:'5',
|
||
|
|
calibResult:'false', camErr:'0', errorCode:'0x00000001', result:'failed' }, 'failed');
|
||
|
|
assert.equal(rejected.error.code, 'sdk_error');
|
||
|
|
assert.equal(rejected.error.httpStatus, 502);
|
||
|
|
assert.match(rejected.error.message, /0x00000001/);
|
||
|
|
assert.match(rejected.error.message, /calibTarget="5"/);
|
||
|
|
assert.equal(rejected.result, null);
|
||
|
|
|
||
|
|
// This is the actual successful SDK reply from the completed 56-pose
|
||
|
|
// calibration, whose previous HTTP task incorrectly timed out.
|
||
|
|
const calculated = { cmd:'calibCalculateResult', type:'rep', calibResult:'true', calibTarget:'6',
|
||
|
|
camErr:'0.004910327805427969', errorCode:'0x00000000', isTrinity:'true', result:'success' };
|
||
|
|
const succeeded = await computeWithCallback(calculated);
|
||
|
|
assert.equal(succeeded.error, null);
|
||
|
|
assert.equal(succeeded.result.action, 'calibrationCompute');
|
||
|
|
assert.equal(succeeded.result.calibrationActive, true);
|
||
|
|
assert.equal(succeeded.result.status, 'confirmed');
|
||
|
|
assert.deepEqual(succeeded.result.sdkResult, calculated,
|
||
|
|
'Return the actual callback with its original fields and string values, including the residual.');
|
||
|
|
|
||
|
|
// The documented completion ACK is still supported. Its task must retain
|
||
|
|
// this callback, without leaking the preceding calculation's fields.
|
||
|
|
const acknowledged = { cmd:'freeCalibrationComputeFinish', type:'rep', result:'success' };
|
||
|
|
const legacy = await computeWithCallback(acknowledged);
|
||
|
|
assert.equal(legacy.error, null);
|
||
|
|
assert.equal(legacy.result.action, 'calibrationCompute');
|
||
|
|
assert.equal(legacy.result.calibrationActive, true);
|
||
|
|
assert.equal(legacy.result.status, 'confirmed');
|
||
|
|
assert.deepEqual(legacy.result.sdkResult, acknowledged);
|
||
|
|
|
||
|
|
await command('/api/v1/calibration/capturePose', { confirm:true });
|
||
|
|
await assertSessionPreserved();
|
||
|
|
assert.deepEqual((await request(`/api/v1/tasks/${rejected.taskId}`)).json, rejected);
|
||
|
|
assert.deepEqual((await request(`/api/v1/tasks/${succeeded.taskId}`)).json, succeeded,
|
||
|
|
'A later callback and command must not overwrite the completed calculation result.');
|
||
|
|
assert.deepEqual((await request(`/api/v1/tasks/${legacy.taskId}`)).json, legacy);
|
||
|
|
});
|
||
|
|
await t.test('calibration recovery validates targets, releases an idle session and preserves HTTP tasks and downloads', async () => {
|
||
|
|
const before = await state();
|
||
|
|
assert.equal(before.calibrationActive, true);
|
||
|
|
const oldRecord = JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8'));
|
||
|
|
const target = { confirm:true, expectedSessionId:before.recoverySessionId || before.sessionId };
|
||
|
|
assert.equal((await request('/api/v1/calibration/recover', { method:'POST', body:{ confirm:true } })).status, 400);
|
||
|
|
const rejected = await terminal(await submit('/api/v1/calibration/recover', { ...target, force:true, expectedSessionId:'0'.repeat(32) }), 'failed');
|
||
|
|
assert.equal(rejected.error.code, 'session_changed');
|
||
|
|
assert.equal((await state()).sessionId, before.sessionId, 'A stale recovery request cannot abort another session.');
|
||
|
|
const recovered = await terminal(await submit('/api/v1/calibration/recover', target), 'succeeded', 60000);
|
||
|
|
assert.equal(recovered.result.recovered, true);
|
||
|
|
assert.equal(recovered.result.reconnected, true);
|
||
|
|
assert.equal(recovered.result.calibrationAborted, true);
|
||
|
|
assert.equal(recovered.result.forced, false);
|
||
|
|
const after = await state();
|
||
|
|
assert.equal(after.initialized, true); assert.equal(after.calibrationActive, false);
|
||
|
|
assert.equal(after.scanning, false); assert.equal(after.projectReady, false);
|
||
|
|
assert.notEqual(after.sessionId, before.sessionId);
|
||
|
|
const newRecord = JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8'));
|
||
|
|
assert.equal(newRecord.processId, oldRecord.processId);
|
||
|
|
assert.equal(newRecord.startedFileTime, oldRecord.startedFileTime, 'Recovery must keep the HTTP supervisor alive.');
|
||
|
|
assert.deepEqual((await request(`/api/v1/tasks/${recovered.taskId}`)).json, recovered);
|
||
|
|
assert.equal(hash((await request(savedExport.downloadUrl)).bytes), hash(savedBytes));
|
||
|
|
const notCalibrating = await terminal(await submit('/api/v1/calibration/recover', { confirm:true, force:true, expectedSessionId:after.sessionId }), 'failed');
|
||
|
|
assert.equal(notCalibrating.error.code, 'calibration_not_active');
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('an independent recovery task can abort a blocked calibration without restarting HTTP or accepting duplicate recovery', async () => {
|
||
|
|
await command('/api/v1/calibration/enter', {});
|
||
|
|
await command('/api/v1/calibration/setMode', { mode:1 });
|
||
|
|
const before = await state();
|
||
|
|
const fixture = join(directory, 'OFFLINE_TEST_CALIBRATION_START_HANG');
|
||
|
|
await writeFile(fixture, 'OFFLINE_TEST_FIXTURE\n');
|
||
|
|
const blocked = await submit('/api/v1/calibration/startSystem', { confirm:true });
|
||
|
|
await until(async () => (await state()).busy, 'The offline calibration did not block.');
|
||
|
|
const busyCaps = await request('/api/v1/capabilities');
|
||
|
|
assert.equal(busyCaps.status, 200);
|
||
|
|
assert.ok(busyCaps.json.routes.includes('POST /api/v1/calibration/recover'));
|
||
|
|
const target = { confirm:true, expectedSessionId:before.sessionId };
|
||
|
|
const ordinary = await terminal(await submit('/api/v1/calibration/recover', target), 'failed');
|
||
|
|
assert.equal(ordinary.error.code, 'recovery_requires_force');
|
||
|
|
assert.equal((await request(blocked.statusUrl)).json.state, 'running', 'Normal release cannot implicitly abort a running calibration.');
|
||
|
|
const recovering = await submit('/api/v1/calibration/recover', { ...target, force:true });
|
||
|
|
const duplicate = await request('/api/v1/calibration/recover', { method:'POST', body:{ ...target, force:true } });
|
||
|
|
assert.equal(duplicate.status, 409); assert.equal(duplicate.json.error.code, 'recovery_in_progress');
|
||
|
|
assert.equal((await request('/api/v1/health')).status, 200);
|
||
|
|
assert.equal((await request('/api/v1/device/connect', { method:'POST', body:{} })).status, 409);
|
||
|
|
await unlink(fixture);
|
||
|
|
const finished = await terminal(recovering, 'succeeded', 60000);
|
||
|
|
assert.equal(finished.result.forced, true);
|
||
|
|
const aborted = await terminal(blocked, 'failed');
|
||
|
|
assert.equal(aborted.error.code, 'calibration_aborted');
|
||
|
|
const after = await state();
|
||
|
|
assert.equal(after.initialized, true); assert.equal(after.calibrationActive, false);
|
||
|
|
assert.equal(after.busy, false); assert.equal(after.restartRequired, false);
|
||
|
|
assert.notEqual(after.sessionId, before.sessionId);
|
||
|
|
await delay(150);
|
||
|
|
assert.deepEqual((await request(blocked.statusUrl)).json, aborted, 'Late results cannot overwrite the aborted task.');
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('a queued calibration command cannot execute against the replacement SDK after recovery', async () => {
|
||
|
|
await command('/api/v1/calibration/enter', {});
|
||
|
|
const before = await state();
|
||
|
|
const fixture = join(directory, 'OFFLINE_TEST_HTTP_DELAY_CALIBRATION_DISPATCH');
|
||
|
|
await writeFile(fixture, 'OFFLINE_TEST_FIXTURE\n');
|
||
|
|
const delayed = await submit('/api/v1/calibration/setMode', { mode:1 });
|
||
|
|
await until(async () => {
|
||
|
|
try { return JSON.parse(await readFile(join(directory, 'OFFLINE_TEST_HTTP_DISPATCH_WAITING'), 'utf8')).taskId === delayed.taskId; }
|
||
|
|
catch { return false; }
|
||
|
|
}, 'The mock HTTP calibration dispatch did not pause.');
|
||
|
|
const recovered = await terminal(await submit('/api/v1/calibration/recover', { confirm:true, force:true, expectedSessionId:before.sessionId }), 'succeeded', 60000);
|
||
|
|
assert.equal(recovered.result.recovered, true);
|
||
|
|
await unlink(fixture);
|
||
|
|
const aborted = await terminal(delayed, 'failed');
|
||
|
|
assert.equal(aborted.error.code, 'calibration_aborted');
|
||
|
|
await delay(250);
|
||
|
|
const caps = (await request('/api/v1/capabilities')).json;
|
||
|
|
assert.equal((await state()).calibrationActive, false, 'A delayed old HTTP request cannot re-enter calibration or modify the new session.');
|
||
|
|
assert.equal(caps.calibration.lastConfirmedAction, 'none');
|
||
|
|
assert.deepEqual((await request(delayed.statusUrl)).json, aborted);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('a failed normal release remains explicitly retryable with the original recovery identity', async () => {
|
||
|
|
await command('/api/v1/calibration/enter', {});
|
||
|
|
const before = await state();
|
||
|
|
await writeFile(join(directory, 'OFFLINE_TEST_RECOVERY_CLOSE_FAIL_ONCE'), 'OFFLINE_TEST_FIXTURE\n');
|
||
|
|
const target = { confirm:true, expectedSessionId:before.recoverySessionId || before.sessionId };
|
||
|
|
const refused = await terminal(await submit('/api/v1/calibration/recover', target), 'failed', 60000);
|
||
|
|
assert.equal(refused.error.code, 'recovery_requires_force');
|
||
|
|
assert.equal((await state()).recoverySessionId, target.expectedSessionId);
|
||
|
|
const retry = await terminal(await submit('/api/v1/calibration/recover', { ...target, force:true }), 'succeeded', 60000);
|
||
|
|
assert.equal(retry.result.recovered, true);
|
||
|
|
assert.equal((await state()).restartRequired, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('failure while connecting a replacement worker can be retried without reviving the old calibration', async () => {
|
||
|
|
await command('/api/v1/calibration/enter', {});
|
||
|
|
const before = await state();
|
||
|
|
await writeFile(join(directory, 'OFFLINE_TEST_RECOVERY_CONNECT_FAIL_ONCE'), 'OFFLINE_TEST_FIXTURE\n');
|
||
|
|
const target = { confirm:true, force:true, expectedSessionId:before.recoverySessionId || before.sessionId };
|
||
|
|
const failed = await terminal(await submit('/api/v1/calibration/recover', target), 'failed', 60000);
|
||
|
|
assert.equal(failed.error.code, 'recovery_connect_failed');
|
||
|
|
const fault = await state();
|
||
|
|
assert.equal(fault.recoverySessionId, target.expectedSessionId);
|
||
|
|
const retry = await terminal(await submit('/api/v1/calibration/recover', { ...target, expectedSessionId:fault.recoverySessionId }), 'succeeded', 60000);
|
||
|
|
assert.equal(retry.result.recovered, true);
|
||
|
|
assert.equal((await state()).calibrationActive, false);
|
||
|
|
assert.equal((await state()).restartRequired, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
await t.test('a timed-out calibration exposes a recoverable session identity and can be recovered past restart_required', async () => {
|
||
|
|
await command('/api/v1/calibration/enter', {});
|
||
|
|
await command('/api/v1/calibration/setMode', { mode:1 });
|
||
|
|
const before = await state();
|
||
|
|
const fixture = join(directory, 'OFFLINE_TEST_CALIBRATION_START_TIMEOUT');
|
||
|
|
await writeFile(fixture, 'OFFLINE_TEST_FIXTURE\n');
|
||
|
|
const timedOut = await terminal(await submit('/api/v1/calibration/startSystem', { confirm:true }), 'failed');
|
||
|
|
assert.equal(timedOut.error.code, 'sdk_timeout');
|
||
|
|
const fault = await state();
|
||
|
|
assert.equal(fault.restartRequired, true);
|
||
|
|
assert.equal(fault.recoverySessionId, before.sessionId);
|
||
|
|
const faultCaps = await request('/api/v1/capabilities');
|
||
|
|
assert.equal(faultCaps.status, 200);
|
||
|
|
assert.ok(faultCaps.json.routes.includes('POST /api/v1/calibration/recover'));
|
||
|
|
await unlink(fixture);
|
||
|
|
const recovered = await terminal(await submit('/api/v1/calibration/recover', {
|
||
|
|
confirm:true, force:true, expectedSessionId:fault.recoverySessionId || fault.sessionId,
|
||
|
|
}), 'succeeded', 60000);
|
||
|
|
assert.equal(recovered.result.recovered, true);
|
||
|
|
assert.equal((await state()).restartRequired, false);
|
||
|
|
await command('/api/v1/projects', { mode:'trak', name:'OFFLINE_Recovery_Project_Guard' });
|
||
|
|
const project = await state();
|
||
|
|
const refused = await terminal(await submit('/api/v1/calibration/recover', { confirm:true, force:true, expectedSessionId:project.sessionId }), 'failed');
|
||
|
|
assert.equal(refused.error.code, 'project_protected');
|
||
|
|
assert.equal((await state()).projectId, project.projectId);
|
||
|
|
});
|
||
|
|
} catch (error) {
|
||
|
|
error.message += `\nNative mock output:\n${output}\nFixture directory: ${directory}`; throw error;
|
||
|
|
} finally {
|
||
|
|
for (const stream of [...sockets]) stream.close();
|
||
|
|
if (child.exitCode === null && !spawnError) {
|
||
|
|
const stop = spawn(executable, ['--stop', '--data-root', directory], { cwd: directory, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
|
|
let stopOutput = ''; stop.stdout.on('data', bytes => { stopOutput += bytes; }); stop.stderr.on('data', bytes => { stopOutput += bytes; });
|
||
|
|
const result = await Promise.race([new Promise(resolveStop => { stop.once('exit', code => resolveStop({ code })); stop.once('error', error => resolveStop({ error })); }), delay(26000, undefined, { ref: false }).then(() => ({ timeout: true }))]);
|
||
|
|
assert.equal(result.code, 0, `Native test shutdown was not confirmed: ${stopOutput} ${JSON.stringify(result)}; test will not kill an unknown service.`);
|
||
|
|
}
|
||
|
|
const ended = await Promise.race([exited, delay(5000, undefined, { ref: false }).then(() => ({ timeout: true }))]); assert.equal(ended.code, 0, `Native mock did not exit cleanly: ${JSON.stringify(ended)}\n${output}`);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
test('SDK automatically restarts after failed initialization/cleanup while HTTP, tasks and protected sessions survive', { skip: process.platform !== 'win32', timeout: 80000 }, async () => {
|
||
|
|
let occupied = false;
|
||
|
|
try { await request('/', { authenticated: false, timeout: 400 }); occupied = true; } catch { }
|
||
|
|
assert.equal(occupied, false, 'Auto-connect fixture will not stop an unrelated HTTP service.');
|
||
|
|
const directory = await mkdtemp(join(tmpdir(), 'freescan-auto-offline-'));
|
||
|
|
await writeFile(join(directory, 'api-settings.json'), JSON.stringify({
|
||
|
|
enabled: true, prefix: base + '/', apiKey: key, previewFps: 20, previewMaxWidth: 1280, previewJpegQuality: 75,
|
||
|
|
autoConnect: true, autoConnectRetrySeconds: 5,
|
||
|
|
sdkPath: join(directory, 'NO_REAL_SDK', 'SDKCWrapper.dll'), bridgePath: join(directory, 'NO_REAL_BRIDGE.dll'),
|
||
|
|
}));
|
||
|
|
await writeFile(join(directory, 'OFFLINE_TEST_FAIL_INITIALIZE_ONCE'), 'OFFLINE_TEST_FIXTURE\n');
|
||
|
|
const child = spawn(executable, ['--data-root', directory, '--mock'], { cwd: directory, windowsHide: true, stdio: ['ignore','pipe','pipe'] });
|
||
|
|
let output = '';
|
||
|
|
const append = bytes => { output = (output + bytes.toString('utf8')).slice(-16000); };
|
||
|
|
child.stdout.on('data', append); child.stderr.on('data', append);
|
||
|
|
const ended = new Promise(resolveExit => { child.once('exit', code => resolveExit(code)); child.once('error', error => resolveExit(error)); });
|
||
|
|
try {
|
||
|
|
const failed = await until(async () => {
|
||
|
|
const current = await state();
|
||
|
|
return current.simulated && current.autoConnection.state === 'retry_wait' ? current : null;
|
||
|
|
}, 'Mock initialization failure was not reported', 18000);
|
||
|
|
assert.equal(failed.initialized, false);
|
||
|
|
assert.equal(failed.autoConnection.lastError.code, 'sdk_timeout');
|
||
|
|
const originalRecord = JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8'));
|
||
|
|
const failedTask = await terminal(await submit('/api/v1/scan/start', {}), 'failed');
|
||
|
|
let observedRecovering = false;
|
||
|
|
const connected = await until(async () => {
|
||
|
|
const current = await state();
|
||
|
|
if (current.autoConnection.state === 'recovering') observedRecovering = true;
|
||
|
|
return current.simulated && current.initialized && !current.busy && current.autoConnection.state === 'connected' ? current : null;
|
||
|
|
}, 'Automatic mock SDK did not restart and initialize', 30000);
|
||
|
|
assert.equal(connected.projectReady, false);
|
||
|
|
assert.equal(connected.scanning, false);
|
||
|
|
assert.equal(connected.autoConnection.enabled, true);
|
||
|
|
assert.equal(connected.autoConnection.retryIntervalSeconds, 5);
|
||
|
|
assert.equal(connected.autoConnection.attempts, 2);
|
||
|
|
assert.equal(connected.autoConnection.restartCount, 1);
|
||
|
|
assert.equal(connected.autoConnection.lastRestartForced, true);
|
||
|
|
assert.ok(Number.isFinite(Date.parse(connected.autoConnection.lastRestartUtc)));
|
||
|
|
assert.ok(observedRecovering, 'HTTP status must remain readable during SDK restart.');
|
||
|
|
assert.deepEqual(JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8')), originalRecord,
|
||
|
|
'SDK recovery must preserve the same HTTP parent PID and identity.');
|
||
|
|
assert.deepEqual((await request(`/api/v1/tasks/${failedTask.taskId}`)).json, failedTask,
|
||
|
|
'SDK restart must retain the original HTTP task table.');
|
||
|
|
assert.match(output, /SDK工作进程已重启/);
|
||
|
|
await command('/api/v1/device/disconnect', confirmation(connected));
|
||
|
|
await delay(2200);
|
||
|
|
const disconnected = await state();
|
||
|
|
assert.equal(disconnected.initialized, false);
|
||
|
|
assert.equal(disconnected.autoConnection.paused, true);
|
||
|
|
assert.equal(disconnected.autoConnection.state, 'paused');
|
||
|
|
await command('/api/v1/device/connect', {});
|
||
|
|
await until(async () => (await state()).autoConnection.state === 'connected', 'Manual connect did not resume automatic monitoring');
|
||
|
|
const reconnected = await state();
|
||
|
|
assert.notEqual(reconnected.sessionId, connected.sessionId);
|
||
|
|
await command('/api/v1/projects', { name:'Protected', mode:'trak' });
|
||
|
|
const project = await state();
|
||
|
|
await command('/api/v1/scan/start', {});
|
||
|
|
await delay(1200);
|
||
|
|
assert.equal((await state()).scanning, true);
|
||
|
|
await command('/api/v1/scan/stop', {});
|
||
|
|
await delay(1200);
|
||
|
|
const paused = await state();
|
||
|
|
assert.equal(paused.sessionId, project.sessionId);
|
||
|
|
assert.equal(paused.projectId, project.projectId);
|
||
|
|
assert.equal(paused.projectReady, true);
|
||
|
|
assert.equal(paused.scanning, false, 'The automatic connector must never resume acquisition.');
|
||
|
|
assert.equal(paused.autoConnection.state, 'session_active');
|
||
|
|
assert.equal(paused.autoConnection.restartCount, 1, 'Project/scanning/paused sessions must not trigger SDK replacement.');
|
||
|
|
} catch (error) {
|
||
|
|
error.message += '\n' + output; throw error;
|
||
|
|
} finally {
|
||
|
|
if (child.exitCode === null) {
|
||
|
|
const stop = spawn(executable, ['--stop','--data-root',directory], { cwd:directory, windowsHide:true, stdio:['ignore','pipe','pipe'] });
|
||
|
|
const stopped = await Promise.race([new Promise(resolveStop => { stop.once('exit', code=>resolveStop(code)); stop.once('error', resolveStop); }), delay(25000, undefined, { ref:false }).then(()=> 'timeout')]);
|
||
|
|
assert.equal(stopped, 0, `Automatic fixture did not stop normally: ${output}`);
|
||
|
|
}
|
||
|
|
assert.equal(await Promise.race([ended,delay(5000, undefined, { ref:false }).then(()=> 'timeout')]), 0);
|
||
|
|
}
|
||
|
|
});
|