-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.ts
More file actions
246 lines (220 loc) · 8.53 KB
/
Server.ts
File metadata and controls
246 lines (220 loc) · 8.53 KB
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
import EventEmitter from "node:events";
import http from "node:http";
import packageJson from "../package.json" with {type: "json"};
import {Request} from "./Request.js";
import {EmptyResponse} from "./response/index.js";
import {Response} from "./response/Response.js";
import {RouteRegistry} from "./routing/RouteRegistry.js";
import {ServerErrorRegistry} from "./ServerErrorRegistry.js";
/**
* An HTTP server.
* @see {@link Server.Events} for events.
*/
class Server extends EventEmitter<Server.Events> {
/**
* Headers sent with every response.
*/
public readonly globalHeaders: Headers;
/**
* This server's route registry.
*/
public readonly routes = new RouteRegistry();
/**
* This server's error registry.
*/
public readonly errors = new ServerErrorRegistry();
private readonly server: http.Server;
private readonly port?: number;
private readonly copyOrigin: boolean;
private readonly handleConditionalRequests: boolean;
/**
* Create a new HTTP server.
* @param options Server options.
*/
public constructor(options?: Server.Options) {
super();
this.server = http.createServer({
joinDuplicateHeaders: true,
}, this.listener.bind(this));
this.globalHeaders = new Headers(options?.globalHeaders);
if (!this.globalHeaders.has("server"))
this.globalHeaders.set("Server", `cldn/${packageJson.version}`);
this.port = options?.port;
this.copyOrigin = options?.copyOrigin ?? false;
this.handleConditionalRequests = options?.handleConditionalRequests ?? true;
if (this.port !== undefined) this.listen(this.port).then();
this.once("listening", () => {
if (this.listenerCount("error") === 0)
this.on("error", e => console.error("Internal Server Error:", e));
});
}
/** @internal **/
public get _keepAliveTimeout() {
return this.server.keepAliveTimeout;
}
/**
* Close the server. Will stop accepting new connections and wait for existing connections to close.
* @param [timeout=5000] Maximum time to wait for existing connections to close before forcibly closing them.
*/
public async close(timeout = 5000): Promise<void> {
if (!this.server.listening)
throw new Error("Server is not listening.");
this.emit("closing");
let timeoutId: NodeJS.Timeout;
await Promise.race([
new Promise<void>(resolve => {
timeoutId = setTimeout(() => {
this.server.closeAllConnections();
resolve();
}, timeout)
}),
new Promise<void>(resolve => {
clearTimeout(timeoutId);
this.server.close(() => resolve());
}),
]);
this.emit("closed");
}
/**
* Start listening for connections.
*/
public listen(port: number): Promise<void> {
if (this.server.listening)
throw new Error("Server is already listening.");
return new Promise(resolve => {
this.server.listen(port, process.env.HOST, () => {
this.emit("listening", port, process.env.HOST);
resolve();
});
});
}
private async listener(req: http.IncomingMessage, res: http.ServerResponse) {
let apiRequest: Request;
try {
apiRequest = Request.incomingMessage(req);
}
catch (e) {
if (e instanceof Request.BadUrlError) {
this.errors._get(ServerErrorRegistry.ErrorCodes.BAD_URL, null)._send(res, this);
return;
}
if (e instanceof Request.SocketClosedError)
return;
throw e;
}
for (const [key, value] of this.globalHeaders)
apiRequest._responseHeaders.set(key, value);
if (this.copyOrigin) {
apiRequest._responseHeaders.set("access-control-allow-origin", apiRequest.headers.get("Origin") ?? "*");
apiRequest._responseHeaders.set("vary", "origin");
}
let response: Response;
try {
response = await this.routes.handle(apiRequest);
}
catch (e) {
if (e instanceof RouteRegistry.NoRouteError)
response = this.errors._get(ServerErrorRegistry.ErrorCodes.NO_ROUTE, apiRequest);
else {
this.emit("error", e as any);
response = this.errors._get(ServerErrorRegistry.ErrorCodes.INTERNAL, apiRequest);
}
}
await this.sendResponse(response, res, apiRequest);
}
private async sendResponse(response: Response, res: http.ServerResponse, req: Request): Promise<void> {
conditional: if (
this.handleConditionalRequests
&& response.statusCode === 200
&& [Request.Method.GET, Request.Method.HEAD].includes(req.method)
) {
const responseHeaders = response.allHeaders(res, this, req);
const etag = responseHeaders.get("etag");
const lastModified = responseHeaders.has("last-modified")
? new Date(responseHeaders.get("last-modified")!)
: null;
if (etag === null && lastModified === null)
break conditional;
if (req.headers.has("if-match")) {
if (!this.getETags(req.headers.get("if-match")!)
.filter(t => !t.startsWith("W/"))
.includes(etag!))
return this.errors._get(ServerErrorRegistry.ErrorCodes.PRECONDITION_FAILED, req)._send(res, this, req);
}
else if (req.headers.has("if-unmodified-since")) {
if (lastModified === null
|| lastModified.getTime() > new Date(req.headers.get("if-unmodified-since")!).getTime())
return this.errors._get(ServerErrorRegistry.ErrorCodes.PRECONDITION_FAILED, req)._send(res, this, req);
}
if (req.headers.has("if-none-match")) {
if (this.getETags(req.headers.get("if-none-match")!)
.includes(etag!))
return new EmptyResponse(responseHeaders, 304)._send(res, this, req);
}
else if (req.headers.has("if-modified-since")) {
if (lastModified !== null
&& lastModified.getTime() <= new Date(req.headers.get("if-modified-since")!).getTime())
return new EmptyResponse(responseHeaders, 304)._send(res, this, req);
}
}
response._send(res, this, req);
}
private getETags(header: string) {
return header
.split(",")
.map(t => t.trim())
}
}
namespace Server {
/**
* Server options
*/
export interface Options {
/**
* The HTTP listener port. From 1 to 65535. Ports 1–1023 require
* privileges. If not set, {@link Server#listen|Server.listen()} must be called manually.
*/
readonly port?: number;
/**
* Headers to send with every response.
*/
readonly globalHeaders?: HeadersInit;
/**
* Whether to set the `Access-Control-Allow-Origin` response header to copy the `Origin` request header.
* If enabled and the client does not set `Origin`, the header will be set to `*`.
* Will also enable setting `Vary: Origin`.
* @default false
*/
readonly copyOrigin?: boolean;
/**
* Automatically handle conditional requests for GET and HEAD requests that result in a 200 status code.
* `If-Range` headers are ignored.
* @default true
*/
readonly handleConditionalRequests?: boolean;
}
/**
* Server events map
*/
export interface Events {
/**
* Server is listening and ready to accept connections.
*/
listening: [port: number, host?: string];
/**
* The server is closing and not accepting new connections.
*/
closing: [void];
/**
* All connections have ended and the server has closed.
*/
closed: [void];
/**
* An uncaught error occurred. Client has been sent {@link ServerErrorRegistry.ErrorCodes.INTERNAL} error.
* If no listener is registered when the server begins listening for the first time, a default listener will be
* added to direct errors to stderr.
*/
error: [Error];
}
}
export {Server};