-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhttp_server.js
More file actions
195 lines (163 loc) · 4.91 KB
/
http_server.js
File metadata and controls
195 lines (163 loc) · 4.91 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
// Copyright Titanium I.T. LLC.
import * as ensure from "util/ensure.js";
import * as type from "util/type.js";
import http from "node:http";
import EventEmitter from "node:events";
import { HttpServerRequest } from "http/http_server_request.js";
import { HttpServerResponse } from "http/http_server_response.js";
import { Log } from "infrastructure/log.js";
const ROUTER_TYPE = {
routeAsync: Function,
};
/** A general-purpose HTTP server. */
export class HttpServer {
/**
* Factory method. Creates the server instance, but doesn't start it.
* @returns {HttpServer} the server
*/
static create() {
ensure.signature(arguments, []);
return new HttpServer(http);
}
/**
* Factory method. Creates a 'nulled' server instance that simulates listening on a port rather than
* actually doing so.
* @returns {HttpServer} the nulled server
*/
static createNull() {
ensure.signature(arguments, []);
return new HttpServer(stubbedHttp);
}
/** Only for use by tests. (Use a factory method instead.) */
constructor(http) {
ensure.signature(arguments, [ Object ]);
this._http = http;
this._started = false;
this._nodeServer = http.createServer();
}
/**
* @returns {boolean} true if the server has been started
*/
get isStarted() {
return this._started;
}
/**
* @returns {number | null} the port the server is listening on, or null if it hasn't been started
*/
get port() {
return this.isStarted ? this._port : null;
}
/**
* Start the server.
* @param port the port to listen on
* @param log logger to use for internal server errors
* @param router router for handling requests
*/
async startAsync(port, log, router) {
ensure.signatureMinimum(arguments, [ Number, Log, ROUTER_TYPE ]);
this.#ensureStopped("Can't start server because it's already running");
this._port = port;
this._log = log;
this._router = router;
this._started = true; // located before promise to avoid potential race condition
await new Promise((resolve, reject) => {
this._nodeServer.on("listening", () => this.#onStartup(resolve));
this._nodeServer.on("error", (err) => this.#onStartupError(err, reject));
this._nodeServer.on("request", (request, response) => this.#onRequestAsync(request, response));
this._nodeServer.listen(this._port);
});
}
/**
* Stop the server.
*/
async stopAsync() {
ensure.signature(arguments, []);
this.#ensureStarted("Can't stop server because it isn't running");
await new Promise((resolve, reject) => {
this._nodeServer.on("close", resolve);
this._nodeServer.close();
});
this._started = false;
}
/**
* Simulate an HTTP request.
* @param httpRequest the request to simulate
* @returns {Promise<HttpServerResponse>} the HTTP response
*/
async simulateRequestAsync(httpRequest = HttpServerRequest.createNull()) {
ensure.signature(arguments, [[ undefined, HttpServerRequest ]]);
this.#ensureStarted("Can't simulate request because server isn't running");
return await this.#handleRequestAsync(httpRequest);
}
#onStartup(resolve) {
this._log.info({
message: "server started",
port: this._port,
});
resolve();
}
#onStartupError(err, reject) {
reject(new Error(`Couldn't start server due to error: ${err.message}`));
}
async #onRequestAsync(nodeRequest, nodeResponse) {
const httpRequest = HttpServerRequest.create(nodeRequest);
const httpResponse = await this.#handleRequestAsync(httpRequest);
sendResponse(httpResponse, nodeResponse);
}
async #handleRequestAsync(httpRequest) {
try {
const response = await this._router.routeAsync(httpRequest);
const typeError = type.check(response, HttpServerResponse);
if (typeError !== null) {
return internalServerError(this._log, response, "request handler returned invalid response");
}
else {
return response;
}
}
catch (err) {
return internalServerError(this._log, err, "request handler threw exception");
}
}
#ensureStarted(message) {
if (!this.isStarted) throw new Error(message);
}
#ensureStopped(message) {
if (this.isStarted) throw new Error(message);
}
}
function sendResponse(httpResponse, nodeResponse) {
nodeResponse.statusCode = httpResponse.status;
setHeaders(nodeResponse, httpResponse.headers);
nodeResponse.end(httpResponse.body);
}
function setHeaders(nodeResponse, headers) {
Object.entries(headers).forEach(([ name, value ]) => {
nodeResponse.setHeader(name, value);
});
}
function internalServerError(log, details, message) {
log.emergency({ message, details });
return HttpServerResponse.createPlainTextResponse({
status: 500,
body: "Internal Server Error",
debug: {
message,
details: details instanceof Error ? details.stack : details,
},
});
}
/** Embedded Stub **/
const stubbedHttp = {
createServer() {
return new StubbedNodeServer();
}
};
class StubbedNodeServer extends EventEmitter {
listen() {
setImmediate(() => this.emit("listening"));
}
close() {
setImmediate(() => this.emit("close"));
}
}