forked from keroxp/servest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
262 lines (243 loc) · 6.82 KB
/
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
258
259
260
261
262
// Copyright 2019-2020 Yusuke Sakurai. All rights reserved. MIT license.
import {
BufReader,
BufWriter,
} from "./vendor/https/deno.land/std/io/bufio.ts";
import { deferred } from "./vendor/https/deno.land/std/async/mod.ts";
import { initServeOptions, readRequest, writeResponse } from "./serveio.ts";
import { createResponder, Responder } from "./responder.ts";
import { promiseWaitQueue, promiseInterrupter } from "./_util.ts";
import { DataHolder, createDataHolder } from "./data_holder.ts";
import { BodyParser } from "./body_parser.ts";
export type HttpBody =
| string
| Uint8Array
| Deno.Reader
| ReadableStream<Uint8Array>;
/** request data for building http request to server */
export interface ClientRequest {
/** full request url with queries */
url: string;
/** HTTP method */
method: string;
/** HTTP Headers */
headers?: Headers;
/** HTTP Body */
body?: HttpBody;
/** HTTP Trailers setter. It will be after finishing writing body. */
trailers?(): Promise<Headers> | Headers;
}
/** response data for building http response to client */
export interface ServerResponse {
/** HTTP status code */
status: number;
/** HTTP headers */
headers?: Headers;
/** HTTP body */
body?: HttpBody | null;
/** HTTP Trailers setter. It will be after finishing writing body. */
trailers?(): Promise<Headers> | Headers;
}
/** Incoming http request for handling request from client */
export interface IncomingRequest extends BodyParser {
/** Raw requested URL (path + query): /path/to/resource?a=1&b=2 */
url: string;
/** Path part of url: /path/to/resource */
path: string;
/** Parsed query part of url: ?a=1&b=2 */
query: URLSearchParams;
/** HTTP method */
method: string;
/** requested protocol. like HTTP/1.1 */
proto: string;
/** HTTP Headers */
headers: Headers;
/** HTTP Body */
body: BodyReader;
/** Cookie */
cookies: Map<string, string>;
/** keep-alive info */
keepAlive?: KeepAlive;
}
export interface KeepAlive {
timeout: number;
max: number;
}
/** Outgoing http response for building request to server */
export interface ServerRequest extends IncomingRequest, DataHolder, Responder {
conn: Deno.Conn;
bufWriter: BufWriter;
bufReader: BufReader;
/** Match result of path patterns */
match: RegExpMatchArray;
}
/** Incoming http response from server to client */
export interface IncomingResponse extends BodyParser {
/** requested protocol. like HTTP/1.1 */
proto: string;
/** request path with queries. always begin with / */
status: number;
/** status text. like OK */
statusText: string;
/** HTTP Headers */
headers: Headers;
/** HTTP Body */
body: BodyReader;
}
export interface BodyReader extends Deno.Reader {
close(): Promise<void>;
}
export interface ClientResponse extends IncomingResponse {
conn: Deno.Conn;
bufWriter: BufWriter;
bufReader: BufReader;
}
/** serve options */
export interface ServeOptions {
/** canceller promise for async iteration. use defer() */
cancel?: Promise<void>;
/** read timeout for keep-alive connection. ms. default=75000(ms) */
keepAliveTimeout?: number;
/** read timeout for all read request. ms. default=75000(ms) */
readTimeout?: number;
}
export type ServeListener = Deno.Closer;
export interface ServeHandler {
(req: ServerRequest): void | Promise<void>;
}
function createListener(opts: {
hostname?: string;
port: number;
}): Deno.Listener {
return Deno.listen({ ...opts, transport: "tcp" });
}
export function listenAndServeTls(
listenOptions: Deno.ListenTlsOptions,
handler: ServeHandler,
opts?: ServeOptions,
): ServeListener {
const listener = Deno.listenTls(listenOptions);
return listenInternal(listener, handler, opts);
}
export function listenAndServe(
listenOptions: Deno.ListenOptions,
handler: ServeHandler,
opts: ServeOptions = {},
): ServeListener {
opts = initServeOptions(opts);
const listener = createListener(listenOptions);
return listenInternal(listener, handler, opts);
}
function listenInternal(
listener: Deno.Listener,
handler: ServeHandler,
opts: ServeOptions = {},
): ServeListener {
let cancel: Promise<void>;
let d = deferred<void>();
if (opts.cancel) {
cancel = Promise.race([opts.cancel, d]);
} else {
cancel = d;
}
const throwIfCancelled = promiseInterrupter({
cancel,
});
let closed = false;
const close = () => {
if (!closed) {
d.resolve();
listener.close();
closed = true;
}
};
const acceptRoutine = () => {
if (closed) return;
throwIfCancelled(listener.accept())
.then((conn) => {
handleKeepAliveConn(conn, handler, opts);
acceptRoutine();
})
.catch(close);
};
acceptRoutine();
return { close };
}
/** Try to continually read and process requests from keep-alive connection. */
export function handleKeepAliveConn(
conn: Deno.Conn,
handler: ServeHandler,
opts: ServeOptions = {},
): void {
const bufReader = new BufReader(conn);
const bufWriter = new BufWriter(conn);
const originalOpts = opts;
const q = promiseWaitQueue<ServerResponse, void>((resp) =>
writeResponse(bufWriter, resp)
);
// ignore keepAliveTimeout and use readTimeout for the first time
scheduleReadRequest({
keepAliveTimeout: opts.readTimeout,
readTimeout: opts.readTimeout,
cancel: opts.cancel,
});
function scheduleReadRequest(opts: ServeOptions) {
processRequest(opts)
.then((v) => {
if (v) scheduleReadRequest(v);
})
.catch(() => {
conn.close();
});
}
async function processRequest(
opts: ServeOptions,
): Promise<ServeOptions | undefined> {
const baseReq = await readRequest(bufReader, opts);
let responded: Promise<void> = Promise.resolve();
const onResponse = (resp: ServerResponse) => {
responded = q.enqueue(resp);
return responded;
};
const responder = createResponder(bufWriter, onResponse);
const match = baseReq.url.match(/^\//);
if (!match) {
throw new Error("malformed url");
}
const dataHolder = createDataHolder();
const req: ServerRequest = {
...baseReq,
bufWriter,
bufReader,
conn,
...responder,
...dataHolder,
match,
};
await handler(req);
await responded;
await req.body.close();
if (req.respondedStatus() === 101) {
// If upgraded, stop processing
return;
}
let keepAliveTimeout = originalOpts.keepAliveTimeout;
if (req.keepAlive && req.keepAlive.max <= 0) {
throw new Error("keep-alive ended");
}
if (req.headers.get("connection") === "close") {
throw new Error("connection closed header");
}
if (req.keepAlive) {
keepAliveTimeout = Math.min(
keepAliveTimeout!,
req.keepAlive.timeout * 1000,
);
}
return {
keepAliveTimeout,
readTimeout: opts.readTimeout,
cancel: opts.cancel,
};
}
}