AtlatestRepositorysigil-http3

sigil-http3 / tree / scriptscheck-continuous-punch.mjs

1// Real native endpoint + UDP peers, entirely on IPv6 loopback on Linux.
2import assert from 'node:assert/strict';
3import { spawn } from 'node:child_process';
4import { createSocket } from 'node:dgram';
5import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
6import { hostname } from 'node:os';
7import { resolve, join } from 'node:path';
8import { identity, sameIdentity } from './echo-lifecycle.mjs';
9
10const pause = ms => new Promise(done => setTimeout(done, ms));
11const root = resolve('build/continuous-punch-checks');
12mkdirSync(root, { mode: 0o700 });
13const peers = [], received = [];
14let interrupted = false;
15const interrupt = () => { interrupted = true; };
16process.on('SIGTERM', interrupt);
17process.on('SIGINT', interrupt);
18const deadline = setTimeout(interrupt, 30000);
19async function until(predicate, timeout = 6000) {
20 const end = Date.now() + timeout;
21 while (!predicate()) {
22 if (interrupted || Date.now() > end) throw new Error('Continuous punch check interrupted/deadline');
23 await pause(25);
24 }
26async function check(name, seconds, stopEarly = false) {
27 const directory = join(root, name);
28 mkdirSync(directory, { mode: 0o700 });
29 let output = '', stderr = '', closed = false, code;
30 const child = spawn(resolve('tools/interop/build/native/bin/http3-preflight'), [], { env: { ...process.env,
31 HTTP3_PREFLIGHT_HOST: '::1', HTTP3_PREFLIGHT_PORT: '0', HTTP3_PREFLIGHT_DIR: resolve('build/browser'),
32 HTTP3_PREFLIGHT_ORIGIN: 'https://example.com', HTTP3_PUNCH_DIRECTORY: directory,
33 HTTP3_PUNCH_TEST_LOOPBACK: '1', HTTP3_SPIKE_TRACE: '1' }, stdio: ['ignore', 'pipe', 'pipe'] });
34 const admitted = identity(child.pid);
35 assert.ok(admitted && admitted.uid === process.getuid());
36 const done = new Promise(done => child.once('close', result => { closed = true; code = result; done(); }));
37 child.on('error', error => { stderr += error.message; });
38 child.stdout.on('data', bytes => {
39 output += bytes.toString().slice(0, Math.max(0, 1048576 - output.length));
40 if (output.length >= 1048576) interrupt();
41 });
42 child.stderr.on('data', bytes => {
43 stderr += bytes.toString().slice(0, Math.max(0, 1048576 - stderr.length));
44 if (stderr.length >= 1048576) interrupt();
45 });
46 const before = received.length;
47 let result;
48 try {
49 await until(() => closed || output.includes('HTTP3-READY'));
50 assert.equal(closed, false, stderr);
51 const port = Number(output.match(/HTTP3-READY[^\n]*port=(\d+)/)?.[1]);
52 assert.ok(port > 0);
53 await pause(1050);
54 assert.equal(received.length, before, 'Control emitted a priming datagram');
55 const controlAt = new Date().toISOString();
56 writeFileSync(join(directory, 'command.scm'), `(1 "${name}" "::1" ${seconds})\n`, { flag: 'wx', mode: 0o600 });
57 if (seconds > 180) {
58 await until(() => closed);
59 assert.notEqual(code, 0);
60 assert.equal(received.length, before);
61 assert.equal(existsSync(join(directory, 'started.json')), false);
62 result = { invalidWindowRejected: true };
63 } else {
64 await until(() => received.length >= before + 3);
65 assert.ok(sameIdentity(admitted, identity(child.pid)), 'Listener changed during priming');
66 // The same endpoint still receives while its socket sends the pulse.
67 await new Promise((done, reject) => peers[0].send(Buffer.from([0xc0, 0, 0, 0, 1]), port, '::1', error => error ? reject(error) : done()));
68 await until(() => output.includes('event=udp-in'));
69 if (stopEarly) writeFileSync(join(directory, 'stop'), 'stop\n', { mode: 0o600 });
70 await until(() => existsSync(join(directory, 'finished.json')));
71 const finish = JSON.parse(readFileSync(join(directory, 'finished.json')));
72 const count = received.length;
73 await pause(1200);
74 assert.equal(received.length, count, 'Sender continued after its bounded window');
75 assert.equal(closed, false, 'Priming stopped the listener');
76 assert.ok(sameIdentity(admitted, identity(child.pid)));
77 const packets = received.slice(before);
78 assert.ok(packets.every(p => p.address === '::1' && p.port === port && p.bytes === 8), 'Priming used a different source tuple');
79 assert.equal(packets.length, finish.packets);
80 assert.ok(packets.length <= 3 * seconds);
81 assert.equal(finish.reason, stopEarly ? 'controller-stop' : 'window-expired');
82 if (!stopEarly) {
83 assert.equal(packets.length, 9);
84 const first = packets.filter(p => p.destinationPort === 40000).map(p => p.time);
85 assert.ok(first[1] - first[0] >= 950 && first[2] - first[1] >= 950);
86 }
87 result = { controlAt, sourcePort: port, packets: packets.length, finish,
88 samePID: true, ingressWhilePriming: true, stoppedSendingStillListening: true };
89 }
90 } finally {
91 if (!closed && sameIdentity(admitted, identity(child.pid))) child.kill('SIGTERM');
92 await Promise.race([done, pause(2000)]);
93 if (!closed && sameIdentity(admitted, identity(child.pid))) child.kill('SIGKILL');
94 await Promise.race([done, pause(2000)]);
95 assert.equal(closed, true, 'Native child was not reaped');
96 writeFileSync(join(directory, 'stdout.log'), output, { mode: 0o600 });
97 writeFileSync(join(directory, 'stderr.log'), stderr, { mode: 0o600 });
98 }
99 return result;
101try {
102 for (const port of [40000, 40001, 40002]) {
103 const socket = createSocket('udp6'); peers.push(socket);
104 socket.on('message', (bytes, peer) => received.push({ destinationPort: port, address: peer.address,
105 port: peer.port, bytes: bytes.length, time: Date.now() }));
106 await new Promise((done, reject) => { socket.once('error', reject); socket.bind(port, '::1', done); });
107 }
108 const results = { bounded: await check('bounded', 3), cancelled: await check('cancelled', 180, true),
109 invalid: await check('invalid', 181) };
110 writeFileSync(join(root, 'result.json'), JSON.stringify({ passed: true, results }, null, 2) + '\n', { mode: 0o600 });
111 console.log('RESULT native-same-socket-continuous-punch=PASS cases=3');
112} finally {
113 clearTimeout(deadline);
114 process.off('SIGTERM', interrupt);
115 process.off('SIGINT', interrupt);
116 await Promise.all(peers.map(socket => new Promise(done => { try { socket.close(done); } catch { done(); } })));