Skip to content
Draft
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
37 changes: 37 additions & 0 deletions services/companion/src/server.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { SessionCreatedSchema } from "@webchain/protocol";
import type { BrowserRuntime } from "@webchain/runtime";
import { WebchainRuntimeError } from "@webchain/runtime";
import { describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { createCompanionApp } from "./server.js";

function parseApiError(res: { body: string }) {
Expand Down Expand Up @@ -388,6 +390,41 @@ describe("createCompanionApp", () => {
await app.close();
});

it("rolls back created session when response validation fails", async () => {
const runtime = mockRuntime({
createSession: vi.fn(async () => ({
sessionId: "sid-rollback",
pageId: "pid-1",
createdAt: new Date().toISOString(),
})),
});
const { app } = await createCompanionApp({
runtime,
logger: false,
localToken: "tok",
});

const parseSpy = vi
.spyOn(SessionCreatedSchema, "parse")
.mockImplementation(() => {
throw new z.ZodError([]);
});

const res = await app.inject({
method: "POST",
url: "/sessions",
headers: { "x-webchain-token": "tok" },
});

parseSpy.mockRestore();
expect(res.statusCode).toBe(400);
expect(runtime.closeSession).toHaveBeenCalledWith({
action: "closeSession",
sessionId: "sid-rollback",
});
await app.close();
});

it("returns 503 when runtime reports missing browsers", async () => {
const runtime = mockRuntime({
createSession: vi.fn(async () => {
Expand Down
10 changes: 10 additions & 0 deletions services/companion/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,10 @@ export async function createCompanionApp(

app.post("/sessions", async (_request, reply) => {
const trace = createTraceContext();
let createdSessionId: string | undefined;
try {
const session = await options.runtime.createSession();
createdSessionId = session.sessionId;
const parsedSession = SessionCreatedSchema.parse(session);
return SessionCreatedResponseSchema.parse({
...parsedSession,
Expand All @@ -173,6 +175,14 @@ export async function createCompanionApp(
),
});
} catch (error) {
if (createdSessionId) {
await options.runtime
.closeSession({
action: "closeSession",
sessionId: createdSessionId,
})
.catch(() => {});
}
return sendRuntimeFailure(reply, error, trace);
}
});
Expand Down
Loading