-
Notifications
You must be signed in to change notification settings - Fork 2
/
handlers.server.ts
257 lines (247 loc) · 6.84 KB
/
handlers.server.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
import { makeReadableStream, makeWebSocket } from "./channel.ts";
import type {
ClientMessage,
ClientMessageHandler,
DataEndMessage,
DataMessage,
RegisterMessage,
ResponseStartMessage,
WSConnectionClosed,
WSMessage,
} from "./messages.ts";
import { arrayBufferSerializer } from "./serializers.ts";
/**
* List of status codes that represent null bodies in responses.
* @type {number[]}
*/
const NULL_BODIES = [101, 204, 205, 304];
/**
* Handler for the 'response-start' client message.
* @param {ClientState} state - The client state.
* @param {ResponseStartMessage} message - The message data.
*/
const onResponseStart: ClientMessageHandler<ResponseStartMessage> = (
state,
message,
) => {
const request = state.ongoingRequests[message.id];
if (!request) {
console.error(
new Date(),
"Didn't find response object, probably dead?",
);
return;
}
const headers = new Headers();
Object.entries(message.headers).forEach(
([key, value]: [string, string | Array<string>]) => {
if (typeof value === "string") {
headers.set(key, value);
} else if (Array.isArray(value)) {
value.forEach((v) => {
headers.append(key, v);
});
}
},
);
const shouldBeNullBody = NULL_BODIES.includes(message.statusCode);
const stream = !shouldBeNullBody && request.responseBodyChan
? makeReadableStream(request.responseBodyChan, state.ch.out.signal)
: undefined;
const resp = new Response(stream, {
status: message.statusCode,
statusText: message.statusMessage,
headers,
});
request.requestObject?.signal?.addEventListener?.("abort", () => {
if (message.id in state.ongoingRequests) {
delete state.ongoingRequests[message.id];
request.responseObject.reject(
new DOMException("Connection closed", "AbortError"),
);
request?.responseBodyChan?.close?.();
}
});
request.responseObject.resolve(resp);
};
/**
* Handler for the 'data' client message.
* @param {ClientState} state - The client state.
* @param {DataMessage} message - The message data.
*/
const data: ClientMessageHandler<DataMessage> = async (state, message) => {
const request = state.ongoingRequests[message.id];
if (!request) {
return;
}
try {
await request.responseBodyChan?.send(
message.chunk,
);
} catch (_err) {
console.log("Request was aborted", _err);
}
};
/**
* Handler for the 'data-end' client message.
* @param {ClientState} state - The client state.
* @param {DataEndMessage} message - The message data.
*/
const onDataEnd: ClientMessageHandler<DataEndMessage> = (state, message) => {
const request = state.ongoingRequests[message.id];
if (!request) {
return;
}
if (message.error) {
request.responseObject.reject(
new DOMException("Connection closed", JSON.stringify(message.error)),
);
return;
}
try {
request.responseBodyChan?.close?.();
} catch (_err) {
console.log(`error closing body chan`, _err);
}
};
/**
* Handler for the 'ws-closed' client message.
* @param {ClientState} state - The client state.
* @param {WSConnectionClosed} message - The message data.
*/
const onWsClosed: ClientMessageHandler<WSConnectionClosed> = (
state,
message,
) => {
delete state.ongoingRequests[message.id];
};
/**
* Handler for the 'ws-message' client message.
* @param {ClientState} state - The client state.
* @param {WSMessage} message - The message data.
*/
const onWsMessage: ClientMessageHandler<WSMessage> = async (state, message) => {
await state.ongoingRequests?.[message.id]?.webSocketChan?.send(message.data);
};
/**
* Handler for the 'ws-opened' client message.
* @param {ClientState} state - The client state.
* @param {DataEndMessage} message - The message data.
*/
const onWsOpened: ClientMessageHandler<DataEndMessage> = async (
state,
message,
) => {
const request = state.ongoingRequests[message.id];
if (!request) {
return;
}
try {
const { socket, response } = Deno.upgradeWebSocket(request.requestObject);
request.responseObject.resolve(response);
const socketChan = await makeWebSocket<
ArrayBuffer,
ArrayBuffer,
ArrayBuffer
>(
socket,
arrayBufferSerializer(),
);
request.webSocketChan = socketChan.out;
(async () => {
const signal = state.ch.out.signal;
try {
for await (const msg of socketChan.in.recv(signal)) {
await state.ch.out.send({
type: "ws-message",
id: message.id,
data: msg,
});
}
if (signal.aborted) {
return;
}
await state.ch.out.send({ type: "ws-closed", id: message.id });
} catch (error) {
if (signal.aborted) {
console.log("sending through a closed channel error", error, message);
} else {
console.error(
`unexpected error when handling websocket message`,
error,
message,
);
}
} finally {
try {
socket.close();
} catch (_err) {
// ignore
}
}
})();
} catch (err) {
console.error(new Date(), "Error upgrading websocket", err);
delete state.ongoingRequests[message.id];
}
};
/**
* Handler for the 'register' client message.
* @param {ClientState} state - The client state.
* @param {RegisterMessage} message - The message data.
*/
const register: ClientMessageHandler<RegisterMessage> = async (
state,
message,
) => {
if (state.apiKeys.includes(message.apiKey)) {
state.controller.link(message.domain);
await state.ch.out.send({
type: "registered",
domain: message.domain,
id: message.id,
});
} else {
console.error(
new Date(),
"Given API key is wrong/not recognised, stopping connection",
message,
);
await state.ch.out.send({ type: "error", message: "Invalid API key" });
state.socket.close();
}
};
/**
* A record mapping client message types to their respective handlers.
* @type {Record<ClientMessage["type"], ClientMessageHandler<any>>}
* @ignore
*/
// deno-lint-ignore no-explicit-any
const handlersByType: Record<ClientMessage["type"], ClientMessageHandler<any>> =
{
"response-start": onResponseStart,
data,
"data-end": onDataEnd,
"ws-closed": onWsClosed,
"ws-message": onWsMessage,
"ws-opened": onWsOpened,
register,
};
/**
* Handles client messages received from the server.
* @param {ClientState} state - The client state.
* @param {ClientMessage} message - The message received from the server.
*/
export const handleClientMessage: ClientMessageHandler = async (
state,
message,
) => {
await handlersByType?.[message.type]?.(state, message)?.catch?.((err) => {
console.error(
"unexpected error happening when handling message",
message,
err,
);
delete state.ongoingRequests[message.id];
});
};