Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NetworkTransferMeasurement.integration.ts

177 lines5.8 KB

1// @effect-diagnostics nodeBuiltinImport:off - Measures the real Node HTTP and WebSocket transports.
2import * as NodeHttp from "node:http";
3import * as NodeZlib from "node:zlib";
4​
5import * as NodeSocket from "@effect/platform-node/NodeSocket";
6import { WsRpcGroup } from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Schema from "effect/Schema";
10import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
11import * as Socket from "effect/unstable/socket/Socket";
12​
13export class TransferHttpRequestError extends Schema.TaggedErrorClass<TransferHttpRequestError>()(
14 "TransferHttpRequestError",
15 {
16 url: Schema.String,
17 cause: Schema.Defect(),
18 },
19) {}
20​
21export interface HttpTransferMeasurement {
22 readonly status: number;
23 readonly contentEncoding: string | null;
24 readonly encodedBody: Uint8Array;
25 readonly encodedBodyBytes: number;
26 readonly decodedBody: Uint8Array;
27 readonly decodedBodyBytes: number;
28 /** HTTP response bytes read from the socket, including status line and headers. */
29 readonly wireBytes: number;
31​
32export const measureHttpGet = Effect.fn("TransferBudget.measureHttpGet")(function* (input: {
33 readonly url: string;
34 readonly headers?: Readonly<Record<string, string>>;
35}) {
36 return yield* Effect.tryPromise({
37 try: () =>
38 new Promise<HttpTransferMeasurement>((resolve, reject) => {
39 let socketBytesBeforeResponse = 0;
40 const request = NodeHttp.get(
41 input.url,
42 {
43 agent: false,
44 headers: {
45 "accept-encoding": "gzip",
46 connection: "close",
47 ...input.headers,
48 },
49 },
50 (response) => {
51 const chunks: Buffer[] = [];
52 response.on("data", (chunk: Buffer) => chunks.push(chunk));
53 response.once("error", reject);
54 response.once("end", () => {
55 try {
56 const encodedBody = Buffer.concat(chunks);
57 const header = response.headers["content-encoding"];
58 const contentEncoding = Array.isArray(header)
59 ? (header[0] ?? null)
60 : (header ?? null);
61 const decodedBody =
62 contentEncoding === "gzip" ? NodeZlib.gunzipSync(encodedBody) : encodedBody;
63 resolve({
64 status: response.statusCode ?? 0,
65 contentEncoding,
66 encodedBody,
67 encodedBodyBytes: encodedBody.byteLength,
68 decodedBody,
69 decodedBodyBytes: decodedBody.byteLength,
70 wireBytes: Math.max(0, response.socket.bytesRead - socketBytesBeforeResponse),
71 });
72 } catch (cause) {
73 reject(cause);
74 }
75 });
76 },
77 );
78 request.once("socket", (socket) => {
79 socketBytesBeforeResponse = socket.bytesRead;
80 });
81 request.once("error", reject);
82 request.setTimeout(10_000, () => {
83 request.destroy(new Error(`Timed out reading ${input.url}`));
84 });
85 }),
86 catch: (cause) => new TransferHttpRequestError({ url: input.url, cause }),
87 });
88});
89​
90export interface WebSocketTransferTotals {
91 readonly wireBytes: number;
92 readonly decodedBytes: number;
93 readonly messages: number;
95​
96export interface WebSocketTransferRecorder {
97 readonly connect: (
98 url: string,
99 protocols: string | string[] | undefined,
100 cookie: string,
101 ) => globalThis.WebSocket;
102 readonly totals: () => WebSocketTransferTotals;
103 readonly negotiatedExtensions: () => string;
105​
106interface NodeWebSocketWithTransport extends NodeSocket.NodeWS.WebSocket {
107 readonly _socket?: {
108 readonly bytesRead: number;
109 };
111​
112function rawDataBytes(data: NodeSocket.NodeWS.RawData): number {
113 if (Array.isArray(data)) {
114 return data.reduce((total, chunk) => total + chunk.byteLength, 0);
115 }
116 return data.byteLength;
118​
119export function makeWebSocketTransferRecorder(): WebSocketTransferRecorder {
120 let socket: NodeWebSocketWithTransport | null = null;
121 let decodedBytes = 0;
122 let messages = 0;
123​
124 return {
125 connect: (url, protocols, cookie) => {
126 const nextSocket = new NodeSocket.NodeWS.WebSocket(url, protocols, {
127 headers: { cookie },
128 perMessageDeflate: true,
129 }) as NodeWebSocketWithTransport;
130 socket = nextSocket;
131 nextSocket.on("message", (data) => {
132 const bytes = rawDataBytes(data);
133 decodedBytes += bytes;
134 messages += 1;
135 });
136 return nextSocket as unknown as globalThis.WebSocket;
137 },
138 totals: () => ({
139 wireBytes: socket?._socket?.bytesRead ?? 0,
140 decodedBytes,
141 messages,
142 }),
143 negotiatedExtensions: () => socket?.extensions ?? "",
144 };
146​
147export function transferDelta(
148 start: WebSocketTransferTotals,
149 end: WebSocketTransferTotals,
150): WebSocketTransferTotals {
151 return {
152 wireBytes: Math.max(0, end.wireBytes - start.wireBytes),
153 decodedBytes: Math.max(0, end.decodedBytes - start.decodedBytes),
154 messages: Math.max(0, end.messages - start.messages),
155 };
157​
158export function countingWsRpcProtocolLayer(input: {
159 readonly url: string;
160 readonly cookie: string;
161 readonly recorder: WebSocketTransferRecorder;
162}) {
163 const webSocketConstructorLayer = Layer.succeed(Socket.WebSocketConstructor, (url, protocols) =>
164 input.recorder.connect(url, protocols, input.cookie),
165 );
166 return RpcClient.layerProtocolSocket().pipe(
167 Layer.provide(
168 Socket.layerWebSocket(input.url, { openTimeout: "10 seconds" }).pipe(
169 Layer.provide(webSocketConstructorLayer),
170 ),
171 ),
172 Layer.provide(RpcSerialization.layerJson),
173 );
175​
176export const makeCountingWsRpcClient = RpcClient.make(WsRpcGroup);
177export type CountingWsRpcClient = Effect.Success<typeof makeCountingWsRpcClient>;