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
6 changes: 6 additions & 0 deletions apps/mobile/src/connection/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import {
BoundedThreadSnapshotLoader,
ThreadHistoryController,
} from "@t3tools/client-runtime/state/threads";
import { SOCKET_RPC_CODEC_SCHEMA_BINARY } from "@t3tools/shared/socketFrameParts";
import { Platform } from "react-native";
import * as Layer from "effect/Layer";
import { Atom } from "effect/reactivity";

import type { FoundationHotModule } from "../lib/foundation-fast-refresh";
import { hotSwappableAtomRuntime } from "../lib/hot-swappable-atom-runtime";
import * as Runtime from "../lib/runtime";
import * as NativeWebSocket from "../native/nativeWebSocket";
import { appAtomRegistry } from "../state/atom-registry";
import * as BackgroundActivity from "./background-activity";
import * as ConnectionPlatform from "./platform";
Expand Down Expand Up @@ -46,6 +48,10 @@ const layerProvidedClientConnection = layerSnapshotLoader.pipe(
providerCatalogsOnDemand: true,
providerCatalogDigests: true,
providerStatusDeltas: true,
// Android stays on JSON: RN's WebSocketModule.kt base64-encodes binary frames over the bridge.
...(NativeWebSocket.supportsNativeBinaryWebSocket
? { rpcCodec: SOCKET_RPC_CODEC_SCHEMA_BINARY }
: {}),
// Halves idle pings. The timeout is checked on ping ticks, after an unanswered ping
// and 15 s with no frame: within 25 s of the last frame (20 s at the 5 s default),
// and a host stalled for 10 s can lose the socket (15 s at the default).
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/native/nativeWebSocket.ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ function layerFromModule(native: NativeModule): Layer.Layer<Socket.WebSocketCons

const native = requireOptionalNativeModule<NativeModule>("T3WebSocket");

export const supportsNativeBinaryWebSocket = native !== null;

// A dev client built before this module shipped still has SocketRocket.
export const layer: Layer.Layer<Socket.WebSocketConstructor> =
native === null ? Socket.layerWebSocketConstructorGlobal : layerFromModule(native);
2 changes: 2 additions & 0 deletions apps/mobile/src/native/nativeWebSocket.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as Socket from "effect/socket/Socket";

export const supportsNativeBinaryWebSocket = false;

export const layer = Socket.layerWebSocketConstructorGlobal;
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmen
expect(second.capabilities.serverResolvedCommandContext).toBe(true);
expect(second.capabilities.projectProviderInstanceOverrides).toBe(true);
expect(second.capabilities.wsAckWindow).toBe(4);
expect(second.capabilities.wsRpcCodecs).toEqual(["json", "schema-binary"]);
expect(second.capabilities.agentActivityPublishing).toBe(false);
}),
);
Expand Down
7 changes: 6 additions & 1 deletion apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import {
type ExecutionEnvironmentDescriptor,
} from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { MAX_SOCKET_ACK_WINDOW } from "@t3tools/shared/socketFrameParts";
import {
MAX_SOCKET_ACK_WINDOW,
SOCKET_RPC_CODEC_JSON,
SOCKET_RPC_CODEC_SCHEMA_BINARY,
} from "@t3tools/shared/socketFrameParts";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Deferred from "effect/Deferred";
Expand Down Expand Up @@ -315,6 +319,7 @@ export const make = Effect.gen(function* () {
htmlPreviewTheme: true,
agentFeedback: true,
wsAckWindow: MAX_SOCKET_ACK_WINDOW,
wsRpcCodecs: [SOCKET_RPC_CODEC_JSON, SOCKET_RPC_CODEC_SCHEMA_BINARY],
},
};

Expand Down
30 changes: 30 additions & 0 deletions apps/server/src/socketHeartbeat.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { SCHEMA_BINARY_PONG_FRAME } from "@t3tools/shared/socketFrameParts";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
Expand Down Expand Up @@ -65,4 +66,33 @@ describe("withSocketHeartbeat", () => {
yield* Scope.close(scope, Exit.void);
}),
);

it.effect("writes binary Pong heartbeat frames when configured for SchemaBinary sockets", () =>
Effect.gen(function* () {
const written: Array<string | Uint8Array | Socket.CloseEvent> = [];
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)),
}),
}),
{ frame: SCHEMA_BINARY_PONG_FRAME },
);
const scope = yield* Scope.make();
const writer = yield* Scope.provide(socket.writer, scope);

const outbound = new Uint8Array([1, 2, 3]);
yield* TestClock.adjust("15 seconds");
yield* writer.write(outbound);
yield* TestClock.adjust("15 seconds");
assert.deepStrictEqual(written, [outbound]);

yield* TestClock.adjust("5 seconds");
assert.deepStrictEqual(written, [outbound, SCHEMA_BINARY_PONG_FRAME]);

yield* Scope.close(scope, Exit.void);
}),
);
});
12 changes: 10 additions & 2 deletions apps/server/src/socketHeartbeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,16 @@ export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}';

const SOCKET_HEARTBEAT_INTERVAL_NANOS = Duration.toNanosUnsafe(SOCKET_HEARTBEAT_INTERVAL);

export interface SocketHeartbeatOptions {
readonly frame?: string | Uint8Array;
}

/** 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 {
export function withSocketHeartbeat(
socket: Socket.Socket,
options?: SocketHeartbeatOptions,
): Socket.Socket {
const frame = options?.frame ?? SOCKET_HEARTBEAT_FRAME;
return Socket.make({
reader: socket.reader,
writer: Effect.gen(function* () {
Expand All @@ -35,7 +43,7 @@ export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket {
}
// Stamp before writing so an ignored write failure still sleeps a full interval.
markWrite();
yield* writer.write(SOCKET_HEARTBEAT_FRAME).pipe(Effect.ignore);
yield* writer.write(frame).pipe(Effect.ignore);
}
});

Expand Down
77 changes: 77 additions & 0 deletions apps/server/src/terminal/OutputProtocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import {
TerminalAttachStreamEvent as TerminalAttachStreamEventSchema,
WS_METHODS,
} from "@t3tools/contracts";
import { layerSocketSchemaBinary } from "@t3tools/shared/socketFrameParts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";
Expand Down Expand Up @@ -262,6 +264,81 @@ describe("terminal output window", () => {
assert.equal((yield* Queue.take(responses))._tag, "Exit");
}).pipe(Effect.provide(RpcSerialization.layerJson)),
);

it.effect(
"enforces byte-window backpressure on terminalAttach under SchemaBinary Uint8Array chunks",
() =>
Effect.gen(function* () {
const tag = WS_METHODS.terminalAttach;
const group = RpcGroup.make(
Rpc.make(tag, { success: TerminalAttachStreamEventSchema, stream: true }),
);
const serialization = yield* RpcSerialization.RpcSerialization;
const encodeVoid = Schema.encodeEffect(serialization.codecFor(Schema.Void));
const decodeChunk = Schema.decodeUnknownEffect(
serialization.codecFor(Schema.NonEmptyArray(TerminalAttachStreamEventSchema)),
);
const output = yield* Queue.unbounded<TerminalAttachStreamEvent>();
const responses = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();
const protocol = yield* RpcServer.Protocol.make((write) =>
Effect.gen(function* () {
yield* Deferred.succeed(receive, write);
return {
disconnects: yield* Queue.unbounded<number>(),
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: yield* encodeVoid(undefined),
headers: [],
});

const large = eventWith("data", "x".repeat(64 * 1024));
yield* Queue.offer(output, large);
yield* TestClock.adjust(0);
const first = yield* Queue.take(responses);
assert.equal(first._tag, "Chunk");
if (first._tag === "Chunk") {
assert.instanceOf(first.values, Uint8Array);
assert.deepEqual(yield* decodeChunk(first.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" });
const resumed = yield* Queue.take(responses);
assert.equal(resumed._tag, "Chunk");
if (resumed._tag === "Chunk") {
assert.instanceOf(resumed.values, Uint8Array);
assert.deepEqual(yield* decodeChunk(resumed.values), [next]);
}

yield* write(0, { _tag: "Interrupt", requestId: "1" });
assert.equal((yield* Queue.take(responses))._tag, "Exit");
}).pipe(Effect.provide(layerSocketSchemaBinary)),
);
});

const output = (data: string): TerminalAttachStreamEvent => ({
Expand Down
18 changes: 11 additions & 7 deletions apps/server/src/terminal/OutputProtocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,17 @@ const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) =>
byteLengthOf(event.snapshot.label)
: 0);

// Byte-windowed streams carry TerminalAttachStreamEvent, whose encoded form is the
// event itself, so charge it like the output queue does instead of serializing twice.
const chunkSize = (values: ReadonlyArray<unknown>) =>
values.reduce<number>(
(total, value) => total + queuedSize(value as TerminalAttachStreamEvent),
EVENT_OVERHEAD,
);
// Byte-windowed streams carry TerminalAttachStreamEvent (array on JSON, Uint8Array on binary),
// so charge the already-encoded size instead of re-serializing.
const chunkSize = (values: unknown) =>
values instanceof Uint8Array
? EVENT_OVERHEAD + values.byteLength
: Array.isArray(values)
? values.reduce<number>(
(total, value) => total + queuedSize(value as TerminalAttachStreamEvent),
EVENT_OVERHEAD,
)
: EVENT_OVERHEAD;

interface Window {
readonly bytes: boolean;
Expand Down
Loading
Loading