forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.ts
535 lines (496 loc) · 17.7 KB
/
application.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// Copyright 2018-2021 the oak authors. All rights reserved. MIT license.
import { Context } from "./context.ts";
import { assert, Status, STATUS_TEXT } from "./deps.ts";
import {
hasNativeHttp,
HttpServerNative,
NativeRequest,
} from "./http_server_native.ts";
import { HttpServerStd } from "./http_server_std.ts";
import type { ServerRequest, ServerResponse } from "./http_server_std.ts";
import { Key, KeyStack } from "./keyStack.ts";
import { compose, Middleware } from "./middleware.ts";
import {
FetchEventListenerObject,
Server,
ServerConstructor,
} from "./types.d.ts";
import { isConn } from "./util.ts";
export interface ListenOptionsBase extends Deno.ListenOptions {
secure?: false;
signal?: AbortSignal;
}
export interface ListenOptionsTls extends Deno.ListenTlsOptions {
/** Application-Layer Protocol Negotiation (ALPN) protocols to announce to
* the client. If not specified, no ALPN extension will be included in the
* TLS handshake.
*
* **NOTE** this is part of the native HTTP server in Deno 1.9 or later,
* which requires the `--unstable` flag to be available.
*/
alpnProtocols?: string[];
secure: true;
signal?: AbortSignal;
}
export interface HandleMethod {
/** Handle an individual server request, returning the server response. This
* is similar to `.listen()`, but opening the connection and retrieving
* requests are not the responsibility of the application. If the generated
* context gets set to not to respond, then the method resolves with
* `undefined`, otherwise it resolves with a request that is compatible with
* `std/http/server`. */
(
request: ServerRequest,
secure?: boolean,
): Promise<ServerResponse | undefined>;
/** Handle an individual server request, returning the server response. This
* is similar to `.listen()`, but opening the connection and retrieving
* requests are not the responsibility of the application. If the generated
* context gets set to not to respond, then the method resolves with
* `undefined`, otherwise it resolves with a request that is compatible with
* `std/http/server`. */
(
request: Request,
conn?: Deno.Conn,
secure?: boolean,
): Promise<Response | undefined>;
}
export type ListenOptions = ListenOptionsTls | ListenOptionsBase;
interface ApplicationErrorEventListener<S extends AS, AS> {
(evt: ApplicationErrorEvent<S, AS>): void | Promise<void>;
}
interface ApplicationErrorEventListenerObject<S extends AS, AS> {
handleEvent(evt: ApplicationErrorEvent<S, AS>): void | Promise<void>;
}
interface ApplicationErrorEventInit<S extends AS, AS extends State>
extends ErrorEventInit {
context?: Context<S, AS>;
}
type ApplicationErrorEventListenerOrEventListenerObject<S extends AS, AS> =
| ApplicationErrorEventListener<S, AS>
| ApplicationErrorEventListenerObject<S, AS>;
interface ApplicationListenEventListener {
(evt: ApplicationListenEvent): void | Promise<void>;
}
interface ApplicationListenEventListenerObject {
handleEvent(evt: ApplicationListenEvent): void | Promise<void>;
}
interface ApplicationListenEventInit extends EventInit {
hostname?: string;
port: number;
secure: boolean;
serverType: "std" | "native" | "custom";
}
type ApplicationListenEventListenerOrEventListenerObject =
| ApplicationListenEventListener
| ApplicationListenEventListenerObject;
export interface ApplicationOptions<S> {
/** An initial set of keys (or instance of `KeyGrip`) to be used for signing
* cookies produced by the application. */
keys?: KeyStack | Key[];
/** If set to `true`, proxy headers will be trusted when processing requests.
* This defaults to `false`. */
proxy?: boolean;
/** A server constructor to use instead of the default server for receiving
* requests. When the native HTTP server is detected in the environment, then
* the native server will be used, otherwise the `std/http` server will be
* used. Passing either `HTTPServerStd` or `HTTPServerNative` will override
* this behavior.
*/
serverConstructor?: ServerConstructor<ServerRequest | NativeRequest>;
/** The initial state object for the application, of which the type can be
* used to infer the type of the state for both the application and any of the
* application's context. */
state?: S;
}
interface RequestState {
handling: Set<Promise<void>>;
closing: boolean;
closed: boolean;
server: Server<ServerRequest | NativeRequest>;
}
// deno-lint-ignore no-explicit-any
export type State = Record<string | number | symbol, any>;
const ADDR_REGEXP = /^\[?([^\]]*)\]?:([0-9]{1,5})$/;
export class ApplicationErrorEvent<S extends AS, AS extends State>
extends ErrorEvent {
context?: Context<S, AS>;
constructor(eventInitDict: ApplicationErrorEventInit<S, AS>) {
super("error", eventInitDict);
this.context = eventInitDict.context;
}
}
export class ApplicationListenEvent extends Event {
hostname?: string;
port: number;
secure: boolean;
serverType: "std" | "native" | "custom";
constructor(eventInitDict: ApplicationListenEventInit) {
super("listen", eventInitDict);
this.hostname = eventInitDict.hostname;
this.port = eventInitDict.port;
this.secure = eventInitDict.secure;
this.serverType = eventInitDict.serverType;
}
}
/** A class which registers middleware (via `.use()`) and then processes
* inbound requests against that middleware (via `.listen()`).
*
* The `context.state` can be typed via passing a generic argument when
* constructing an instance of `Application`.
*/
// deno-lint-ignore no-explicit-any
export class Application<AS extends State = Record<string, any>>
extends EventTarget {
#composedMiddleware?: (context: Context<AS, AS>) => Promise<unknown>;
#eventHandler?: FetchEventListenerObject;
#keys?: KeyStack;
#middleware: Middleware<State, Context<State, AS>>[] = [];
#serverConstructor: ServerConstructor<ServerRequest | NativeRequest>;
/** A set of keys, or an instance of `KeyStack` which will be used to sign
* cookies read and set by the application to avoid tampering with the
* cookies. */
get keys(): KeyStack | Key[] | undefined {
return this.#keys;
}
set keys(keys: KeyStack | Key[] | undefined) {
if (!keys) {
this.#keys = undefined;
return;
} else if (Array.isArray(keys)) {
this.#keys = new KeyStack(keys);
} else {
this.#keys = keys;
}
}
/** If `true`, proxy headers will be trusted when processing requests. This
* defaults to `false`. */
proxy: boolean;
/** Generic state of the application, which can be specified by passing the
* generic argument when constructing:
*
* const app = new Application<{ foo: string }>();
*
* Or can be contextually inferred based on setting an initial state object:
*
* const app = new Application({ state: { foo: "bar" } });
*
* When a new context is created, the application's state is cloned and the
* state is unique to that request/response. Changes can be made to the
* application state that will be shared with all contexts.
*/
state: AS;
constructor(options: ApplicationOptions<AS> = {}) {
super();
const {
state,
keys,
proxy,
serverConstructor = hasNativeHttp() ? HttpServerNative : HttpServerStd,
} = options;
this.proxy = proxy ?? false;
this.keys = keys;
this.state = state ?? {} as AS;
this.#serverConstructor = serverConstructor;
}
#getComposed(): ((context: Context<AS, AS>) => Promise<unknown>) {
if (!this.#composedMiddleware) {
this.#composedMiddleware = compose(this.#middleware);
}
return this.#composedMiddleware;
}
/** Deal with uncaught errors in either the middleware or sending the
* response. */
// deno-lint-ignore no-explicit-any
#handleError(context: Context<AS>, error: any): void {
if (!(error instanceof Error)) {
error = new Error(`non-error thrown: ${JSON.stringify(error)}`);
}
const { message } = error;
this.dispatchEvent(new ApplicationErrorEvent({ context, message, error }));
if (!context.response.writable) {
return;
}
for (const key of context.response.headers.keys()) {
context.response.headers.delete(key);
}
if (error.headers && error.headers instanceof Headers) {
for (const [key, value] of error.headers) {
context.response.headers.set(key, value);
}
}
context.response.type = "text";
const status: Status = context.response.status =
error instanceof Deno.errors.NotFound
? 404
: error.status && typeof error.status === "number"
? error.status
: 500;
context.response.body = error.expose
? error.message
: STATUS_TEXT.get(status);
}
/** Processing registered middleware on each request. */
async #handleRequest(
request: ServerRequest | NativeRequest,
secure: boolean,
state: RequestState,
): Promise<void> {
const context = new Context(this, request, secure);
let resolve: () => void;
const handlingPromise = new Promise<void>((res) => resolve = res);
state.handling.add(handlingPromise);
if (!state.closing && !state.closed) {
try {
await this.#getComposed()(context);
} catch (err) {
this.#handleError(context, err);
}
}
if (context.respond === false) {
context.response.destroy();
resolve!();
state.handling.delete(handlingPromise);
return;
}
let closeResources = true;
try {
if (request instanceof NativeRequest) {
closeResources = false;
await request.respond(await context.response.toDomResponse());
} else {
await request.respond(await context.response.toServerResponse());
}
if (state.closing) {
state.server.close();
state.closed = true;
}
} catch (err) {
this.#handleError(context, err);
} finally {
context.response.destroy(closeResources);
resolve!();
state.handling.delete(handlingPromise);
}
}
/** Add an event listener for an `"error"` event which occurs when an
* un-caught error occurs when processing the middleware or during processing
* of the response. */
addEventListener<S extends AS>(
type: "error",
listener: ApplicationErrorEventListenerOrEventListenerObject<S, AS> | null,
options?: boolean | AddEventListenerOptions,
): void;
/** Add an event listener for a `"listen"` event which occurs when the server
* has successfully opened but before any requests start being processed. */
addEventListener(
type: "listen",
listener: ApplicationListenEventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions,
): void;
/** Add an event listener for an event. Currently valid event types are
* `"error"` and `"listen"`. */
addEventListener(
type: "error" | "listen",
listener: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions,
): void {
super.addEventListener(type, listener, options);
}
/** When using Deno Deploy, this method can create an event handler object
* for the application which can be registered as a fetch event handler.
*
* ```
* import { Application } from "https://deno.land/x/oak/mod.ts";
*
* const app = new App();
* app.use((ctx) => ctx.response.body = "hello oak");
*
* addEventListener("fetch", app.fetchEventHandler());
* ```
*/
fetchEventHandler(): FetchEventListenerObject {
if (this.#eventHandler) {
return this.#eventHandler;
}
return this.#eventHandler = {
handleEvent: async (requestEvent) => {
let resolve: (response: Response) => void;
// deno-lint-ignore no-explicit-any
let reject: (reason: any) => void;
const responsePromise = new Promise<Response>((res, rej) => {
resolve = res;
reject = rej;
});
const respondedPromise = requestEvent.respondWith(responsePromise);
const response = await this.handle(requestEvent.request);
if (response) {
resolve!(response);
} else {
reject!(new Error("No response returned from app handler."));
}
try {
await respondedPromise;
} catch (error) {
this.dispatchEvent(new ApplicationErrorEvent({ error }));
}
},
};
}
/** Handle an individual server request, returning the server response. This
* is similar to `.listen()`, but opening the connection and retrieving
* requests are not the responsibility of the application. If the generated
* context gets set to not to respond, then the method resolves with
* `undefined`, otherwise it resolves with a request that is compatible with
* `std/http/server`. */
handle = (async (
request: ServerRequest | Request,
secureOrConn: Deno.Conn | undefined,
secure = false,
): Promise<ServerResponse | Response | undefined> => {
if (!this.#middleware.length) {
throw new TypeError("There is no middleware to process requests.");
}
let contextRequest: ServerRequest | NativeRequest;
if (request instanceof Request) {
assert(isConn(secureOrConn) || typeof secureOrConn === "undefined");
contextRequest = new NativeRequest({
request,
respondWith() {
return Promise.resolve(undefined);
},
}, secureOrConn);
} else {
assert(
typeof secureOrConn === "boolean" ||
typeof secureOrConn === "undefined",
);
secure = secureOrConn ?? false;
contextRequest = request;
}
const context = new Context(
this,
contextRequest,
secure as boolean | undefined,
);
try {
await this.#getComposed()(context);
} catch (err) {
this.#handleError(context, err);
}
if (context.respond === false) {
context.response.destroy();
return;
}
try {
const response = contextRequest instanceof NativeRequest
? await context.response.toDomResponse()
: await context.response.toServerResponse();
context.response.destroy(false);
return response;
} catch (err) {
// deno-lint-ignore no-unreachable
this.#handleError(context, err);
// deno-lint-ignore no-unreachable
throw err;
}
}) as HandleMethod;
/** Start listening for requests, processing registered middleware on each
* request. If the options `.secure` is undefined or `false`, the listening
* will be over HTTP. If the options `.secure` property is `true`, a
* `.certFile` and a `.keyFile` property need to be supplied and requests
* will be processed over HTTPS. */
async listen(addr: string): Promise<void>;
/** Start listening for requests, processing registered middleware on each
* request. If the options `.secure` is undefined or `false`, the listening
* will be over HTTP. If the options `.secure` property is `true`, a
* `.certFile` and a `.keyFile` property need to be supplied and requests
* will be processed over HTTPS. */
async listen(options: ListenOptions): Promise<void>;
async listen(options: string | ListenOptions): Promise<void> {
if (!this.#middleware.length) {
throw new TypeError("There is no middleware to process requests.");
}
if (typeof options === "string") {
const match = ADDR_REGEXP.exec(options);
if (!match) {
throw TypeError(`Invalid address passed: "${options}"`);
}
const [, hostname, portStr] = match;
options = { hostname, port: parseInt(portStr, 10) };
}
const server = new this.#serverConstructor(this, options);
const { signal } = options;
const state = {
closed: false,
closing: false,
handling: new Set<Promise<void>>(),
server,
};
if (signal) {
signal.addEventListener("abort", () => {
if (!state.handling.size) {
server.close();
state.closed = true;
}
state.closing = true;
});
}
const { hostname, port, secure = false } = options;
const serverType = server instanceof HttpServerStd
? "std"
: server instanceof HttpServerNative
? "native"
: "custom";
this.dispatchEvent(
new ApplicationListenEvent({ hostname, port, secure, serverType }),
);
try {
for await (const request of server) {
this.#handleRequest(request, secure, state);
}
await Promise.all(state.handling);
} catch (error) {
const message = error instanceof Error
? error.message
: "Application Error";
this.dispatchEvent(
new ApplicationErrorEvent({ message, error }),
);
}
}
/** Register middleware to be used with the application. Middleware will
* be processed in the order it is added, but middleware can control the flow
* of execution via the use of the `next()` function that the middleware
* function will be called with. The `context` object provides information
* about the current state of the application.
*
* Basic usage:
*
* ```ts
* const import { Application } from "https://deno.land/x/oak/mod.ts";
*
* const app = new Application();
*
* app.use((ctx, next) => {
* ctx.request; // contains request information
* ctx.response; // setups up information to use in the response;
* await next(); // manages the flow control of the middleware execution
* });
*
* await app.listen({ port: 80 });
* ```
*/
use<S extends State = AS>(
middleware: Middleware<S, Context<S, AS>>,
...middlewares: Middleware<S, Context<S, AS>>[]
): Application<S extends AS ? S : (S & AS)>;
use<S extends State = AS>(
...middleware: Middleware<S, Context<S, AS>>[]
): Application<S extends AS ? S : (S & AS)> {
this.#middleware.push(...middleware);
this.#composedMiddleware = undefined;
// deno-lint-ignore no-explicit-any
return this as Application<any>;
}
}