feat(core): DHCP in the simulation core, as in Swift
engine.ts ports Swift's "DHCP server and automatic client": an active server listens on port 67 from the start and offers a static assignment before its range, round from the address after the last one offered; offers last 10 s, dynamic leases a day, and a server whose offer another server beat blacklists that address for a while. A client starts as an event: DISCOVER, OFFER, a check by ARP, DECLINE, REQUEST, ACK or NAK, 2.5 s per wait, and after ten failures its old address back. The snapshot carries the DHCP settings of clients and servers. Four scenarios match the Swift engine. One Swift error is named in the oracle test: a client run directly is advanced a second time, to FINISH, by the server's answer within its own DISCOVER, and the outer run then writes back its stale copy of the status (Swift's value types); the address and every trace agree, only the reported status is wrong in Swift. Swift's three DHCP engine tests are ported, with tests for stopping and the message format. 15 mutation probes, 14 caught; the other concerns the home router, which runs only once NAT is ported. Two departures from Java remain, to be fixed next: from the event queue the client's ARP check does not wait, so an address conflict is never found, and each answer that wakes the client makes it send its state's message again (a second DISCOVER and REQUEST, the second answered with NAK). Java waits a round trip and sends once per attempt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
deviceConfiguration,
|
||||
dhcpServerConfiguration,
|
||||
firewallConfiguration,
|
||||
firewallRule,
|
||||
interfaceKey,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
portSnapshot,
|
||||
switchConfiguration,
|
||||
topologySnapshot,
|
||||
type DhcpClientStatus,
|
||||
type FirewallConfiguration,
|
||||
type IPv4DeliveryResult,
|
||||
type IcmpObservation,
|
||||
@@ -55,6 +57,11 @@ interface Scenario {
|
||||
}[];
|
||||
}
|
||||
>;
|
||||
dhcpServers?: Record<
|
||||
string,
|
||||
{ active?: boolean; lower?: string; upper?: string; gateway?: string; dns?: string; own?: boolean; staticAssignments?: [string, string][] }
|
||||
>;
|
||||
dhcpClients?: string[];
|
||||
steps: {
|
||||
op: string;
|
||||
from?: string;
|
||||
@@ -144,6 +151,25 @@ function snapshotOf(scenario: Scenario): TopologySnapshot {
|
||||
),
|
||||
]),
|
||||
),
|
||||
dhcpServerConfigurationsByNodeId: new Map(
|
||||
Object.entries(scenario.dhcpServers ?? {}).map(([node, config]) => [
|
||||
node,
|
||||
dhcpServerConfiguration({
|
||||
isActive: config.active ?? false,
|
||||
lowerBoundIPAddress: config.lower ?? '0.0.0.0',
|
||||
upperBoundIPAddress: config.upper ?? '0.0.0.0',
|
||||
gatewayIPAddress: config.gateway ?? '0.0.0.0',
|
||||
dnsServerIPAddress: config.dns ?? '0.0.0.0',
|
||||
useOwnSettings: config.own ?? false,
|
||||
staticAssignments: (config.staticAssignments ?? []).map(([macAddress, ipAddress], index) => ({
|
||||
id: `static-${index}`,
|
||||
macAddress,
|
||||
ipAddress,
|
||||
})),
|
||||
}),
|
||||
]),
|
||||
),
|
||||
dhcpClientConfigurationsByNodeId: new Map((scenario.dhcpClients ?? []).map((node) => [node, { isEnabled: true }])),
|
||||
switchConfigurationsByNodeId: new Map(
|
||||
Object.entries(scenario.switches ?? {}).map(([node, config]) => [
|
||||
node,
|
||||
@@ -156,6 +182,16 @@ function snapshotOf(scenario: Scenario): TopologySnapshot {
|
||||
|
||||
const upper = (id: string) => id.toUpperCase();
|
||||
|
||||
function dhcpStatusJson(status: DhcpClientStatus) {
|
||||
return {
|
||||
state: status.state,
|
||||
errors: status.errorCount,
|
||||
server: status.selectedServerIPAddress ?? null,
|
||||
offered: status.offeredIPAddress ?? null,
|
||||
succeeded: status.succeeded,
|
||||
};
|
||||
}
|
||||
|
||||
function traceJson(event: TraceEvent): Record<string, unknown> {
|
||||
return {
|
||||
id: event.id,
|
||||
@@ -315,6 +351,11 @@ function run(scenario: Scenario): Record<string, unknown> {
|
||||
case 'cleanTcp':
|
||||
results.push(engine.cleanClosedTcpSocket(step.socket!));
|
||||
break;
|
||||
case 'runDhcp': {
|
||||
const status = engine.runDhcpClient(step.node!);
|
||||
results.push(status === undefined ? null : dhcpStatusJson(status));
|
||||
break;
|
||||
}
|
||||
case 'closeSocket':
|
||||
engine.closeSocket(step.socket!);
|
||||
results.push(!engine.state.socketsById.has(step.socket!));
|
||||
@@ -339,6 +380,25 @@ function run(scenario: Scenario): Record<string, unknown> {
|
||||
Object.fromEntries([...table].map(([mac, port]) => [mac, upper(port)])),
|
||||
),
|
||||
icmpObservations: mapOf(state.icmpObservationsByNodeId, (items) => items.map(observationJson)),
|
||||
devices: Object.fromEntries(
|
||||
[...state.topologySnapshot.deviceConfigurations].map(([node, device]) => [
|
||||
upper(node),
|
||||
[device.ipAddress, device.subnetMask, device.defaultGateway, device.dnsServer],
|
||||
]),
|
||||
),
|
||||
dhcp: {
|
||||
clients: mapOf(state.dhcpClientStatusesByNodeId, dhcpStatusJson),
|
||||
leases: [...state.dhcpLeasesByIPAddress]
|
||||
.sort(([lhs], [rhs]) => (lhs < rhs ? -1 : 1))
|
||||
.map(([key, lease]) => [key, lease.clientMacAddress, lease.ipAddress, lease.expiresAtMilliseconds ?? null]),
|
||||
offers: [...state.dhcpOffersByIPAddress]
|
||||
.sort(([lhs], [rhs]) => (lhs < rhs ? -1 : 1))
|
||||
.map(([key, offer]) => [key, offer.clientMacAddress, offer.expiresAtMilliseconds]),
|
||||
blacklist: mapOf(state.dhcpBlacklistByServerNodeId, (entries) =>
|
||||
[...entries].sort(([lhs], [rhs]) => (lhs < rhs ? -1 : 1)).map(([address, expiry]) => [address, expiry]),
|
||||
),
|
||||
servers: mapOf(state.dhcpServerSocketIdsByNodeId, upper),
|
||||
},
|
||||
sockets: [...state.socketsById.values()]
|
||||
.sort((lhs, rhs) => (upper(lhs.id) < upper(rhs.id) ? -1 : 1))
|
||||
.map((socket) => ({
|
||||
@@ -378,7 +438,35 @@ const scenarioNames = readdirSync(scenarioDirectory)
|
||||
.map((name) => name.replace('.scenario.json', ''))
|
||||
.sort();
|
||||
|
||||
/**
|
||||
* Where the Swift engine is wrong, per scenario: its result corrected.
|
||||
*
|
||||
* dhcp-lan: a DHCP client run directly (not from the event queue) sends its
|
||||
* DISCOVER at once; the server's OFFER arrives within that send, and the
|
||||
* UDP delivery advances the client again — to FINISH, with the address set.
|
||||
* The outer run then writes back its stale copy of the status (Swift's
|
||||
* value types): DISCOVER, not succeeded. The address and every trace are
|
||||
* the same; only the reported status is wrong in Swift.
|
||||
*/
|
||||
const SWIFT_ERRORS: Record<string, (expected: Record<string, unknown>) => Record<string, unknown>> = {
|
||||
'dhcp-lan': (expected) => {
|
||||
const client = '00000000-0000-0000-0000-000000000102';
|
||||
const finished = { errors: 0, offered: '192.168.0.102', server: '192.168.0.10', state: 'FINISH', succeeded: true };
|
||||
const results = [...(expected.results as unknown[])];
|
||||
results[1] = finished;
|
||||
const dhcp = expected.dhcp as { clients: Record<string, unknown> };
|
||||
return { ...expected, results, dhcp: { ...dhcp, clients: { ...dhcp.clients, [client]: finished } } };
|
||||
},
|
||||
};
|
||||
|
||||
describe('same result as the Swift engine', () => {
|
||||
it('corrects Swift only where it errs', () => {
|
||||
for (const [name, correct] of Object.entries(SWIFT_ERRORS)) {
|
||||
const expected = JSON.parse(readFileSync(join(scenarioDirectory, `${name}.swift.json`), 'utf8')) as Record<string, unknown>;
|
||||
expect(JSON.stringify(correct(expected)), name).not.toBe(JSON.stringify(expected));
|
||||
}
|
||||
});
|
||||
|
||||
it('has scenarios with Swift results', () => {
|
||||
expect(scenarioNames.length).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -386,10 +474,8 @@ describe('same result as the Swift engine', () => {
|
||||
for (const name of scenarioNames) {
|
||||
it(name, () => {
|
||||
const scenario = JSON.parse(readFileSync(join(scenarioDirectory, `${name}.scenario.json`), 'utf8')) as Scenario;
|
||||
const expected = JSON.parse(readFileSync(join(scenarioDirectory, `${name}.swift.json`), 'utf8')) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const swift = JSON.parse(readFileSync(join(scenarioDirectory, `${name}.swift.json`), 'utf8')) as Record<string, unknown>;
|
||||
const expected = SWIFT_ERRORS[name]?.(swift) ?? swift;
|
||||
const actual = run(scenario);
|
||||
|
||||
// Traces first and one by one: the first difference is the one that matters.
|
||||
|
||||
Reference in New Issue
Block a user