Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/lsp/__serial__/client.test.ts

Raw
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { Client } from "../src/client.ts";
import { normalize } from "../src/result.ts";
import { bounded, LspFailure } from "../src/source.ts";
import { peer } from "./peer.ts";

const owned: Client[] = [];
const directories: string[] = [];
afterEach(async () => {
	await Promise.all(owned.splice(0).map((client) => client.close()));
	await Promise.all(
		directories
			.splice(0)
			.map((directory) => rm(directory, { recursive: true, force: true })),
	);
});

async function setup(mode = "normal") {
	const root = await mkdtemp(join(tmpdir(), "pi-lsp-peer-"));
	directories.push(root);
	const file = join(root, "main.go");
	await writeFile(file, "package fixture\nvar Value = 1\n");
	const client = new Client(root, await peer(root, mode), process.execPath);
	owned.push(client);
	return { root, file, client };
}

function signal(ms = 3000) {
	return AbortSignal.timeout(ms);
}

it("honors configuration, denies edits, syncs external managed/unopened changes and versions", async () => {
	const { root, file, client } = await setup();
	const dependency = join(root, "dep.go");
	await writeFile(dependency, "package fixture\nvar Dependency = 1\n");
	const first = (await client.query("hover", file, 2, 5, signal())) as {
		contents: string;
	};
	const state = JSON.parse(first.contents);
	expect(state.configuration).toEqual([{ marker: "normal" }]);
	expect(state.denied).toMatchObject({ applied: false });
	expect(state.commandDenied).toBe(true);
	expect(state.registered).toBe(false);
	expect(await readFile(file, "utf8")).toBe("package fixture\nvar Value = 1\n");
	expect(state.documents[0][1]).toMatchObject({
		version: 1,
		text: "package fixture\nvar Value = 1\n",
	});
	await writeFile(file, "package fixture\nvar Other = 2\n");
	await writeFile(dependency, "package fixture\nvar Dependency = 2\n");
	const second = JSON.parse(
		(
			(await client.query("hover", file, 2, 5, signal())) as {
				contents: string;
			}
		).contents,
	);
	expect(second.documents[0][1]).toMatchObject({
		version: 2,
		text: "package fixture\nvar Other = 2\n",
	});
	expect(second.changes).toContainEqual({
		uri: new URL(`file://${dependency}`).href,
		type: 2,
	});
	await rm(dependency);
	const third = JSON.parse(
		(
			(await client.query("hover", file, 2, 5, signal())) as {
				contents: string;
			}
		).contents,
	);
	expect(third.changes).toContainEqual({
		uri: new URL(`file://${dependency}`).href,
		type: 3,
	});
});

it("isolates process state by root/config and rejects unsupported capability", async () => {
	const a = await setup();
	const b = await setup("unsupported");
	const first = JSON.parse(
		(
			(await a.client.query("hover", a.file, 2, 5, signal())) as {
				contents: string;
			}
		).contents,
	);
	const other = JSON.parse(
		(
			(await b.client.query("hover", b.file, 2, 5, signal())) as {
				contents: string;
			}
		).contents,
	);
	expect(first.pid).not.toBe(other.pid);
	expect(other.configuration).toEqual([{ marker: "unsupported" }]);
	for (const operation of [
		"definition",
		"type_definition",
		"implementations",
	] as const) {
		await expect(
			b.client.query(operation, b.file, 2, 5, signal()),
		).rejects.toMatchObject({ status: "unsupported" });
	}
});

it("preserves application error code zero and malformed-result failure boundaries", async () => {
	const failing = await setup("error");
	await expect(
		failing.client.query("definition", failing.file, 2, 5, signal()),
	).rejects.toMatchObject({ code: 0, message: "application failure" });
	const malformed = await setup("malformed");
	const raw = await malformed.client.query(
		"definition",
		malformed.file,
		2,
		5,
		signal(),
	);
	await expect(
		normalize(
			malformed.client,
			"definition",
			malformed.file,
			raw,
			10,
			2048,
			signal(),
		),
	).rejects.toMatchObject({ status: "server_failure" });
});

it("rejects a cross-file selection when query source changes after directory observation", async () => {
	const { root, file, client } = await setup("ambiguous-cross");
	await mkdir(join(root, "nested"));
	await writeFile(
		join(root, "nested/other.go"),
		"package fixture\nvar Other = 1\n",
	);
	const ready = (await client.query(
		"incoming_calls",
		file,
		2,
		5,
		signal(),
	)) as { candidates: { selection: string }[] };
	const selection = ready.candidates[1]?.selection;
	if (!selection) throw new Error("Missing cross-file candidate");
	// Control the filesystem race; assert the public query outcome, not internal call counts.
	const observing = client as unknown as {
		observe(file: string, signal: AbortSignal): Promise<void>;
	};
	const observe = observing.observe.bind(client);
	const barrier = vi
		.spyOn(observing, "observe")
		.mockImplementationOnce(async (path, abort) => {
			await observe(path, abort);
			await writeFile(file, "package fixture\nvar Value = 2\n");
		});
	try {
		await expect(
			client.query(
				"incoming_calls",
				file,
				2,
				5,
				signal(),
				undefined,
				selection,
			),
		).rejects.toMatchObject({ status: "stale_selection" });
	} finally {
		barrier.mockRestore();
	}
});

it("settles cancellation locally and ignores a late successful reply", async () => {
	const { client, file } = await setup("delay");
	await client.query("hover", file, 2, 5, signal());
	const controller = new AbortController();
	const reason = new LspFailure("cancelled", "cancelled");
	const started = performance.now();
	const work = client.query("definition", file, 2, 5, controller.signal);
	setTimeout(() => controller.abort(reason), 25);
	await expect(work).rejects.toBe(reason);
	expect(performance.now() - started).toBeLessThan(500);
	await new Promise((resolve) => setTimeout(resolve, 250));
	const later = await client.query("references", file, 2, 5, signal());
	expect(later).toEqual([]);
});

it("bounds initialize wait and escalates stubborn cleanup with actual process exit", async () => {
	const { client, file } = await setup("init-hang");
	await expect(
		client.query("definition", file, 2, 5, signal(50)),
	).rejects.toBeDefined();
	await client.close();
	await client.exited;
	expect(
		client.child.exitCode !== null || client.child.signalCode !== null,
	).toBe(true);
	const stubborn = await setup("stubborn");
	await stubborn.client.query("hover", stubborn.file, 2, 5, signal());
	const start = performance.now();
	await stubborn.client.close();
	expect(performance.now() - start).toBeLessThan(1500);
	await stubborn.client.exited;
	expect(
		stubborn.client.child.exitCode !== null ||
			stubborn.client.child.signalCode !== null,
	).toBe(true);
	if (process.platform !== "win32")
		expect(stubborn.client.child.signalCode).toBe("SIGKILL");
});

it("reaps a stubborn peer even when the protocol connection is already disposed", async () => {
	const { client, file } = await setup("stubborn");
	await client.query("hover", file, 2, 5, signal());
	client.connection.dispose();
	const start = performance.now();
	await client.close();
	await client.exited;
	expect(performance.now() - start).toBeLessThan(1500);
	expect(
		client.child.exitCode !== null || client.child.signalCode !== null,
	).toBe(true);
	if (process.platform !== "win32")
		expect(client.child.signalCode).toBe("SIGKILL");
});

it.each(["flood", "partial"])(
	"terminates %s transport without implementing protocol framing",
	async (mode) => {
		const { client, file } = await setup(mode);
		await expect(
			bounded(client.query("definition", file, 2, 5, signal()), signal()),
		).rejects.toBeDefined();
		await client.close();
		expect(
			client.child.exitCode !== null || client.child.signalCode !== null,
		).toBe(true);
	},
);