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
197 changes: 196 additions & 1 deletion src/core/jsonrpc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import {
RequestError,
isJsonRpcMessage,
} from "./jsonrpc.js";
import type { AnyMessage, RequestResponder } from "./jsonrpc.js";
import type {
AnyMessage,
IncomingMessage,
RequestResponder,
} from "./jsonrpc.js";
import type { Stream } from "./stream.js";

type ConnectionInternals = {
Expand Down Expand Up @@ -887,6 +891,197 @@ describe("JSON-RPC connection rules", () => {
});
});

describe("JSON-RPC end of input", () => {
// A handler ahead of the ones that take the messages, like the typed ones
// the ACP connections register, defers their dispatch past the end of input.
const deferring = {
handleMessage: async (message: IncomingMessage) => {
await new Promise((resolve) => setTimeout(resolve, 0));
return Handled.no(message);
},
};

function receiving() {
const notification = vi.fn();
const request = vi.fn();
const builder = Connection.builder()
.withHandler(deferring)
.onReceiveNotification(
"example/last_notification",
(params) => params,
notification,
)
.onReceiveRequest("example/last_request", (params) => params, request);
return { builder, notification, request };
}

const lastNotification: AnyMessage = {
jsonrpc: "2.0",
method: "example/last_notification",
params: {},
};
const lastRequest: AnyMessage = {
jsonrpc: "2.0",
id: 1,
method: "example/last_request",
params: {},
};

// The peer sends its last messages and exits, closing its side.
async function endInput(peerStream: Stream, messages: AnyMessage[]) {
const writer = peerStream.writable.getWriter();
for (const message of messages) await writer.write(message);
await writer.close();
}

// Past the deferred dispatch of every message received so far.
function dispatchSettled() {
return new Promise((resolve) => setTimeout(resolve, 10));
}

it("dispatches notifications received before the peer ended its stream", async () => {
const [connectionStream, peerStream] = memoryStreamPair();
const { builder, notification } = receiving();
const connection = builder.connect(connectionStream);

await endInput(peerStream, [lastNotification]);
await connection.closed;

await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce());
});

it("dispatches notifications received before reading failed", async () => {
const { builder, notification } = receiving();
let sent = false;
const connection = builder.connect({
readable: new ReadableStream<AnyMessage>({
// The notification is read before reading fails.
pull(controller) {
if (sent) {
controller.error(new Error("read failed"));
} else {
sent = true;
controller.enqueue(lastNotification);
}
},
}),
writable: new WritableStream<AnyMessage>(),
});

await connection.closed;

await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce());
});

it("drops requests received before the peer ended its stream", async () => {
const [connectionStream, peerStream] = memoryStreamPair();
const { builder, notification, request } = receiving();
const connection = builder.connect(connectionStream);

// No response can reach the peer, so the request is not handled.
await endInput(peerStream, [lastRequest, lastNotification]);
await connection.closed;

await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce());
expect(request).not.toHaveBeenCalled();
});

it("keeps dispatching when closed after the peer ended its stream", async () => {
const [connectionStream, peerStream] = memoryStreamPair();
const { builder, notification } = receiving();
const connection = builder.connect(connectionStream);

await endInput(peerStream, [lastNotification]);
await connection.closed;
connection.close();

await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce());
});

it("keeps dispatching when connectWith ends after the peer ended its stream", async () => {
const [connectionStream, peerStream] = memoryStreamPair();
const { builder, notification } = receiving();
const result = builder.connectWith(
connectionStream,
() => new Promise<never>(() => {}),
);

await endInput(peerStream, [lastNotification]);
await expect(result).rejects.toThrow("ACP connection closed");

await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce());
});

it("keeps dispatching when a pending write fails after the peer ended its stream", async () => {
const { builder, notification } = receiving();
const write = Promise.withResolvers<void>();
let input!: ReadableStreamDefaultController<AnyMessage>;
const connection = builder.connect({
readable: new ReadableStream<AnyMessage>({
start(controller) {
input = controller;
},
}),
writable: new WritableStream<AnyMessage>({ write: () => write.promise }),
});

const sent = connection.sendNotification("example/outgoing", {});
input.enqueue(lastNotification);
input.close();
await connection.closed;
write.reject(new Error("write failed"));
await expect(sent).rejects.toThrow("write failed");

await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce());
});

it("logs errors of notifications dispatched after the peer ended its stream", async () => {
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => {});
const [connectionStream, peerStream] = memoryStreamPair();
const connection = Connection.builder()
.withHandler(deferring)
.onReceiveNotification(
"example/last_notification",
(params) => params,
() => {
throw new Error("handler failed");
},
)
.connect(connectionStream);

try {
await endInput(peerStream, [lastNotification]);
await connection.closed;

await vi.waitFor(() =>
expect(consoleError).toHaveBeenCalledWith(
"Error handling notification",
expect.objectContaining({ method: "example/last_notification" }),
),
);
} finally {
consoleError.mockRestore();
}
});

it("stops dispatching when the connection is closed locally", async () => {
const [connectionStream, peerStream] = memoryStreamPair();
const { builder, notification } = receiving();
const connection = builder.connect(connectionStream);
const writer = peerStream.writable.getWriter();

await writer.write(lastNotification);
connection.close();
await connection.closed;
await dispatchSettled();

expect(notification).not.toHaveBeenCalled();
writer.releaseLock();
});
});

describe("JSON-RPC malformed peer messages", () => {
it("does not print params of invalid or failed messages", async () => {
const secret = "SYNTHETIC_PRIVATE_CREDENTIAL";
Expand Down
61 changes: 53 additions & 8 deletions src/core/jsonrpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -723,13 +723,19 @@ export class ConnectionContext {

/**
* AbortSignal that aborts when the connection closes.
*
* Unless `close()` closed the connection, notifications received before it
* closed can still reach their handlers after the signal aborts.
*/
get signal(): AbortSignal {
return this.connection.signal;
}

/**
* Promise that resolves when the connection closes.
*
* Unless `close()` closed the connection, notifications received before it
* closed can still reach their handlers after this resolves.
*/
get closed(): Promise<void> {
return this.connection.closed;
Expand Down Expand Up @@ -771,6 +777,10 @@ export class Connection {
private retryQueue: IncomingMessage[] = [];
private context = new ConnectionContext(this);
private receiveReader?: ReadableStreamDefaultReader<AnyMessage>;
// Whether `close()` closed the connection. Otherwise the peer ended its
// stream, or reading or writing failed, and the notifications received
// before then are still dispatched: the peer sent them before it went away.
private closedLocally = false;

constructor(
requestHandler: RequestHandler,
Expand Down Expand Up @@ -860,7 +870,7 @@ export class Connection {
if (this.retryQueue.length > 0) {
for (const message of this.retryQueue.splice(0)) {
void this.processIncomingMessage(message).catch((error) =>
this.close(error),
this.shutdown(error),
);
}
}
Expand All @@ -871,13 +881,19 @@ export class Connection {

/**
* AbortSignal that aborts when the connection closes.
*
* Unless `close()` closed the connection, notifications received before it
* closed can still reach their handlers after the signal aborts.
*/
get signal(): AbortSignal {
return this.abortController.signal;
}

/**
* Promise that resolves when the connection closes.
*
* Unless `close()` closed the connection, notifications received before it
* closed can still reach their handlers after this resolves.
*/
get closed(): Promise<void> {
return this.closedPromise;
Expand Down Expand Up @@ -987,13 +1003,33 @@ export class Connection {
}

/**
* Closes the connection and rejects pending requests.
* Closes the connection and rejects pending requests. Messages received but
* not yet dispatched are dropped. Does nothing once the connection is closed.
*/
close(error?: unknown): void {
if (this.abortController.signal.aborted) {
return;
}

this.closedLocally = true;
this.shutdown(error);
}

/**
* Closes the connection because its peer closed, as when the peer ends its
* stream: notifications already received are still dispatched.
*
* @internal
*/
closeFromPeer(error?: unknown): void {
this.shutdown(error);
}

private shutdown(error?: unknown): void {
if (this.abortController.signal.aborted) {
return;
}

const closeError: unknown = error ?? new Error("ACP connection closed");
this.abortController.abort(closeError);
for (const pendingResponse of this.pendingResponses.values()) {
Expand Down Expand Up @@ -1071,7 +1107,7 @@ export class Connection {
} catch (error) {
closeError = error;
} finally {
this.close(closeError);
this.shutdown(closeError);
}
}

Expand Down Expand Up @@ -1121,7 +1157,7 @@ export class Connection {
this.handleProtocolNotification(message);
}
return this.processIncomingMessage(this.toIncomingMessage(message)).catch(
(error) => this.close(error),
(error) => this.shutdown(error),
);
} else if ("id" in message) {
this.handleResponse(message);
Expand All @@ -1132,10 +1168,19 @@ export class Connection {
return Promise.resolve();
}

// Once the connection is closed, a request can no longer be answered, so
// only notifications are still dispatched, unless `close()` closed it.
private dispatchStopped(message: IncomingMessage): boolean {
return (
this.abortController.signal.aborted &&
(this.closedLocally || message.kind === "request")
);
}

private async processIncomingMessage(
message: IncomingMessage,
): Promise<void> {
if (this.abortController.signal.aborted) {
if (this.dispatchStopped(message)) {
return;
}

Expand All @@ -1148,7 +1193,7 @@ export class Connection {
...this.dynamicHandlers.values(),
...this.fallbackHandlers,
]) {
if (this.abortController.signal.aborted) {
if (this.dispatchStopped(current)) {
return;
}

Expand All @@ -1171,7 +1216,7 @@ export class Connection {
);
}
} catch (error) {
if (this.abortController.signal.aborted) {
if (this.dispatchStopped(current)) {
return;
}

Expand Down Expand Up @@ -1304,7 +1349,7 @@ export class Connection {
}
})
.catch((error) => {
this.close(error);
this.shutdown(error);
throw error;
});
return this.writeQueue;
Expand Down
Loading
Loading