Skip to content
Open
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 @@ -3,15 +3,19 @@
// daemon spawns real PTYs via node-pty.

import { strict as assert } from "node:assert";
import { once } from "node:events";
import { mkdtempSync, rmSync } from "node:fs";
import * as net from "node:net";
import * as os from "node:os";
import * as path from "node:path";
import { after, before, test } from "node:test";
import { Server } from "@superset/pty-daemon";
import {
type ClientMessage,
CURRENT_PROTOCOL_VERSION,
encodeFrame,
FrameDecoder,
type ListMessage,
} from "@superset/pty-daemon/protocol";
import { TerminalModes } from "@superset/pty-daemon/terminal-modes";
import { DaemonClient, DaemonUnavailableError } from "./DaemonClient.ts";
Expand Down Expand Up @@ -405,6 +409,126 @@ test("adoption flow: client A opens, drops, client B finds + subscribes-with-rep
await b.dispose();
});

test(
"a timed-out list reply cannot settle the next list request",
{ timeout: 5000 },
async (t) => {
const socketDir = mkdtempSync(path.join(os.tmpdir(), "paradev-list-"));
const socketPath = path.join(socketDir, "daemon.sock");
const firstRequest = Promise.withResolvers<ListMessage>();
const secondRequest = Promise.withResolvers<{
message: ListMessage;
socket: net.Socket;
}>();
let count = 0;
const fake = net.createServer((socket) => {
const decoder = new FrameDecoder();
socket.on("data", (chunk) => {
decoder.push(chunk);
for (const frame of decoder.drain()) {
const message = frame.message as ClientMessage;
if (message.type === "hello") {
socket.write(
encodeFrame({
type: "hello-ack",
protocol: CURRENT_PROTOCOL_VERSION,
daemonVersion: "test",
supportsListRequestIds: true,
}),
);
} else if (message.type === "list") {
if (++count === 1) firstRequest.resolve(message);
else secondRequest.resolve({ message, socket });
}
}
});
});
const client = new DaemonClient({ socketPath });
const cancelled = Promise.withResolvers<never>();
const cancel = () =>
cancelled.reject(t.signal.reason ?? new Error("Fixture closed"));
void cancelled.promise.catch(() => {});
t.signal.addEventListener("abort", cancel, { once: true });
const wait = <T>(promise: Promise<T>) =>
Promise.race([promise, cancelled.promise]);
try {
t.signal.throwIfAborted();
await once(fake.listen(socketPath), "listening", { signal: t.signal });
await client.connect();
t.signal.throwIfAborted();
t.mock.timers.enable({ apis: ["setTimeout"] });
const [first] = await wait(
Promise.all([
firstRequest.promise.then((message) => {
t.mock.timers.runAll();
return message;
}),
assert.rejects(client.list(), DaemonUnavailableError),
]),
);

const session = {
id: "current",
pid: 1,
cols: 80,
rows: 24,
alive: true,
};
const [sessions] = await wait(
Promise.all([
client.list(),
(async () => {
const { message: second, socket } = await wait(
secondRequest.promise,
);
const repliesRead = Promise.withResolvers<void>();
client.subscribe(
"list-test-marker",
{ replay: false },
{
onOutput: () => repliesRead.resolve(),
onExit: () => {},
},
);
socket.write(
Buffer.concat([
encodeFrame({
type: "list-reply",
requestId: first.requestId,
sessions: [],
}),
encodeFrame({
type: "list-reply",
requestId: second.requestId,
sessions: [session],
}),
encodeFrame(
{ type: "output", id: "list-test-marker" },
Buffer.from("replies read"),
),
]),
);
// The marker arrives after both replies, even if neither matched.
await wait(repliesRead.promise);
t.mock.timers.runAll();
})(),
]),
);
assert.deepEqual(sessions, [session]);
} finally {
t.signal.removeEventListener("abort", cancel);
cancel();
t.mock.timers.reset();
try {
await client.dispose();
await new Promise<void>((resolve) => fake.close(() => resolve()));
} finally {
rmSync(socketDir, { recursive: true, force: true });
}
}
},
);

test("open rejects with DaemonUnavailableError when the daemon dies mid-request", async () => {
// Fake daemon: completes the handshake, then never answers `open` — the
// socket dying underneath the pending request must classify as
Expand Down
28 changes: 20 additions & 8 deletions packages/host-service/src/terminal/DaemonClient/DaemonClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import {
CURRENT_PROTOCOL_VERSION,
encodeFrame,
FrameDecoder,
type ListMessage,
type PrepareUpgradeMessage,
type ServerMessage,
type SessionInfo,
type SessionMeta,
Expand Down Expand Up @@ -99,6 +101,8 @@ export class DaemonClient {
private connected = false;
private modeSnapshots = false;
private colorQueries = false;
private listRequestIds = false;
private lastListRequestId = 0;

constructor(opts: DaemonClientOptions) {
this.opts = opts;
Expand Down Expand Up @@ -179,8 +183,11 @@ export class DaemonClient {
}

async list(): Promise<SessionInfo[]> {
const requestId = this.listRequestIds
? ++this.lastListRequestId
: undefined;
const reply = await this.requestNonSession(
{ type: "list" },
{ type: "list", requestId },
"list-reply",
LIST_TIMEOUT_MS,
);
Expand Down Expand Up @@ -331,6 +338,7 @@ export class DaemonClient {
}
this.modeSnapshots = ack.supportsModeSnapshots === true;
this.colorQueries = ack.supportsColorQueries === true;
this.listRequestIds = ack.supportsListRequestIds === true;
this.daemonVersion = ack.daemonVersion;
this.negotiated = ack.protocol;
}
Expand Down Expand Up @@ -385,10 +393,11 @@ export class DaemonClient {
}

private requestNonSession(
req: { type: "list" } | { type: "prepare-upgrade" },
req: ListMessage | PrepareUpgradeMessage,
expectType: "list-reply" | "upgrade-prepared",
timeoutMs: number,
): Promise<ServerMessage> {
const requestId = req.type === "list" ? req.requestId : undefined;
return new Promise<ServerMessage>((resolve, reject) => {
let resolved = false;
const settle = (m: ServerMessage) => {
Expand All @@ -405,14 +414,17 @@ export class DaemonClient {
};
const off = this.on((m) => {
if (m.type === expectType) {
settle(m);
if (m.type !== "list-reply" || m.requestId === requestId) settle(m);
return;
}
// Non-session error frames (no `id`) belong to the
// most-recent non-session request — settle on those. Errors
// keyed to a session id come from concurrent ops on that
// session; ignore them here.
if (m.type === "error" && m.id === undefined) settle(m);
// An untagged error cannot be attributed to a tagged list request.
if (
requestId === undefined &&
m.type === "error" &&
m.id === undefined
) {
settle(m);
}
});
const offDisc = this.onDisconnect((err) =>
fail(new DaemonUnavailableError(err?.message ?? "daemon disconnected")),
Expand Down
3 changes: 2 additions & 1 deletion packages/pty-daemon/src/Server/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,7 @@ export class Server {
trustdHealthy: this.trustdHealthy,
supportsModeSnapshots: true,
supportsColorQueries: true,
supportsListRequestIds: true,
});
return;
}
Expand Down Expand Up @@ -512,7 +513,7 @@ export class Server {
return;
}
case "list": {
conn.send(handleList(ctx));
conn.send({ ...handleList(ctx), requestId: msg.requestId });
return;
}
case "subscribe": {
Expand Down
3 changes: 3 additions & 0 deletions packages/pty-daemon/src/protocol/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export interface HelloAckMessage {
trustdHealthy?: boolean;
supportsModeSnapshots?: boolean;
supportsColorQueries?: boolean;
supportsListRequestIds?: boolean;
}

// ---------- Client -> Daemon ----------
Expand Down Expand Up @@ -90,6 +91,7 @@ export interface CloseMessage {

export interface ListMessage {
type: "list";
requestId?: number;
}

export interface SubscribeMessage {
Expand Down Expand Up @@ -152,6 +154,7 @@ export interface ClosedMessage {

export interface ListReplyMessage {
type: "list-reply";
requestId?: number;
sessions: SessionInfo[];
}

Expand Down
22 changes: 22 additions & 0 deletions packages/pty-daemon/test/control-plane.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,28 @@ describe("handshake", () => {
await c.close();
});

test("echoes a list request ID and still accepts an untagged list", async () => {
const c = await connect(sockPath);
try {
c.send({ type: "hello", protocols: [2] });
const ack = await c.waitFor((m) => m.type === "hello-ack");
assert.equal(ack.type, "hello-ack");
assert.equal(ack.supportsListRequestIds, true);
c.send({ type: "list", requestId: 42 });
const tagged = await c.waitFor((m) => m.type === "list-reply");
assert.deepEqual(tagged, {
type: "list-reply",
requestId: 42,
sessions: [],
});
c.send({ type: "list" });
const untagged = await c.waitForNext((m) => m.type === "list-reply");
assert.deepEqual(untagged, { type: "list-reply", sessions: [] });
} finally {
await c.close();
}
});

test("rejects duplicate hello", async () => {
const c = await connectAndHello(sockPath);
c.send({ type: "hello", protocols: [2] });
Expand Down
Loading