From 74fe7799959b2acbc36baa80fd88fdef6aa586d6 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 3 Dec 2026 13:00:51 -0800 Subject: [PATCH] perf(ws): [NBR] cut WebSocket control, Ack, and framing wire bytes --- .../src/environment/ServerEnvironment.test.ts | 1 + .../src/environment/ServerEnvironment.ts | 2 + apps/server/src/socketHeartbeat.test.ts | 29 ++ apps/server/src/socketHeartbeat.ts | 55 ++- .../src/terminal/OutputProtocol.test.ts | 159 ++++++++ apps/server/src/terminal/OutputProtocol.ts | 35 +- apps/server/src/ws.ts | 7 +- packages/client-runtime/src/rpc/protocol.ts | 2 +- .../client-runtime/src/rpc/session.test.ts | 383 +++++++++++++++++- packages/client-runtime/src/rpc/session.ts | 277 ++++++++++++- packages/contracts/src/environment.ts | 2 + packages/shared/src/socketFrameParts.test.ts | 137 +++++++ packages/shared/src/socketFrameParts.ts | 50 ++- 13 files changed, 1093 insertions(+), 46 deletions(-) create mode 100644 packages/shared/src/socketFrameParts.test.ts diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 0a04962c34b0a..682518d242d47 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -326,6 +326,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmen expect(second.capabilities.threadPullRequestLinking).toBe(true); expect(second.capabilities.serverResolvedCommandContext).toBe(true); expect(second.capabilities.projectProviderInstanceOverrides).toBe(true); + expect(second.capabilities.wsAckWindow).toBe(4); expect(second.capabilities.agentActivityPublishing).toBe(false); }), ); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index d518748c74965..6d5ff51ac0602 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -5,6 +5,7 @@ import { type ExecutionEnvironmentDescriptor, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { MAX_SOCKET_ACK_WINDOW } from "@t3tools/shared/socketFrameParts"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; @@ -313,6 +314,7 @@ export const make = Effect.gen(function* () { shellOlderSettled: true, htmlPreviewTheme: true, agentFeedback: true, + wsAckWindow: MAX_SOCKET_ACK_WINDOW, }, }; diff --git a/apps/server/src/socketHeartbeat.test.ts b/apps/server/src/socketHeartbeat.test.ts index 2cb002bbf8862..7b13d979e27db 100644 --- a/apps/server/src/socketHeartbeat.test.ts +++ b/apps/server/src/socketHeartbeat.test.ts @@ -36,4 +36,33 @@ describe("withSocketHeartbeat", () => { assert.strictEqual(written.length, 2); }), ); + + it.effect("defers heartbeats while outbound frames are written and resumes when idle", () => + Effect.gen(function* () { + const written: Array = []; + const socket = withSocketHeartbeat( + Socket.make({ + reader: Effect.never, + writer: Effect.succeed({ + write: (chunk) => Effect.sync(() => void written.push(chunk)), + writeAll: (chunks) => Effect.sync(() => void written.push(...chunks)), + }), + }), + ); + const scope = yield* Scope.make(); + const writer = yield* Scope.provide(socket.writer, scope); + + yield* TestClock.adjust("15 seconds"); + yield* writer.write("frame-1"); + yield* TestClock.adjust("15 seconds"); + yield* writer.writeAll(["frame-2", "frame-3"]); + yield* TestClock.adjust("15 seconds"); + assert.deepStrictEqual(written, ["frame-1", "frame-2", "frame-3"]); + + yield* TestClock.adjust("5 seconds"); + assert.deepStrictEqual(written, ["frame-1", "frame-2", "frame-3", SOCKET_HEARTBEAT_FRAME]); + + yield* Scope.close(scope, Exit.void); + }), + ); }); diff --git a/apps/server/src/socketHeartbeat.ts b/apps/server/src/socketHeartbeat.ts index 6ffd9c9cf785c..185c85480fa63 100644 --- a/apps/server/src/socketHeartbeat.ts +++ b/apps/server/src/socketHeartbeat.ts @@ -1,3 +1,4 @@ +import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Socket from "effect/socket/Socket"; @@ -9,19 +10,51 @@ export const SOCKET_HEARTBEAT_INTERVAL = Duration.seconds(20); // RPC clients count any decoded frame as liveness and ignore unsolicited pongs. export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}'; -/** Server side: writes a heartbeat frame on an interval for as long as the writer is open. */ +const SOCKET_HEARTBEAT_INTERVAL_NANOS = Duration.toNanosUnsafe(SOCKET_HEARTBEAT_INTERVAL); + +/** Server side: writes a heartbeat frame after an idle interval for as long as the writer is open. */ export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket { return Socket.make({ reader: socket.reader, - writer: Effect.tap(socket.writer, (writer) => - writer - .write(SOCKET_HEARTBEAT_FRAME) - .pipe( - Effect.delay(SOCKET_HEARTBEAT_INTERVAL), - Effect.forever, - Effect.ignore, - Effect.forkScoped, - ), - ), + writer: Effect.gen(function* () { + const clock = yield* Clock.Clock; + const writer = yield* socket.writer; + let lastWriteNanos = clock.monotonicTimeNanosUnsafe(); + + const markWrite = () => { + lastWriteNanos = clock.monotonicTimeNanosUnsafe(); + }; + + const heartbeatLoop = Effect.gen(function* () { + for (;;) { + const remainingNanos = + SOCKET_HEARTBEAT_INTERVAL_NANOS - (clock.monotonicTimeNanosUnsafe() - lastWriteNanos); + if (remainingNanos > 0n) { + yield* Effect.sleep(Duration.nanos(remainingNanos)); + continue; + } + // Stamp before writing so an ignored write failure still sleeps a full interval. + markWrite(); + yield* writer.write(SOCKET_HEARTBEAT_FRAME).pipe(Effect.ignore); + } + }); + + yield* Effect.forkScoped(heartbeatLoop); + + return { + write: (chunk) => + Effect.suspend(() => { + markWrite(); + return writer.write(chunk).pipe(Effect.tap(() => Effect.sync(markWrite))); + }), + writeAll: (chunks) => + Effect.suspend(() => { + if (chunks.length > 0) markWrite(); + return writer + .writeAll(chunks) + .pipe(Effect.tap(() => (chunks.length > 0 ? Effect.sync(markWrite) : Effect.void))); + }), + }; + }), }); } diff --git a/apps/server/src/terminal/OutputProtocol.test.ts b/apps/server/src/terminal/OutputProtocol.test.ts index 7ae536605e8fa..19846af2ec70a 100644 --- a/apps/server/src/terminal/OutputProtocol.test.ts +++ b/apps/server/src/terminal/OutputProtocol.test.ts @@ -103,6 +103,165 @@ describe("terminal output window", () => { assert.equal((yield* Queue.take(responses))._tag, "Exit"); }).pipe(Effect.provide(RpcSerialization.layerJson)), ); + + it.effect.each([ + ORCHESTRATION_V2_WS_METHODS.subscribeThread, + WS_METHODS.subscribeTerminalMetadata, + ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput, + ] as const)("releases ackWindow chunks per Ack on %s while preserving backpressure", (tag) => + Effect.gen(function* () { + const group = RpcGroup.make( + Rpc.make(tag, { success: TerminalAttachStreamEventSchema, stream: true }), + ); + const output = yield* Queue.unbounded(); + const responses = yield* Queue.unbounded(); + const receive = yield* Deferred.make[0]>(); + const protocol = yield* RpcServer.Protocol.make((write) => + Effect.gen(function* () { + yield* Deferred.succeed(receive, write); + const serialization = yield* RpcSerialization.RpcSerialization; + return { + disconnects: yield* Queue.unbounded(), + send: (_clientId, response) => Queue.offer(responses, response), + end: () => Effect.void, + clientIds: Effect.succeed(new Set([0])), + initialMessage: Effect.succeedNone, + supportsAck: true, + supportsTransferables: false, + supportsSpanPropagation: false, + supportsNotifications: true, + codecFor: serialization.codecFor, + }; + }), + ); + yield* RpcServer.make(group).pipe( + Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))), + Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol, { ackWindow: 4 })), + Effect.forkScoped, + ); + const write = yield* Deferred.await(receive); + yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] }); + + for (let index = 0; index < 8; index++) { + const value = eventWith("data", `c-${index}`); + yield* Queue.offer(output, value); + yield* TestClock.adjust(0); + assert.deepEqual(yield* Queue.take(responses), { + _tag: "Chunk", + requestId: "1", + values: [value], + }); + } + const ninth = eventWith("data", "c-8"); + yield* Queue.offer(output, ninth); + yield* TestClock.adjust(0); + assert.equal(yield* Queue.size(responses), 0); + + yield* write(0, { _tag: "Ack", requestId: "1" }); + assert.deepEqual(yield* Queue.take(responses), { + _tag: "Chunk", + requestId: "1", + values: [ninth], + }); + for (let index = 9; index < 12; index++) { + const value = eventWith("data", `c-${index}`); + yield* Queue.offer(output, value); + yield* TestClock.adjust(0); + assert.deepEqual(yield* Queue.take(responses), { + _tag: "Chunk", + requestId: "1", + values: [value], + }); + } + const thirteenth = eventWith("data", "c-12"); + yield* Queue.offer(output, thirteenth); + yield* TestClock.adjust(0); + assert.equal(yield* Queue.size(responses), 0); + + yield* write(0, { _tag: "Ack", requestId: "1" }); + assert.deepEqual(yield* Queue.take(responses), { + _tag: "Chunk", + requestId: "1", + values: [thirteenth], + }); + for (let index = 13; index < 16; index++) { + const value = eventWith("data", `c-${index}`); + yield* Queue.offer(output, value); + yield* TestClock.adjust(0); + assert.deepEqual(yield* Queue.take(responses), { + _tag: "Chunk", + requestId: "1", + values: [value], + }); + } + + yield* write(0, { _tag: "Interrupt", requestId: "1" }); + assert.equal((yield* Queue.take(responses))._tag, "Exit"); + }).pipe(Effect.provide(RpcSerialization.layerJson)), + ); + + it.effect( + "unblocks byte-windowed terminalAttach after a 64 KiB chunk on one Ack with ackWindow=4", + () => + Effect.gen(function* () { + const tag = WS_METHODS.terminalAttach; + const group = RpcGroup.make( + Rpc.make(tag, { success: TerminalAttachStreamEventSchema, stream: true }), + ); + const output = yield* Queue.unbounded(); + const responses = yield* Queue.unbounded(); + const receive = yield* Deferred.make[0]>(); + const protocol = yield* RpcServer.Protocol.make((write) => + Effect.gen(function* () { + yield* Deferred.succeed(receive, write); + const serialization = yield* RpcSerialization.RpcSerialization; + return { + disconnects: yield* Queue.unbounded(), + send: (_clientId, response) => Queue.offer(responses, response), + end: () => Effect.void, + clientIds: Effect.succeed(new Set([0])), + initialMessage: Effect.succeedNone, + supportsAck: true, + supportsTransferables: false, + supportsSpanPropagation: false, + supportsNotifications: true, + codecFor: serialization.codecFor, + }; + }), + ); + yield* RpcServer.make(group).pipe( + Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))), + Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol, { ackWindow: 4 })), + Effect.forkScoped, + ); + const write = yield* Deferred.await(receive); + yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] }); + + const large = eventWith("data", "x".repeat(64 * 1024)); + yield* Queue.offer(output, large); + yield* TestClock.adjust(0); + assert.deepEqual(yield* Queue.take(responses), { + _tag: "Chunk", + requestId: "1", + values: [large], + }); + + const next = eventWith("data", "after-large"); + yield* Queue.offer(output, next); + yield* TestClock.adjust(0); + assert.equal(yield* Queue.size(responses), 0); + + yield* write(0, { _tag: "Ack", requestId: "1" }); + assert.deepEqual(yield* Queue.take(responses), { + _tag: "Chunk", + requestId: "1", + values: [next], + }); + + yield* write(0, { _tag: "Interrupt", requestId: "1" }); + assert.equal((yield* Queue.take(responses))._tag, "Exit"); + }).pipe(Effect.provide(RpcSerialization.layerJson)), + ); }); const output = (data: string): TerminalAttachStreamEvent => ({ diff --git a/apps/server/src/terminal/OutputProtocol.ts b/apps/server/src/terminal/OutputProtocol.ts index 1b3f48faa6427..23c912e771014 100644 --- a/apps/server/src/terminal/OutputProtocol.ts +++ b/apps/server/src/terminal/OutputProtocol.ts @@ -70,9 +70,19 @@ interface Window { readonly sizes: number[]; } +export interface OutputWindowOptions { + readonly ackWindow?: number; +} + export function withOutputWindow( protocol: RpcServer.Protocol["Service"], + options?: OutputWindowOptions, ): RpcServer.Protocol["Service"] { + // Keep at least two ack windows inside MAX_PENDING_CHUNKS so batching never stalls a stream. + const ackWindow = Math.max( + 1, + Math.min(Math.floor(options?.ackWindow ?? 1), Math.floor(MAX_PENDING_CHUNKS / 2)), + ); // RpcServer drops a disconnected client before its streams exit, so their Exit never // reaches send; departed clients are pruned when a window opens instead. const clients = new Map>(); @@ -87,7 +97,12 @@ export function withOutputWindow( for (const id of clients.keys()) if (!connected.has(id)) clients.delete(id); let windows = clients.get(clientId); if (!windows) clients.set(clientId, (windows = new Map())); - if (!windows.has(requestId)) windows.set(requestId, { bytes, sizes: [] }); + let window = windows.get(requestId); + if (!window) { + window = { bytes, sizes: [] }; + windows.set(requestId, window); + } + return window; }); return { ...protocol, @@ -102,11 +117,13 @@ export function withOutputWindow( Effect.andThen(write(clientId, message)), ); } + } else if (message._tag === "Interrupt") { + clients.get(clientId)?.delete(String(message.requestId)); } else if (message._tag === "Ack") { const window = windowFor(clientId, String(message.requestId)); if (window) { const wasFull = isFull(window.sizes); - window.sizes.shift(); + window.sizes.splice(0, ackWindow); if (!wasFull || isFull(window.sizes)) return Effect.void; } } @@ -120,8 +137,8 @@ export function withOutputWindow( if (response._tag === "Exit") { clients.get(clientId)?.delete(String(response.requestId)); } else if (response._tag === "Chunk") { - const window = windowFor(clientId, String(response.requestId)); - if (window) { + const requestId = String(response.requestId); + const pushAndAck = (window: Window) => { window.sizes.push(window.bytes ? chunkSize(response.values) : 0); if (!isFull(window.sizes)) { return send.pipe( @@ -133,6 +150,16 @@ export function withOutputWindow( ), ); } + return send; + }; + const window = windowFor(clientId, requestId); + if (window) { + return pushAndAck(window); + } + // When windowed Acks are negotiated, lazily count-window every stream so clients + // can batch Acks uniformly without stalling on unwindowed 1-chunk streams. + if (ackWindow > 1) { + return openWindow(clientId, requestId, false).pipe(Effect.flatMap(pushAndAck)); } } return send; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 02b556e4ae4f9..82d163b13e4d9 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -300,6 +300,8 @@ import * as SourceControlRateLimit from "@t3tools/source-control-core/server/Sou import { isNetworkPath } from "@t3tools/shared/path"; import * as RelayClient from "@t3tools/shared/relayClient"; import { + parseSocketAckWindow, + SOCKET_ACK_WINDOW_QUERY_PARAM, SOCKET_FRAME_PARTS_QUERY_PARAM, splitLargeSocketFrames, } from "@t3tools/shared/socketFrameParts"; @@ -4047,10 +4049,13 @@ export const layer = Layer.unwrap( const clientAnalyticsProps = readClientAnalyticsProps(request); yield* analytics.recordOwners(readClientOwners(request), "client"); const reportProfiles = yield* serverBrowser.profileReporter; + const ackWindow = parseSocketAckWindow( + url.value.searchParams.get(SOCKET_ACK_WINDOW_QUERY_PARAM), + ); const rpcWebSocketHttpEffect = yield* Effect.gen(function* () { const { protocol, httpEffect } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket; yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe( - Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol)), + Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol, { ackWindow })), Effect.provide( Layer.merge( RpcAuthorization.layer(session.scopes, (method, payload) => { diff --git a/packages/client-runtime/src/rpc/protocol.ts b/packages/client-runtime/src/rpc/protocol.ts index 32c93d0483199..de725b239733c 100644 --- a/packages/client-runtime/src/rpc/protocol.ts +++ b/packages/client-runtime/src/rpc/protocol.ts @@ -2,7 +2,7 @@ import { WsRpcGroup } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { RpcClient } from "effect/rpc"; -export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup); +export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup, { disableTracing: true }); type RpcClientFactory = typeof makeWsRpcProtocolClient; export type WsRpcProtocolClient = RpcClientFactory extends Effect.Effect ? Client : never; diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 09b7353ed7703..6b0c778667ce2 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -10,10 +10,12 @@ import { UsageLimitSourceId, CALM_HOST_PRESSURE, } from "@t3tools/contracts"; -import { splitSocketFrame } from "@t3tools/shared/socketFrameParts"; +import { DEFAULT_SOCKET_ACK_WINDOW, splitSocketFrame } from "@t3tools/shared/socketFrameParts"; import { describe, expect, it } from "@effect/vitest"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -162,8 +164,17 @@ const RpcRequest = Schema.TaggedStruct("Request", { payload: Schema.Unknown, tag: Schema.String, }); +const RpcAck = Schema.TaggedStruct("Ack", { + requestId: Schema.Union([Schema.String, Schema.Number]), +}); const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); const isRpcRequest = Schema.is(RpcRequest); +const isRpcAck = Schema.is(RpcAck); +const sentAcks = (socket: TestWebSocket, requestId: string | number) => + socket.sent + .map((message) => decodeJson(message)) + .filter(isRpcAck) + .filter((ack) => String(ack.requestId) === String(requestId)); const encodeJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); const encodeServerConfig = Schema.encodeSync(ServerConfig); const encodeServerConfigStreamEvent = Schema.encodeSync(ServerConfigStreamEvent); @@ -345,7 +356,7 @@ describe("RpcSessionFactory", () => { }).pipe(Effect.scoped), ); - it.effect("connects while a large config snapshot downloads at 4000 bytes per second", () => + it.effect("connects while a large config snapshot downloads across split frame parts", () => Effect.gen(function* () { const { factory, sockets } = yield* makeFactory(); const session = yield* factory.connect(PREPARED); @@ -364,6 +375,34 @@ describe("RpcSessionFactory", () => { ? splitSocketFrame(frame) : [frame]; + // 16,000 raw UTF-8 B/s (~4,000 compressed wire B/s at 4:1 deflate) exceeds 15s unsplit. + for (const part of parts) { + const bytes = new TextEncoder().encode(part); + yield* TestClock.adjust((bytes.length / 16_000) * 1000); + socket.serverMessage(new TextDecoder().decode(bytes)); + } + yield* Fiber.join(readyFiber); + + expect(yield* session.initialConfig).toEqual(config); + }), + ); + + it.effect("reassembles legacy 48 KiB frame parts at 4000 bytes per second", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + const request = yield* awaitRequest(socket); + const config = { ...SERVER_CONFIG, cwd: "/" + "é€😀x".repeat(16 * 1024) }; + const frame = encodeJson({ + _tag: "Chunk", + requestId: request.id, + values: [{ version: 1, type: "snapshot", config: encodeServerConfig(config) }], + }); + const parts = splitSocketFrame(frame, 48 * 1024); + for (const part of parts) { const bytes = new TextEncoder().encode(part); yield* TestClock.adjust((bytes.length / 4000) * 1000); @@ -382,7 +421,9 @@ describe("RpcSessionFactory", () => { const readyFiber = yield* Effect.forkChild(session.ready); const socket = yield* awaitSocket(sockets); - expect(socket.url).toBe(`${PREPARED.socketUrl}&frameParts=1`); + expect(socket.url).toBe( + `${PREPARED.socketUrl}&frameParts=1&ackWindow=${DEFAULT_SOCKET_ACK_WINDOW}`, + ); socket.open(); yield* completeInitialConfig(socket); yield* Fiber.join(readyFiber); @@ -1261,4 +1302,340 @@ describe("RpcSessionFactory", () => { expect(config.availableEditors).toEqual(["zed"]); }), ); + + it.effect("omits RPC tracing fields from outgoing requests even inside an active span", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + + const probeFiber = yield* session.probe.pipe( + Effect.withSpan("test.caller"), + Effect.forkChild, + ); + const probeRequest = yield* awaitRequest(socket, 1); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: probeRequest.id, + exit: { _tag: "Success", value: {} }, + }), + ); + yield* Fiber.join(probeFiber); + + const rawRequests = socket.sent + .map((message) => decodeJson(message)) + .filter( + (message): message is Record => + typeof message === "object" && + message !== null && + "_tag" in message && + message._tag === "Request", + ); + expect(rawRequests).toHaveLength(2); + for (const raw of rawRequests) { + expect("traceId" in raw).toBe(false); + expect("spanId" in raw).toBe(false); + expect("sampled" in raw).toBe(false); + } + }), + ); + + it.effect( + "suppresses client Ping frames during active traffic while preserving idle pings and timeout", + () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const closedFiber = yield* Effect.forkChild(Effect.flip(session.closed)); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + yield* TestClock.adjust(0); + + const sentPings = () => socket.sent.filter((frame) => frame === '{"_tag":"Ping"}'); + for (let tick = 0; tick < 5; tick++) { + yield* TestClock.adjust("4 seconds"); + socket.serverMessage(encodeJson({ _tag: "Pong" })); + yield* TestClock.adjust(0); + } + expect(sentPings()).toHaveLength(0); + + yield* TestClock.adjust("5 seconds"); + expect(sentPings()).toHaveLength(1); + socket.serverMessage(encodeJson({ _tag: "Pong" })); + yield* TestClock.adjust(0); + expect(closedFiber.pollUnsafe()).toBeUndefined(); + + yield* TestClock.adjust("15 seconds"); + expect(yield* Fiber.join(closedFiber)).toMatchObject({ + _tag: "ConnectionTransientError", + reason: "transport", + detail: + "Test environment stopped responding for 15s. It may be overloaded, asleep, or off the network.", + }); + }), + ); + + it.effect( + "probes instead of timing out when timer throttling delays a suppressed 10s ping tick", + () => + Effect.gen(function* () { + const baseClock = yield* Clock.Clock; + let extraSleepDelayMs = 0; + const throttledClock: Clock.Clock = { + ...baseClock, + sleep: (duration) => { + const millis = Duration.toMillis(duration); + if (extraSleepDelayMs > 0 && Number.isFinite(millis)) { + const extra = extraSleepDelayMs; + extraSleepDelayMs = 0; + return baseClock.sleep(Duration.millis(millis + extra)); + } + return baseClock.sleep(duration); + }, + }; + + const { factory, sockets } = yield* makeFactory({ pingInterval: "10 seconds" }); + const session = yield* factory + .connect(PREPARED) + .pipe(Effect.provideService(Clock.Clock, throttledClock)); + const readyFiber = yield* Effect.forkChild(session.ready); + const closedFiber = yield* Effect.forkChild(Effect.flip(session.closed)); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + yield* TestClock.adjust(0); + + const sentPings = () => socket.sent.filter((frame) => frame === '{"_tag":"Ping"}'); + + // Suppress the 10s tick with an inbound frame at 7s, then throttle the next wake by +16s. + yield* TestClock.adjust("7 seconds"); + socket.serverMessage(encodeJson({ _tag: "Pong" })); + yield* TestClock.adjust(0); + extraSleepDelayMs = 16_000; + yield* TestClock.adjust("3 seconds"); + expect(sentPings()).toHaveLength(0); + + // Waking 26s after the last frame with no ping sent yet must probe, not drop the socket. + yield* TestClock.adjust("23 seconds"); + expect(sentPings()).toHaveLength(1); + expect(closedFiber.pollUnsafe()).toBeUndefined(); + + socket.serverMessage(encodeJson({ _tag: "Pong" })); + yield* TestClock.adjust(0); + + // Active suppression covers the full 10s interval before probing again. + yield* TestClock.adjust("9 seconds"); + expect(sentPings()).toHaveLength(1); + expect(closedFiber.pollUnsafe()).toBeUndefined(); + + yield* TestClock.adjust("1 second"); + expect(sentPings()).toHaveLength(2); + expect(closedFiber.pollUnsafe()).toBeUndefined(); + + yield* TestClock.adjust("10 seconds"); + expect(yield* Fiber.join(closedFiber)).toMatchObject({ + _tag: "ConnectionTransientError", + reason: "transport", + detail: + "Test environment stopped responding for 15s. It may be overloaded, asleep, or off the network.", + }); + }), + ); + + it.effect( + "coalesces stream Ack frames when wsAckWindow is advertised and flushes large terminal chunks", + () => + Effect.gen(function* () { + const ackWindowConfig = { + ...ENCODED_SERVER_CONFIG, + environment: { + ...ENCODED_SERVER_CONFIG.environment, + capabilities: { + ...ENCODED_SERVER_CONFIG.environment.capabilities, + wsAckWindow: 4, + }, + }, + }; + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket, ackWindowConfig); + yield* Fiber.join(readyFiber); + + const receivedConfig = yield* Queue.unbounded(); + const configFiber = yield* session.client[WS_METHODS.subscribeServerConfig]({ + omitKeybindings: true, + }).pipe( + Stream.runForEach((event) => Queue.offer(receivedConfig, event)), + Effect.forkChild, + ); + const configRequest = yield* awaitRequest(socket, 1); + for (let index = 0; index < 16; index++) { + socket.serverMessage( + encodeJson({ + _tag: "Chunk", + requestId: configRequest.id, + values: [ + { + version: 1, + type: "keybindingsUpdated", + payload: { keybindings: [], issues: [] }, + }, + ], + }), + ); + yield* Queue.take(receivedConfig); + } + yield* TestClock.adjust(0); + expect(sentAcks(socket, configRequest.id)).toHaveLength(4); + yield* Fiber.interrupt(configFiber); + + const receivedTerminal = yield* Queue.unbounded(); + const terminalFiber = yield* session.client[WS_METHODS.terminalAttach]({ + threadId: "thread-1", + terminalId: "default", + }).pipe( + Stream.runForEach((event) => Queue.offer(receivedTerminal, event)), + Effect.forkChild, + ); + const terminalRequest = yield* awaitRequest(socket, 2); + socket.serverMessage( + encodeJson({ + _tag: "Chunk", + requestId: terminalRequest.id, + values: [ + { + type: "output", + threadId: "thread-1", + terminalId: "default", + data: "hello", + }, + ], + }), + ); + yield* Queue.take(receivedTerminal); + yield* TestClock.adjust(0); + expect(sentAcks(socket, terminalRequest.id)).toHaveLength(0); + + socket.serverMessage( + encodeJson({ + _tag: "Chunk", + requestId: terminalRequest.id, + values: [ + { + type: "output", + threadId: "thread-1", + terminalId: "default", + data: "x".repeat(40 * 1024), + }, + ], + }), + ); + yield* Queue.take(receivedTerminal); + yield* TestClock.adjust(0); + expect(sentAcks(socket, terminalRequest.id)).toHaveLength(1); + yield* Fiber.interrupt(terminalFiber); + }), + ); + + it.effect("activates Ack batching from chunk 1 when descriptor advertises wsAckWindow", () => + Effect.gen(function* () { + const ackWindowDescriptor = { + ...SERVER_CONFIG.environment, + capabilities: { + ...SERVER_CONFIG.environment.capabilities, + wsAckWindow: 4, + }, + }; + const ackWindowConfig = { + ...ENCODED_SERVER_CONFIG, + environment: { + ...ENCODED_SERVER_CONFIG.environment, + capabilities: { + ...ENCODED_SERVER_CONFIG.environment.capabilities, + wsAckWindow: 4, + }, + }, + }; + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect({ ...PREPARED, descriptor: ackWindowDescriptor }); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket, ackWindowConfig); + yield* Fiber.join(readyFiber); + yield* TestClock.adjust(0); + + const request0 = yield* awaitRequest(socket, 0); + expect(sentAcks(socket, request0.id)).toHaveLength(0); + + const observed = yield* Queue.unbounded(); + const subscriber = yield* session.subscribeServerConfig({}).pipe( + Stream.runForEach((event) => Queue.offer(observed, event)), + Effect.forkChild, + ); + expect((yield* Queue.take(observed)).type).toBe("snapshot"); + + for (let index = 0; index < 3; index++) { + yield* publishConfigEvents(socket, [ + { version: 1, type: "keybindingsUpdated", payload: { keybindings: [], issues: [] } }, + ]); + yield* Queue.take(observed); + } + yield* TestClock.adjust(0); + expect(sentAcks(socket, request0.id)).toHaveLength(1); + yield* Fiber.interrupt(subscriber); + }), + ); + + it.effect("sends one Ack per chunk for legacy servers without wsAckWindow", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + + const received = yield* Queue.unbounded(); + const streamFiber = yield* session.client[WS_METHODS.subscribeServerConfig]({ + omitKeybindings: true, + }).pipe( + Stream.runForEach((event) => Queue.offer(received, event)), + Effect.forkChild, + ); + const streamRequest = yield* awaitRequest(socket, 1); + for (let index = 0; index < 4; index++) { + socket.serverMessage( + encodeJson({ + _tag: "Chunk", + requestId: streamRequest.id, + values: [ + { + version: 1, + type: "keybindingsUpdated", + payload: { keybindings: [], issues: [] }, + }, + ], + }), + ); + yield* Queue.take(received); + } + yield* TestClock.adjust(0); + expect(sentAcks(socket, streamRequest.id)).toHaveLength(4); + yield* Fiber.interrupt(streamFiber); + }), + ); }); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 12ba0087d1711..db082fe57cde9 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -7,8 +7,12 @@ import { WS_METHODS, } from "@t3tools/contracts"; import { + DEFAULT_SOCKET_ACK_WINDOW, joinSocketFrameParts, + SOCKET_ACK_BYTE_FLUSH_THRESHOLD, + SOCKET_ACK_WINDOW_QUERY_PARAM, SOCKET_FRAME_PARTS_QUERY_PARAM, + utf8ByteLength, } from "@t3tools/shared/socketFrameParts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; @@ -52,6 +56,146 @@ import { environmentMismatchError } from "../connection/errors.ts"; import { recordServerClock } from "../clock.ts"; const SOCKET_OPEN_TIMEOUT = "15 seconds"; +const DEFAULT_PING_INTERVAL = Duration.seconds(5); +const CLIENT_PING_FRAME = '{"_tag":"Ping"}'; +const TERMINAL_EVENT_OVERHEAD = 128; +const TERMINAL_BYTE_WINDOWED_METHODS: ReadonlySet = new Set([ + WS_METHODS.terminalAttach, + WS_METHODS.terminalObserve, +]); + +interface StreamAckState { + readonly byteWindowed: boolean; + readonly pendingChunkBytes: number[]; + ackedChunks: number; + ackedBytes: number; +} + +const minBigInt = (a: bigint, b: bigint) => (a < b ? a : b); +const maxBigInt = (a: bigint, b: bigint) => (a > b ? a : b); + +function resolveAckWindow(advertised: number | undefined): number { + if (advertised === undefined) return 1; + return Math.max(1, Math.min(Math.floor(advertised), DEFAULT_SOCKET_ACK_WINDOW)); +} + +function estimateTerminalEventBytes(event: unknown): number { + if (typeof event !== "object" || event === null) return TERMINAL_EVENT_OVERHEAD; + const record = event as Record; + let bytes = TERMINAL_EVENT_OVERHEAD; + if (typeof record.threadId === "string") bytes += utf8ByteLength(record.threadId); + if (typeof record.terminalId === "string") bytes += utf8ByteLength(record.terminalId); + if (typeof record.data === "string") bytes += utf8ByteLength(record.data); + if (typeof record.message === "string") bytes += utf8ByteLength(record.message); + if (typeof record.label === "string") bytes += utf8ByteLength(record.label); + if (typeof record.pendingControlSequence === "string") { + bytes += utf8ByteLength(record.pendingControlSequence); + } + if (typeof record.snapshot === "object" && record.snapshot !== null) { + const snap = record.snapshot as Record; + for (const field of ["threadId", "terminalId", "history", "cwd", "worktreePath", "label"]) { + const value = snap[field]; + if (typeof value === "string") bytes += utf8ByteLength(value); + } + } + return bytes; +} + +function estimateTerminalChunkBytes(values: ReadonlyArray): number { + let total = TERMINAL_EVENT_OVERHEAD; + for (const value of values) { + total += estimateTerminalEventBytes(value); + } + return total; +} + +function withIdleOnlyClientPings( + socket: Socket.Socket, + clock: Clock.Clock, + options: { + readonly pingInterval: Duration.Duration; + readonly pingTimeout: Duration.Duration; + readonly onPingTimeout: () => void; + }, +): Socket.Socket { + const intervalMillis = Duration.toMillis(options.pingInterval); + const timeoutMillis = Duration.toMillis(options.pingTimeout); + if (!Number.isFinite(intervalMillis) || intervalMillis <= 0 || !Number.isFinite(timeoutMillis)) { + return socket; + } + const intervalNanos = Duration.toNanosUnsafe(options.pingInterval); + const timeoutNanos = Duration.toNanosUnsafe(options.pingTimeout); + const probeReplyWindowNanos = minBigInt(intervalNanos, timeoutNanos); + return Socket.make({ + reader: Effect.gen(function* () { + const reader = yield* socket.reader; + const writer = yield* socket.writer; + const timedOut = yield* Deferred.make(); + let lastInboundNanos = clock.monotonicTimeNanosUnsafe(); + let firstPingSentNanos: bigint | undefined; + let lastPingSentNanos: bigint | undefined; + + // Only arm ping timeout once a Ping frame is actually sent, so suppressed + // ticks or background-tab timer throttling never time out an unprobed socket. + const pingLoop = Effect.gen(function* () { + for (;;) { + const now = clock.monotonicTimeNanosUnsafe(); + if (firstPingSentNanos !== undefined) { + const timeoutAt = maxBigInt( + lastInboundNanos + timeoutNanos, + firstPingSentNanos + probeReplyWindowNanos, + ); + if (now >= timeoutAt) { + yield* Deferred.fail( + timedOut, + new Socket.SocketError({ + reason: new Socket.SocketReadError({ + cause: new Error("ping timeout"), + }), + }), + ); + return; + } + const nextPingAt = (lastPingSentNanos ?? firstPingSentNanos) + intervalNanos; + if (now >= nextPingAt) { + lastPingSentNanos = now; + yield* writer.write(CLIENT_PING_FRAME).pipe(Effect.ignore); + continue; + } + yield* Effect.sleep(Duration.nanos(minBigInt(timeoutAt, nextPingAt) - now)); + continue; + } + + const nextPingAt = lastInboundNanos + intervalNanos; + if (now < nextPingAt) { + yield* Effect.sleep(Duration.nanos(nextPingAt - now)); + continue; + } + firstPingSentNanos = now; + lastPingSentNanos = now; + yield* writer.write(CLIENT_PING_FRAME).pipe(Effect.ignore); + } + }); + + yield* Effect.forkScoped(pingLoop); + + return { + upgrade: reader.upgrade, + pull: Effect.raceFirst( + Effect.tap(reader.pull, () => + Effect.sync(() => { + lastInboundNanos = clock.monotonicTimeNanosUnsafe(); + firstPingSentNanos = undefined; + lastPingSentNanos = undefined; + }), + ), + Deferred.await(timedOut).pipe(Effect.tapError(() => Effect.sync(options.onPingTimeout))), + ), + }; + }), + writer: socket.writer, + }); +} export interface RpcSession { readonly client: WsRpcProtocolClient; @@ -148,6 +292,7 @@ function serverConfigReplayEvents( } const isSocketErrorReason = Schema.is(Socket.SocketErrorReason); +const PING_TIMEOUT_DURATION = Duration.fromInputUnsafe(PING_TIMEOUT); const PING_TIMEOUT_SECONDS = Duration.toSeconds(PING_TIMEOUT); function mapSessionRpcError( @@ -210,6 +355,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ...input, workspaceSnapshotsOnDemand: true, }); + const pingInterval = + options.pingInterval === undefined + ? DEFAULT_PING_INTERVAL + : Duration.fromInputUnsafe(options.pingInterval); const connect = Effect.fnUntraced(function* (connection: PreparedConnection) { const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct"; @@ -241,11 +390,16 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( }); const mapRpcError = (error: Parameters[0]) => mapSessionRpcError(error, via, socketFailure); + let effectiveAckWindow = resolveAckWindow(connection.descriptor?.capabilities.wsAckWindow); + const byteWindowedRequests = new Set(); + const ackState = new Map(); const hooks = RpcClient.ConnectionHooks.of({ onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid), - onDisconnect: Effect.suspend(() => Deferred.fail(disconnected, socketFailure())).pipe( - Effect.asVoid, - ), + onDisconnect: Effect.suspend(() => { + byteWindowedRequests.clear(); + ackState.clear(); + return Deferred.fail(disconnected, socketFailure()); + }).pipe(Effect.asVoid), }); // The protocol never reopens its socket, so every frame counted here came // from this session's one socket. @@ -261,9 +415,20 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( }; const socketUrl = new URL(connection.socketUrl); socketUrl.searchParams.set(SOCKET_FRAME_PARTS_QUERY_PARAM, "1"); + socketUrl.searchParams.set(SOCKET_ACK_WINDOW_QUERY_PARAM, String(DEFAULT_SOCKET_ACK_WINDOW)); const layerSocket = Layer.effect( Socket.Socket, - Effect.map(Effect.service(Socket.Socket), joinSocketFrameParts), + Effect.gen(function* () { + const clock = yield* Clock.Clock; + const socket = joinSocketFrameParts(yield* Effect.service(Socket.Socket)); + return withIdleOnlyClientPings(socket, clock, { + pingInterval, + pingTimeout: PING_TIMEOUT_DURATION, + onPingTimeout: () => { + pingTimedOut = true; + }, + }); + }), ).pipe( Layer.provide( Socket.layerWebSocket(socketUrl.toString(), { @@ -276,28 +441,99 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( const layerProtocol = Layer.effect( RpcClient.Protocol, RpcClient.makeProtocolSocket({ - pingInterval: options.pingInterval, - pingTimeout: PING_TIMEOUT, + // Owned by withIdleOnlyClientPings so idle suppression never arms a stale timeout. + pingInterval: Duration.infinity, + pingTimeout: Duration.infinity, retryTransientErrors: false, retryPolicy: Schedule.recurs(0), - // RpcClient runs this before it fails the open requests. - onPingTimeout: Effect.sync(() => { - pingTimedOut = true; - }), }).pipe( // Teardown sends an interrupt per open stream, and a write to a closed // socket waits out the client's 1s interrupt timeout before reconnecting. // Requests still go through, so they fail with the protocol error. Effect.map((protocol) => ({ ...protocol, + run: (clientId, handle) => + protocol.run(clientId, (message) => + Effect.suspend(() => { + if (message._tag === "Chunk") { + const id = String(message.requestId); + let state = ackState.get(id); + if (!state) { + state = { + byteWindowed: byteWindowedRequests.has(id), + pendingChunkBytes: [], + ackedChunks: 0, + ackedBytes: 0, + }; + ackState.set(id, state); + } + if (state.byteWindowed) { + state.pendingChunkBytes.push(estimateTerminalChunkBytes(message.values)); + } + } else if (message._tag === "Exit") { + const id = String(message.requestId); + byteWindowedRequests.delete(id); + ackState.delete(id); + } else if (message._tag === "Defect" || message._tag === "ClientProtocolError") { + byteWindowedRequests.clear(); + ackState.clear(); + } + return handle(message); + }), + ), send: (clientId, request, transferables) => - request._tag === "Request" - ? Effect.sync(() => { - awaitingReply = true; - }).pipe(Effect.andThen(protocol.send(clientId, request, transferables))) - : Deferred.isDoneUnsafe(disconnected) - ? Effect.void - : protocol.send(clientId, request, transferables), + Effect.suspend(() => { + if (request._tag === "Request") { + awaitingReply = true; + const id = String(request.id); + if (TERMINAL_BYTE_WINDOWED_METHODS.has(request.tag)) { + byteWindowedRequests.add(id); + } + return protocol.send(clientId, request, transferables).pipe( + Effect.onError(() => + Effect.sync(() => { + byteWindowedRequests.delete(id); + ackState.delete(id); + }), + ), + ); + } + if (request._tag === "Interrupt") { + const id = String(request.requestId); + byteWindowedRequests.delete(id); + ackState.delete(id); + } + if (Deferred.isDoneUnsafe(disconnected)) { + return Effect.void; + } + if (request._tag === "Ack") { + const id = String(request.requestId); + const state = ackState.get(id); + if (state?.byteWindowed) { + state.ackedBytes += state.pendingChunkBytes.shift() ?? 0; + } + if (effectiveAckWindow <= 1) { + if (state) { + state.ackedChunks = 0; + state.ackedBytes = 0; + } + return protocol.send(clientId, request, transferables); + } + if (!state) { + return Effect.void; + } + state.ackedChunks += 1; + if ( + state.ackedChunks < effectiveAckWindow && + (!state.byteWindowed || state.ackedBytes < SOCKET_ACK_BYTE_FLUSH_THRESHOLD) + ) { + return Effect.void; + } + state.ackedChunks = 0; + state.ackedBytes = 0; + } + return protocol.send(clientId, request, transferables); + }), })), ), ).pipe( @@ -343,7 +579,12 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( Effect.gen(function* () { const isInitialConfig = event.type === "snapshot" && !Deferred.isDoneUnsafe(initialConfigDeferred); - if (isInitialConfig) options.onInitialConfig?.(); + if (isInitialConfig) { + effectiveAckWindow = resolveAckWindow( + event.config.environment.capabilities.wsAckWindow, + ); + options.onInitialConfig?.(); + } const buffered = yield* Ref.modify(serverConfigState, (current) => { const projection = applyServerConfigProjection( Option.map(current, (state) => state.projection), diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 731a674b7852f..fcbcdfe02da30 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -235,6 +235,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ issueLinkedThreads: Schema.optionalKey(Schema.Boolean), /** Keeps more than one account per standalone issue tracker; older servers keep one. */ issueTrackerAccounts: Schema.optionalKey(Schema.Boolean), + /** Max stream chunks a single WebSocket Ack releases when `?ackWindow=` is set. */ + wsAckWindow: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/shared/src/socketFrameParts.test.ts b/packages/shared/src/socketFrameParts.test.ts new file mode 100644 index 0000000000000..04f63516d6b44 --- /dev/null +++ b/packages/shared/src/socketFrameParts.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from "@effect/vitest"; +import type * as Arr from "effect/Array"; +import * as Effect from "effect/Effect"; +import * as Socket from "effect/socket/Socket"; + +import { + joinSocketFrameParts, + MAX_SOCKET_ACK_WINDOW, + parseSocketAckWindow, + SOCKET_FRAME_PART_BYTES, + splitLargeSocketFrames, + splitSocketFrame, + utf8ByteLength, +} from "./socketFrameParts.ts"; + +const makeChunkSocket = (chunks: ReadonlyArray>) => { + let index = 0; + const written: Array = []; + const socket = Socket.make({ + reader: Effect.succeed({ + upgrade: () => Effect.void, + pull: Effect.suspend(() => { + const next = chunks[index++]; + return next + ? Effect.succeed(next) + : Effect.fail( + new Socket.SocketError({ + reason: new Socket.SocketCloseError({ code: 1000 }), + }), + ); + }), + }), + writer: Effect.succeed({ + write: (chunk) => Effect.sync(() => void written.push(chunk)), + writeAll: (batch) => Effect.sync(() => void written.push(...batch)), + }), + }); + return { socket, written }; +}; + +describe("socketFrameParts", () => { + it("keeps frames up to SOCKET_FRAME_PART_BYTES unsplit and splits larger multi-byte frames cleanly", () => { + const medium = "a".repeat(160 * 1024); + expect(splitSocketFrame(medium)).toEqual([medium]); + + const large = "é€😀x".repeat(26 * 1024); + const parts = splitSocketFrame(large); + expect(parts.length).toBeGreaterThan(1); + const encoder = new TextEncoder(); + const decoder = new TextDecoder("utf-8", { fatal: true }); + for (const part of parts) { + const encoded = encoder.encode(part); + expect(encoded.length).toBeLessThanOrEqual(SOCKET_FRAME_PART_BYTES); + expect(decoder.decode(encoded)).toBe(part); + } + const rejoined = parts.map((part, i) => (i < parts.length - 1 ? part.slice(1) : part)).join(""); + expect(rejoined).toBe(large); + }); + + it.effect( + "reassembles new, legacy 48 KiB, and mixed part sizes while passing binary through", + () => + Effect.gen(function* () { + const large = "é€😀x".repeat(26 * 1024); + const newParts = splitSocketFrame(large); + const legacyParts = splitSocketFrame(large, 48 * 1024); + const prefix = large.slice(0, 60 * 1024); + const prefixParts = splitSocketFrame(prefix, 48 * 1024); + expect(prefixParts.length).toBeGreaterThan(1); + const lastPrefixPart = prefixParts[prefixParts.length - 1] ?? ""; + const mixedParts = [ + prefixParts[0], + ...prefixParts.slice(1, -1), + `\u001e${lastPrefixPart}`, + large.slice(60 * 1024), + ] as const; + const binary = new Uint8Array([1, 2, 3, 4]); + + const { socket, written } = makeChunkSocket([newParts, legacyParts, mixedParts, [binary]]); + + const writerSocket = splitLargeSocketFrames(socket); + const writer = yield* writerSocket.writer; + yield* writer.write(large); + yield* writer.write(binary); + expect(written).toEqual([...newParts, binary]); + + const readerSocket = joinSocketFrameParts(socket); + const reader = yield* readerSocket.reader; + const firstBatch = yield* reader.pull; + const secondBatch = yield* reader.pull; + const thirdBatch = yield* reader.pull; + const fourthBatch = yield* reader.pull; + + expect(firstBatch.slice(0, -1)).toEqual( + Array.from({ length: newParts.length - 1 }, () => '{"_tag":"Pong"}'), + ); + expect(firstBatch.at(-1)).toBe(large); + expect(secondBatch.slice(0, -1)).toEqual( + Array.from({ length: legacyParts.length - 1 }, () => '{"_tag":"Pong"}'), + ); + expect(secondBatch.at(-1)).toBe(large); + expect(thirdBatch.at(-1)).toBe(large); + expect(fourthBatch).toEqual([binary]); + }).pipe(Effect.scoped), + ); + + it("parses and clamps ackWindow query values safely", () => { + expect(parseSocketAckWindow(null)).toBe(1); + expect(parseSocketAckWindow(undefined)).toBe(1); + expect(parseSocketAckWindow("")).toBe(1); + expect(parseSocketAckWindow("0")).toBe(1); + expect(parseSocketAckWindow("-4")).toBe(1); + expect(parseSocketAckWindow("abc")).toBe(1); + expect(parseSocketAckWindow("4abc")).toBe(1); + expect(parseSocketAckWindow("1")).toBe(1); + expect(parseSocketAckWindow("2")).toBe(2); + expect(parseSocketAckWindow("4")).toBe(4); + expect(parseSocketAckWindow("99")).toBe(MAX_SOCKET_ACK_WINDOW); + }); + + it("measures UTF-8 byte lengths matching TextEncoder", () => { + const encoder = new TextEncoder(); + for (const sample of [ + "", + "ascii-123", + "café", + "界", + "😀", + "\ud800", + "\ud800界", + "\udc00a", + "é€😀x".repeat(64), + ]) { + expect(utf8ByteLength(sample)).toBe(encoder.encode(sample).length); + } + }); +}); diff --git a/packages/shared/src/socketFrameParts.ts b/packages/shared/src/socketFrameParts.ts index e0c82a87de3bb..d79e7daa2ba49 100644 --- a/packages/shared/src/socketFrameParts.ts +++ b/packages/shared/src/socketFrameParts.ts @@ -2,12 +2,41 @@ import * as Arr from "effect/Array"; import * as Effect from "effect/Effect"; import * as Socket from "effect/socket/Socket"; -// Old clients omit this; old servers ignore it. +// Old clients omit these; old servers ignore them. export const SOCKET_FRAME_PARTS_QUERY_PARAM = "frameParts"; +export const SOCKET_ACK_WINDOW_QUERY_PARAM = "ackWindow"; +export const DEFAULT_SOCKET_ACK_WINDOW = 4; +export const MAX_SOCKET_ACK_WINDOW = 4; +// Half of the server's 64 KiB byte-windowed stream cap so large terminal chunks flush immediately. +export const SOCKET_ACK_BYTE_FLUSH_THRESHOLD = 32 * 1024; -// WebSocket messages arrive whole. At 4,000 bytes/s each part takes about -// 12 seconds, leaving margin before the client's 15-second liveness timeout. -const SOCKET_FRAME_PART_BYTES = 48 * 1024; +// JSON snapshots compress ~4-6x under permessage-deflate, so 192 KiB raw UTF-8 stays around +// 32-48 KiB on the wire (under the 15s liveness timeout even on slow links) and well below +// Cloudflare/mobile frame limits while cutting split framing and DEFLATE sync flushes by 4x. +export const SOCKET_FRAME_PART_BYTES = 192 * 1024; + +export function parseSocketAckWindow(value: string | null | undefined): number { + if (value === null || value === undefined || !/^\d+$/.test(value)) return 1; + const parsed = Number.parseInt(value, 10); + return Math.max(1, Math.min(parsed, MAX_SOCKET_ACK_WINDOW)); +} + +function isSurrogatePairAt(text: string, index: number, code: number): boolean { + if (code < 0xd800 || code > 0xdbff || index + 1 >= text.length) return false; + const next = text.charCodeAt(index + 1); + return next >= 0xdc00 && next <= 0xdfff; +} + +export function utf8ByteLength(text: string): number { + let bytes = 0; + for (let index = 0; index < text.length;) { + const code = text.charCodeAt(index); + const pair = isSurrogatePairAt(text, index, code); + bytes += pair ? 4 : code < 0x80 ? 1 : code < 0x800 ? 2 : 3; + index += pair ? 2 : 1; + } + return bytes; +} // No JSON message starts with a record separator. It marks every part but the last. const PART_PREFIX = "\u001e"; @@ -28,7 +57,7 @@ export function splitSocketFrame( let bytes = PART_PREFIX.length; for (let index = 0; index < frame.length;) { const code = frame.charCodeAt(index); - const pair = code >= 0xd800 && code <= 0xdbff && index + 1 < frame.length; + const pair = isSurrogatePairAt(frame, index, code); const size = pair ? 4 : code < 0x80 ? 1 : code < 0x800 ? 2 : 3; if (bytes + size > partBytes) { parts.push(PART_PREFIX + frame.slice(start, index)); @@ -42,14 +71,19 @@ export function splitSocketFrame( } /** Server side: sends string frames longer than one part as consecutive parts. */ -export function splitLargeSocketFrames(socket: Socket.Socket): Socket.Socket { +export function splitLargeSocketFrames( + socket: Socket.Socket, + partBytes = SOCKET_FRAME_PART_BYTES, +): Socket.Socket { const split = (chunk: string | Uint8Array): Arr.NonEmptyReadonlyArray => - typeof chunk === "string" ? splitSocketFrame(chunk) : [chunk]; + typeof chunk === "string" ? splitSocketFrame(chunk, partBytes) : [chunk]; return Socket.make({ reader: socket.reader, writer: Effect.map(socket.writer, (writer) => ({ write: (chunk) => - typeof chunk === "string" ? writer.writeAll(splitSocketFrame(chunk)) : writer.write(chunk), + typeof chunk === "string" + ? writer.writeAll(splitSocketFrame(chunk, partBytes)) + : writer.write(chunk), writeAll: (chunks) => writer.writeAll(Arr.flatMap(chunks, split)), })), });