Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import http from 'node:http';
import net from 'node:net';
import path from 'node:path';
import { spawn, type ChildProcess } from 'node:child_process';
import { fileURLToPath } from 'node:url';
Expand Down Expand Up @@ -70,43 +69,36 @@ let server: StdioClientHandle;
let targets: Target[] = [];
const call = <T extends ToolAnswer = ToolAnswer>(name: string, args: Record<string, unknown> = {}): Promise<T> => server.call<T>(name, args);

async function getFreePort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, '127.0.0.1', () => {
const address = probe.address();
const port = typeof address === 'object' && address ? address.port : 0;
probe.close(() => (port ? resolve(port) : reject(new Error('no free port'))));
});
probe.on('error', reject);
});
}

/** Start a server fixture under `node --inspect` and wait for the port it prints. */
/** Start a server fixture under `node --inspect=127.0.0.1:0` and read both kernel-assigned ports. */
async function startTarget(script: string): Promise<Target> {
const inspectPort = await getFreePort();
const proc = spawn(process.execPath, [`--inspect=127.0.0.1:${inspectPort}`, script], {
const proc = spawn(process.execPath, ['--inspect=127.0.0.1:0', script], {
cwd: path.dirname(script),
windowsHide: true,
stdio: ['ignore', 'pipe', 'pipe']
});
let buffer = '';
const target: Target = { proc, inspectPort, httpPort: 0 };
const target: Target = { proc, inspectPort: 0, httpPort: 0 };
// Register before readiness so afterEach also cleans up a failed startup.
targets.push(target);
target.httpPort = await new Promise<number>((resolve, reject) => {
const ports = await new Promise<{ inspectPort: number; httpPort: number }>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`the server did not print its port: ${buffer}`)), 30000);
const onData = (chunk: Buffer) => {
buffer += chunk.toString();
const listening = /listening (\d+)/.exec(buffer);
const inspector = /Debugger listening on ws:\/\/127\.0\.0\.1:(\d+)\//.exec(buffer);
// The inspector's own banner goes to stderr first; wait for both.
if (listening && buffer.includes('Debugger listening on')) { clearTimeout(timer); resolve(Number(listening[1])); }
if (listening && inspector) {
clearTimeout(timer);
resolve({ inspectPort: Number(inspector[1]), httpPort: Number(listening[1]) });
}
};
proc.stdout!.on('data', onData);
proc.stderr!.on('data', onData);
proc.on('error', (error) => { clearTimeout(timer); reject(error); });
proc.on('exit', (code) => { clearTimeout(timer); reject(new Error(`the server exited ${code} before listening: ${buffer}`)); });
});
target.inspectPort = ports.inspectPort;
target.httpPort = ports.httpPort;
return target;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import path from 'node:path';
import net from 'node:net';
import { spawn, type ChildProcess } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { startStdioClient, type StdioClientHandle, type ToolAnswer } from '../../../test-utils/helpers/mcp-stdio-client.js';
Expand Down Expand Up @@ -81,37 +80,25 @@ async function pollUntil<T>(read: () => Promise<T>, accept: (value: T) => boolea
return last;
}

async function getFreePort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, '127.0.0.1', () => {
const address = probe.address();
const port = typeof address === 'object' && address ? address.port : 0;
probe.close(() => (port ? resolve(port) : reject(new Error('no free port'))));
});
probe.on('error', reject);
});
}

/** Start a script under `node --inspect` and wait until its inspector listens. */
/** Start a script under `node --inspect=127.0.0.1:0` and read the kernel-assigned inspector port. */
async function startTarget(script: string): Promise<Target> {
const port = await getFreePort();
const proc = spawn(process.execPath, [`--inspect=127.0.0.1:${port}`, script], {
const proc = spawn(process.execPath, ['--inspect=127.0.0.1:0', script], {
cwd: treeDir,
windowsHide: true,
stdio: ['pipe', 'pipe', 'pipe']
});
let buffer = '';
// close also waits for the output pipes, so the exit assertions see the final lines.
const exited = new Promise<number | null>((resolve) => proc.on('close', (code) => resolve(code)));
const target: Target = { proc, port, output: () => buffer, exited, go: (mode = 'go') => { proc.stdin!.write(`${mode}\n`); } };
const target: Target = { proc, port: 0, output: () => buffer, exited, go: (mode = 'go') => { proc.stdin!.write(`${mode}\n`); } };
// Register before readiness so afterEach also cleans up a failed startup.
targets.push(target);
await new Promise<void>((resolve, reject) => {
target.port = await new Promise<number>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`node --inspect not listening: ${buffer}`)), 30000);
const onData = (chunk: Buffer) => {
buffer += chunk.toString();
if (buffer.includes('Debugger listening on')) { clearTimeout(timer); resolve(); }
const match = /Debugger listening on ws:\/\/127\.0\.0\.1:(\d+)\//.exec(buffer);
if (match) { clearTimeout(timer); resolve(Number(match[1])); }
};
proc.stdout!.on('data', onData);
proc.stderr!.on('data', onData);
Expand Down
25 changes: 23 additions & 2 deletions tests/adapters/python/integration/python-subprocess-attach.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,16 @@ interface Target { proc: ChildProcess; port: number; output: () => string; exite

let targets: Target[] = [];

const PORT_IN_USE_PATTERN = /Address already in use|EADDRINUSE|10048/i;

/**
* Start attach_parent.py under `python -m debugpy --listen` and wait for its
* READY line. No TCP probe: a session-less connect makes the adapter exit
* (docs/python/spike-notes-subprocess.md), and the script prints READY after
* debugpy has its listener up.
* debugpy has its listener up. Retries if a parallel test grabs the ephemeral
* port between `getFreePort()` closing its probe socket and `debugpy` binding.
*/
async function startTarget(extraArgs: string[] = []): Promise<Target> {
async function startTargetOnce(extraArgs: string[] = []): Promise<Target> {
const port = await getFreePort();
const proc = spawn(PYTHON, ['-m', 'debugpy', '--listen', `127.0.0.1:${port}`, ...extraArgs, attachParent], {
cwd: treeDir,
Expand All @@ -129,6 +132,24 @@ async function startTarget(extraArgs: string[] = []): Promise<Target> {
return target;
}

async function startTarget(extraArgs: string[] = []): Promise<Target> {
const maxAttempts = 4;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await startTargetOnce(extraArgs);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (attempt < maxAttempts && PORT_IN_USE_PATTERN.test(message)) {
const failed = targets.pop();
if (failed && failed.proc.exitCode === null) failed.proc.kill();
continue;
}
throw error;
}
}
throw new Error('unreachable');
}

/** The target's exit, with its own pipe's last lines: the proof that nothing killed it. */
async function targetRanToItsEnd(target: Target): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined;
Expand Down
Loading