diff --git a/src/build-format.test.ts b/src/build-format.test.ts new file mode 100644 index 0000000..c56ec90 --- /dev/null +++ b/src/build-format.test.ts @@ -0,0 +1,277 @@ +import { + assert, + assertEquals, + assertMatch, + assertRejects, + assertStringIncludes, +} from "@std/assert"; +import { delay } from "@std/async/delay"; +import { join } from "@std/path"; +import { describe, it } from "@std/testing/bdd"; +import { stub } from "@std/testing/mock"; + +import { Builder } from "@udibo/juniper/build"; + +type Entrypoint = "server" | "client"; + +const routeName = (index: number) => + `route_${String(index).padStart(4, "0")}_${"segment".repeat(10)}`; + +async function withRoutes( + count: number, + run: (builder: Builder) => Promise, +): Promise { + const projectRoot = await Deno.makeTempDir({ prefix: "juniper formatter " }); + try { + const routes = join(projectRoot, "routes"); + await Deno.mkdir(routes); + await Deno.writeTextFile(join(projectRoot, "deno.json"), "{}"); + for (let index = 0; index < count; index++) { + const name = routeName(index); + await Deno.writeTextFile( + join(routes, `${name}.ts`), + `export const loader = () => ({ index: ${index} });\n`, + ); + await Deno.writeTextFile( + join(routes, `${name}.tsx`), + "export default function Route() { return null; }\n", + ); + } + await using builder = new Builder({ projectRoot }); + await run(builder); + } finally { + await Deno.remove(projectRoot, { recursive: true }); + } +} + +async function closeChild( + child: Deno.ChildProcess, + pending: boolean, + settled: Promise, +): Promise { + try { + if (pending) child.kill("SIGTERM"); + } catch (error) { + if (!(error instanceof Deno.errors.NotFound)) throw error; + } + await child.status; + await settled; + if (!child.stdout.locked) await child.stdout.cancel(); + try { + if (!child.stderr.locked) await child.stderr.cancel(); + } catch (error) { + if (!(error instanceof TypeError)) throw error; + } +} + +async function generate( + builder: Builder, + entrypoint: Entrypoint, + options: { + malformedInput?: boolean; + rejectInput?: "write" | "close"; + rejectOutput?: "stdout" | "stderr"; + } = {}, +): Promise { + const children: Deno.ChildProcess[] = []; + const pending = new Set(); + const inputObservers: Disposable[] = []; + const forwarding: Promise[] = []; + const inputGate = options.rejectOutput ? Promise.withResolvers() : null; + const killSignals: Deno.Signal[] = []; + const spawn = Deno.Command.prototype.spawn; + using _observer = stub( + Deno.Command.prototype, + "spawn", + function (this: Deno.Command) { + const child = spawn.call(this); + children.push(child); + pending.add(child); + void child.status.then(() => pending.delete(child)); + if (options.rejectOutput) { + const output = options.rejectOutput; + const failed = new TransformStream({ + start(controller) { + controller.error(new Error(`owned ${output} read failure`)); + }, + }); + forwarding.push(child[output].pipeTo(failed.writable).catch(() => {})); + const getWriter = child.stdin.getWriter.bind(child.stdin); + inputObservers.push(stub(child.stdin, "getWriter", () => { + const writer = getWriter(); + const write = writer.write.bind(writer); + inputObservers.push(stub(writer, "write", async (chunk) => { + await inputGate!.promise; + await write(chunk); + })); + return writer; + })); + const kill = child.kill.bind(child); + return new Proxy(child, { + get(target, property) { + if (property === output) return failed.readable; + if (property === "kill") { + return (signal: Deno.Signal) => { + killSignals.push(signal); + try { + kill(signal); + } finally { + inputGate!.resolve(); + } + }; + } + const value = Reflect.get(target, property, target); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + } + if (options.rejectInput || options.malformedInput) { + const getWriter = child.stdin.getWriter.bind(child.stdin); + inputObservers.push(stub(child.stdin, "getWriter", () => { + const writer = getWriter(); + if (options.malformedInput) { + const write = writer.write.bind(writer); + inputObservers.push( + stub( + writer, + "write", + () => + write(new TextEncoder().encode("export const broken = ;\n")), + ), + ); + return writer; + } + const reject = () => { + const result = Promise.reject( + new Error(`owned stdin ${options.rejectInput} failure`), + ); + void result.catch(() => {}); + return result; + }; + inputObservers.push(stub(writer, options.rejectInput!, reject)); + return writer; + })); + } + return child; + }, + ); + const containment = new AbortController(); + const operation = entrypoint === "server" + ? builder.buildMainServerEntrypoint() + : builder.buildMainClientEntrypoint(); + let failure: unknown; + const settled = operation.catch((error) => { + failure = error; + }); + try { + const outcome = await Promise.race([ + settled.then(() => "settled"), + delay(10_000, { signal: containment.signal }).then(() => "deadline"), + ]); + assertEquals(outcome, "settled", "the owned formatter must finish"); + } finally { + containment.abort(); + inputGate?.resolve(); + for (const child of children) { + await closeChild(child, pending.has(child), settled); + } + await settled; + await Promise.all(forwarding); + for (const inputObserver of inputObservers.reverse()) { + inputObserver[Symbol.dispose](); + } + } + assertEquals(children.length, 1); + assertEquals(pending.size, 0); + if (options.rejectOutput) assertEquals(killSignals, ["SIGTERM"]); + if (failure) throw failure; +} + +describe("Builder formatter ownership", () => { + for (const entrypoint of ["server", "client"] as const) { + for (const count of [2, 512]) { + it(`${entrypoint} generation formats all ${count} actual route pairs`, async () => { + await withRoutes(count, async (builder) => { + await generate(builder, entrypoint); + const artifact = await Deno.readTextFile( + entrypoint === "server" ? builder.serverPath : builder.clientPath, + ); + assertStringIncludes(artifact, routeName(0)); + assertStringIncludes(artifact, routeName(count - 1)); + assertEquals((artifact.match(/\bpath:/g) ?? []).length, count + 1); + assertStringIncludes( + artifact, + entrypoint === "server" ? "createServer" : "new Client", + ); + }); + }); + } + } +}); + +describe("Builder formatter failure ownership", () => { + for (const entrypoint of ["server", "client"] as const) { + it(`${entrypoint} preserves genuine formatter diagnostics and an existing artifact on nonzero exit`, async () => { + await withRoutes(2, async (builder) => { + const artifactPath = entrypoint === "server" + ? builder.serverPath + : builder.clientPath; + await Deno.writeTextFile(artifactPath, "existing artifact\n"); + const error = await assertRejects( + () => + generate(builder, entrypoint, { + malformedInput: true, + }), + Error, + `Failed to format generated main ${entrypoint} file: 1`, + ); + assert(error.cause instanceof Error); + assertMatch(error.cause.message, /Syntax\s?Error/i); + assertEquals( + await Deno.readTextFile(artifactPath), + "existing artifact\n", + ); + }); + }); + + for (const rejectOutput of ["stdout", "stderr"] as const) { + it(`${entrypoint} terminates and joins the formatter after a ${rejectOutput} read failure`, async () => { + await withRoutes(2, async (builder) => { + const artifactPath = entrypoint === "server" + ? builder.serverPath + : builder.clientPath; + await Deno.writeTextFile(artifactPath, "existing artifact\n"); + await assertRejects( + () => generate(builder, entrypoint, { rejectOutput }), + Error, + `owned ${rejectOutput} read failure`, + ); + assertEquals( + await Deno.readTextFile(artifactPath), + "existing artifact\n", + ); + }); + }); + } + + for (const rejectInput of ["write", "close"] as const) { + it(`${entrypoint} joins formatter resources after an input ${rejectInput} failure`, async () => { + await withRoutes(2, async (builder) => { + const artifactPath = entrypoint === "server" + ? builder.serverPath + : builder.clientPath; + await Deno.writeTextFile(artifactPath, "existing artifact\n"); + await assertRejects( + () => generate(builder, entrypoint, { rejectInput }), + Error, + `owned stdin ${rejectInput} failure`, + ); + assertEquals( + await Deno.readTextFile(artifactPath), + "existing artifact\n", + ); + }); + }); + } + } +}); diff --git a/src/build.ts b/src/build.ts index e23151e..7c404fd 100644 --- a/src/build.ts +++ b/src/build.ts @@ -35,8 +35,61 @@ const fmtCommand = new Deno.Command(Deno.execPath(), { args: ["fmt", "-"], stdin: "piped", stdout: "piped", + stderr: "piped", }); +async function formatEntrypoint( + contents: string, + entrypoint: "server" | "client", +): Promise { + const fmt = fmtCommand.spawn(); + const writer = fmt.stdin.getWriter(); + let exited = false; + const status = fmt.status.finally(() => { + exited = true; + }); + const stopOnReadFailure = (error: unknown): never => { + if (!exited) { + try { + fmt.kill("SIGTERM"); + } catch (killError) { + if (!(killError instanceof Deno.errors.NotFound)) throw killError; + } + } + throw error; + }; + const stdout = toText(fmt.stdout).catch(stopOnReadFailure); + const stderr = toText(fmt.stderr).catch(stopOnReadFailure); + const input = (async () => { + try { + await writer.write(new TextEncoder().encode(contents)); + await writer.close(); + } catch (error) { + await writer.abort(error).catch(() => {}); + throw error; + } finally { + writer.releaseLock(); + } + })(); + const [inputResult, statusResult, stdoutResult, stderrResult] = await Promise + .allSettled([input, status, stdout, stderr]); + if (stdoutResult.status === "rejected") throw stdoutResult.reason; + if (stderrResult.status === "rejected") throw stderrResult.reason; + if (statusResult.status === "rejected") throw statusResult.reason; + const diagnostics = new TextEncoder().encode(stderrResult.value); + for (let offset = 0; offset < diagnostics.length;) { + offset += await Deno.stderr.write(diagnostics.subarray(offset)); + } + if (!statusResult.value.success) { + throw new Error( + `Failed to format generated main ${entrypoint} file: ${statusResult.value.code}`, + { cause: new Error(stderrResult.value.trimEnd()) }, + ); + } + if (inputResult.status === "rejected") throw inputResult.reason; + return stdoutResult.value; +} + function toPosixPath(value: string): string { return value.replace(/\\/g, "/"); } @@ -363,10 +416,8 @@ export class Builder implements AsyncDisposable { 1, ); - const fmt = fmtCommand.spawn(); - const fmtWriter = fmt.stdin.getWriter(); - const encoder = new TextEncoder(); - fmtWriter.write(encoder.encode(`\ + const contents = await formatEntrypoint( + `\ // This file is auto-generated by @udibo/juniper/build // Do not edit this file directly. @@ -379,14 +430,9 @@ export const server = createServer(import.meta.url, client, ${routesConfigString if (import.meta.main) { Deno.serve(server.fetch); } -`)); - fmtWriter.close(); - const { success, code } = await fmt.status; - if (!success) { - throw new Error(`Failed to format generated main server file: ${code}`); - } - - const contents = await toText(fmt.stdout); +`, + "server", + ); await deno.writeTextFile(this.serverPath, contents); }); } @@ -454,24 +500,17 @@ if (import.meta.main) { 1, ); - const fmt = fmtCommand.spawn(); - const fmtWriter = fmt.stdin.getWriter(); - const encoder = new TextEncoder(); - fmtWriter.write(encoder.encode(`\ + const contents = await formatEntrypoint( + `\ // This file is auto-generated by @udibo/juniper/build // Do not edit this file directly. import { Client } from "@udibo/juniper/client"; export const client = new Client(${routesConfigString}); -`)); - fmtWriter.close(); - const { success, code } = await fmt.status; - if (!success) { - throw new Error(`Failed to format generated main client file: ${code}`); - } - - const contents = await toText(fmt.stdout); +`, + "client", + ); await deno.writeTextFile(this.clientPath, contents); }); }