forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_server_native.ts
200 lines (170 loc) · 5.07 KB
/
http_server_native.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
// Copyright 2018-2021 the oak authors. All rights reserved. MIT license.
import type { Application, State } from "./application.ts";
import type { Server } from "./types.d.ts";
import { isListenTlsOptions } from "./util.ts";
export type Respond = (r: Response | Promise<Response>) => void;
export const DomResponse: typeof Response = Response;
// Since the native bindings are currently unstable in Deno, we will add the
// interfaces here, so that we can type check oak without requiring the
// `--unstable` flag to be used.
interface RequestEvent {
readonly request: Request;
respondWith(r: Response | Promise<Response>): Promise<void>;
}
interface HttpConn extends AsyncIterable<RequestEvent> {
readonly rid: number;
nextRequest(): Promise<RequestEvent | null>;
close(): void;
}
const serveHttp: (conn: Deno.Conn) => HttpConn = "serveHttp" in Deno
? // deno-lint-ignore no-explicit-any
(Deno as any).serveHttp.bind(
Deno,
)
: undefined;
/**
* Detects if the current version of Deno provides the native HTTP bindings,
* which may be only available under the `--unstable` flag.
*/
export function hasNativeHttp(): boolean {
return !!serveHttp;
}
export class NativeRequest {
#conn?: Deno.Conn;
// deno-lint-ignore no-explicit-any
#reject!: (reason?: any) => void;
#request: Request;
#requestPromise: Promise<void>;
#resolve!: (value: Response) => void;
#resolved = false;
constructor(requestEvent: RequestEvent, conn?: Deno.Conn) {
this.#conn = conn;
this.#request = requestEvent.request;
const p = new Promise<Response>((resolve, reject) => {
this.#resolve = resolve;
this.#reject = reject;
});
this.#requestPromise = requestEvent.respondWith(p);
}
get body(): ReadableStream<Uint8Array> | null {
return this.#request.body;
}
get donePromise(): Promise<void> {
return this.#requestPromise;
}
get headers(): Headers {
return this.#request.headers;
}
get method(): string {
return this.#request.method;
}
get remoteAddr(): string | undefined {
return (this.#conn?.remoteAddr as Deno.NetAddr).hostname;
}
get request(): Request {
return this.#request;
}
get url(): string {
try {
const url = new URL(this.#request.url);
return this.#request.url.replace(url.origin, "");
} catch {
// we don't care about errors, we just want to fall back
}
return this.#request.url;
}
get rawUrl(): string {
return this.#request.url;
}
// deno-lint-ignore no-explicit-any
error(reason?: any): void {
if (this.#resolved) {
throw new Error("Request already responded to.");
}
this.#reject(reason);
this.#resolved = true;
}
respond(response: Response): Promise<void> {
if (this.#resolved) {
throw new Error("Request already responded to.");
}
this.#resolve(response);
this.#resolved = true;
return this.#requestPromise;
}
}
// deno-lint-ignore no-explicit-any
export class HttpServerNative<AS extends State = Record<string, any>>
implements Server<NativeRequest> {
#app: Application<AS>;
#closed = false;
#options: Deno.ListenOptions | Deno.ListenTlsOptions;
constructor(
app: Application<AS>,
options: Deno.ListenOptions | Deno.ListenTlsOptions,
) {
if (!("serveHttp" in Deno)) {
throw new Error(
"The native bindings for serving HTTP are not available.",
);
}
this.#app = app;
this.#options = options;
}
get app(): Application<AS> {
return this.#app;
}
get closed(): boolean {
return this.#closed;
}
close(): void {
this.#closed = true;
}
[Symbol.asyncIterator](): AsyncIterableIterator<NativeRequest> {
// deno-lint-ignore no-this-alias
const server = this;
const options = this.#options;
const stream = new ReadableStream<NativeRequest>({
start(controller) {
const listener = isListenTlsOptions(options)
? Deno.listenTls(options)
: Deno.listen(options);
async function serve(conn: Deno.Conn) {
const httpConn = serveHttp(conn);
for await (const requestEvent of httpConn) {
const nativeRequest = new NativeRequest(requestEvent, conn);
controller.enqueue(nativeRequest);
try {
await nativeRequest.donePromise;
} catch (error) {
server.app.dispatchEvent(new ErrorEvent("error", { error }));
}
if (server.closed) {
httpConn.close();
listener.close();
controller.close();
return;
}
}
}
async function accept() {
while (true) {
try {
const conn = await listener.accept();
serve(conn);
} catch (error) {
server.app.dispatchEvent(new ErrorEvent("error", { error }));
}
if (server.closed) {
listener.close();
controller.close();
return;
}
}
}
accept();
},
});
return stream[Symbol.asyncIterator]();
}
}