-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhandlers.client.ts
297 lines (281 loc) · 7.44 KB
/
handlers.client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import {
type Channel,
ignoreIfClosed,
link,
makeChan,
makeChanStream,
makeReadableStream,
makeWebSocket,
} from "./channel.ts";
import type {
ClientMessage,
ClientState,
ErrorMessage,
RegisteredMessage,
RequestAbortedMessage,
RequestDataEndMessage,
RequestDataMessage,
RequestStartMessage,
ServerMessage,
ServerMessageHandler,
WSMessage,
} from "./messages.ts";
import { arrayBufferSerializer } from "./serializers.ts";
/**
* Handler for the 'registered' server message.
* @param {ClientState} state - The client state.
*/
const registered: ServerMessageHandler<RegisteredMessage> = (state) => {
state.live = true;
};
/**
* Handler for the 'error' server message.
* @param {ClientState} state - The client state.
*/
const error: ServerMessageHandler<ErrorMessage> = (state) => {
state.live = false;
};
/**
* Handler for the 'request-start' server message.
* @param {ClientState} state - The client state.
* @param {RequestStartMessage} message - The message data.
*/
const onRequestStart: ServerMessageHandler<RequestStartMessage> = async (
state,
message,
) => {
if (message.headers["upgrade"] === "websocket") {
await handleWebSocket(message, state);
return;
}
const abortCtrl = new AbortController();
state.requests[message.id] = { abortCtrl };
if (!message.hasBody) {
doFetch(message, state, state.ch.out, abortCtrl.signal).catch(
ignoreIfClosed,
).finally(() => {
delete state.requests[message.id];
});
} else {
const bodyData = makeChan<Uint8Array>();
state.requests[message.id]!.body = bodyData;
doFetch(
{ ...message, body: makeReadableStream(bodyData) },
state,
state.ch.out,
abortCtrl.signal,
).catch(ignoreIfClosed).finally(() => {
delete state.requests[message.id];
});
}
};
/**
* Handler for the 'request-data' server message.
* @param {ClientState} state - The client state.
* @param {RequestDataMessage} message - The message data.
*/
const onRequestData: ServerMessageHandler<RequestDataMessage> = async (
state,
message,
) => {
const reqBody = state.requests[message.id]?.body;
if (!reqBody) {
console.info("[req-data] req not found", message.id);
return;
}
await reqBody.send?.(message.chunk);
};
/**
* Handler for the 'request-aborted' server message.
* @param {ClientState} state - The client state.
* @param {RequestAbortedMessage} message - The message data.
*/
const onRequestAborted: ServerMessageHandler<RequestAbortedMessage> = (
state,
message,
) => {
state.requests[message.id]?.abortCtrl?.abort();
};
/**
* Handler for the 'request-data-end' server message.
* @param {ClientState} state - The client state.
* @param {RequestDataEndMessage} message - The message data.
*/
const onRequestDataEnd: ServerMessageHandler<RequestDataEndMessage> = (
state,
message,
) => {
const reqBody = state.requests[message.id]?.body;
if (!reqBody) {
return;
}
reqBody.close();
};
/**
* Handler for the 'ws-message' server message.
* @param {ClientState} state - The client state.
* @param {WSMessage} message - The message data.
*/
const onWsMessage: ServerMessageHandler<WSMessage> = async (state, message) => {
await state.wsSockets?.[message.id]?.send?.(message.data);
};
/**
* Handler for the 'ws-closed' server message.
* @param {ClientState} state - The client state.
* @param {RegisteredMessage} message - The message data.
*/
const onWsClosed: ServerMessageHandler<RegisteredMessage> = (
state,
message,
) => {
const socket = state.wsSockets[message.id];
delete state.wsSockets[message.id];
socket?.close();
};
/**
* Handlers for various server message types.
* @type {Record<ServerMessage["type"], ServerMessageHandler<any>>}
*/
// deno-lint-ignore no-explicit-any
const handlersByType: Record<ServerMessage["type"], ServerMessageHandler<any>> =
{
registered,
error,
"request-aborted": onRequestAborted,
"request-start": onRequestStart,
"request-data": onRequestData,
"request-end": onRequestDataEnd,
"ws-closed": onWsClosed,
"ws-message": onWsMessage,
};
/**
* Handles WebSocket connections.
* @param {RequestStartMessage} message - The WebSocket request message.
* @param {ClientState} state - The client state.
*/
async function handleWebSocket(
message: RequestStartMessage,
state: ClientState,
) {
const ws = new WebSocket(new URL(message.url, state.localAddr));
try {
const wsCh = await makeWebSocket<ArrayBuffer, ArrayBuffer, ArrayBuffer>(
ws,
arrayBufferSerializer(),
);
await state.ch.out.send({
type: "ws-opened",
id: message.id,
});
state.wsSockets[message.id] = ws;
(async () => {
try {
for await (const data of wsCh.in.recv(state.ch.out.signal)) {
await state.ch.out.send({
type: "ws-message",
data,
id: message.id,
});
}
if (state.ch.out.signal.aborted) {
return;
}
await state.ch.out.send({
type: "ws-closed",
id: message.id,
});
} catch (error) {
if (state.ch.out.signal.aborted) {
return;
}
await state.ch.out.send({
type: "ws-closed",
id: message.id,
}).catch(ignoreIfClosed);
throw error;
} finally {
delete state.wsSockets[message.id];
}
})();
} catch (err) {
await state.ch.out.send({
type: "data-end",
error: err,
id: message.id,
}).catch(ignoreIfClosed);
}
}
/**
* Fetches data from a request.
* @param {RequestStartMessage & { body?: ReadableStream; }} request - The request data.
* @param {ClientState} state - The client state.
* @param {Channel<ClientMessage>} clientCh - The client channel.
*/
async function doFetch(
request: RequestStartMessage & { body?: ReadableStream },
state: ClientState,
clientCh: Channel<ClientMessage>,
reqSignal: AbortSignal,
) {
// Read from the stream
const signal = link(clientCh.signal, reqSignal);
try {
const response = await fetch(
new URL(request.url, state.localAddr),
{
...state.client ? { client: state.client } : {},
redirect: "manual",
method: request.method,
headers: state.client
? { ...request.headers, host: request.domain }
: request.headers,
body: request.body,
signal,
},
);
const headers: Record<string, Array<string>> = {};
for (const [key, value] of response.headers.entries()) {
headers[key] ??= [];
headers[key].push(value);
}
await clientCh.send({
type: "response-start",
id: request.id,
statusCode: response.status,
statusMessage: response.statusText,
headers,
});
const body = response?.body;
const stream = body ? makeChanStream(body) : undefined;
for await (const chunk of stream?.recv(signal) ?? []) {
await clientCh.send({
type: "data",
id: request.id,
chunk,
});
}
if (signal.aborted) {
return;
}
await clientCh.send({
type: "data-end",
id: request.id,
});
} catch (err) {
if (signal.aborted) {
return;
}
throw err;
}
}
/**
* Handles server messages.
* @param {ClientState} state - The client state.
* @param {ServerMessage} message - The server message.
*/
export const handleServerMessage: ServerMessageHandler = async (
state,
message,
) => {
await handlersByType?.[message.type]?.(state, message);
};