Files
Shade/packages/shade-transfer/tests/ws-fallback.test.ts
Sterister 53ce776c02 test: stop guessing port numbers
Twenty test servers picked a port with `NNNN + Math.floor(Math.random() * 500)`
and hoped it was free. Several files guessed inside the *same* range —
sdk.test.ts and gates.test.ts both on 19500, three files on 22000, and
webrtc-integration.test.ts used 22000 twice within itself — so with test files
serving in parallel the collision was not unlikely, it was scheduled.

Found from the outside, in Nova, where Shade is vendored: across eight runs of
an unchanged tree, two had failures and six were clean. The visible error was

    Failed to start server. Is port 24287 in use?  EADDRINUSE

and then a second, louder one: `teardownRig` ran on a rig that setup had never
finished building and died on `rig.alice`, so the TypeError from cleanup is
what you read first and the real cause scrolled past above it.

`Bun.serve({ port: 0 })` lets the OS hand out a free port and `server.port`
reads it back. There is no range to collide inside.

teardownRig now tolerates a rig that was never built. Cleanup must never be the
loudest thing in a failing test.

A suite that fails a quarter of the time is worse than a suite that fails: it
teaches everyone to re-run it, and then a real regression looks like the flake.

Verified: 1198 pass / 0 fail here, and the same fix is going into Nova's
vendored copy so the next sync does not bring the guessing back.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014489bKUtUEY1Zgs9xN9mt7
2026-09-08 16:33:40 +02:00

103 lines
3.4 KiB
TypeScript

import { describe, test, expect, afterAll } from 'bun:test';
import { SubtleCryptoProvider } from '@shade/crypto-web';
import { sha256Once } from '@shade/streams';
import {
TransferEngine,
MemoryControlChannel,
ShadeTransferHttpTransport,
ShadeTransferWsTransport,
FallbackTransferTransport,
createTransferRoutes,
type TransferHandle,
type TransferResult,
} from '../src/index.js';
const crypto = new SubtleCryptoProvider();
function hex(b: Uint8Array): string {
return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
}
const cleanups: Array<() => void> = [];
afterAll(() => {
for (const c of cleanups) c();
});
describe('WS opt-in transport with HTTP fallback', () => {
test('WS connect failure → falls back to HTTP transparently', async () => {
const { a: ctrlA, b: ctrlB } = MemoryControlChannel.linked('alice', 'bob');
const receiverEngine = new TransferEngine({
crypto,
controlChannel: ctrlB,
transport: {
probe: async () => undefined,
sendChunk: async () => {
throw new Error('not used');
},
fetchResumeState: async () => null,
},
myAddress: 'bob',
});
const httpApp = await createTransferRoutes(receiverEngine);
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
// range and hoped — and several files here guessed inside the SAME range,
// so with test files serving in parallel the collision arrived about a
// quarter of the time as EADDRINUSE.
const httpServer = Bun.serve({ port: 0, fetch: httpApp.fetch });
const httpPort = httpServer.port;
const httpBaseUrl = `http://localhost:${httpPort}`;
cleanups.push(() => httpServer.stop());
const ws = new ShadeTransferWsTransport({
// Resolve to a closed port — guaranteed connect failure.
resolveWsUrl: async () => `ws://127.0.0.1:1`,
connectTimeoutMs: 500,
});
const http = new ShadeTransferHttpTransport({
resolveBaseUrl: async () => httpBaseUrl,
authenticator: {
signChunk: async () => ({ 'X-Shade-Sender-Address': 'alice' }),
signControl: async () => ({ 'X-Shade-Sender-Address': 'alice' }),
},
});
const fallback = new FallbackTransferTransport(ws, http);
const senderEngine = new TransferEngine({
crypto,
controlChannel: ctrlA,
transport: fallback,
myAddress: 'alice',
});
cleanups.push(() => senderEngine.destroy());
cleanups.push(() => receiverEngine.destroy());
let resolveRecv!: (h: TransferHandle) => void;
const recvHandlePromise = new Promise<TransferHandle>((r) => {
resolveRecv = r;
});
receiverEngine.onIncomingTransfer(async (incoming) => {
const h = await incoming.accept({ output: { kind: 'buffer' } });
resolveRecv(h);
});
const input = crypto.randomBytes(64 * 1024);
const handle = await senderEngine.upload({
to: 'bob',
input,
lanes: 2,
chunkSize: 8 * 1024,
});
const recvHandle = await recvHandlePromise;
const [senderResult, recvResult] = await Promise.all([
handle.done(),
recvHandle.done(),
]);
expect(fallback.fellBack).toBe(true);
const received =
(recvResult as TransferResult & { bytes?: Uint8Array }).bytes ?? new Uint8Array();
expect(received).toEqual(input);
expect(senderResult.sha256).toBe(hex(sha256Once(input)));
});
});