2020-09-21 08:26:41 -04:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-02-26 17:36:05 -05:00
|
|
|
// This is not a real HTTP server. We read blindly one time into 'requestBuf',
|
|
|
|
// then write this fixed 'responseBuf'. The point of this benchmark is to
|
|
|
|
// exercise the event loop in a simple yet semi-realistic way.
|
|
|
|
const requestBuf = new Uint8Array(64 * 1024);
|
|
|
|
const responseBuf = new Uint8Array(
|
|
|
|
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n"
|
|
|
|
.split("")
|
2020-07-14 15:24:17 -04:00
|
|
|
.map((c) => c.charCodeAt(0)),
|
2019-02-26 17:36:05 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
/** Listens on 0.0.0.0:4500, returns rid. */
|
|
|
|
function listen() {
|
2020-08-20 09:45:59 -04:00
|
|
|
const { rid } = Deno.core.jsonOpSync("listen", {});
|
|
|
|
return rid;
|
2019-02-26 17:36:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Accepts a connection, returns rid. */
|
2020-08-20 09:45:59 -04:00
|
|
|
async function accept(serverRid) {
|
|
|
|
const { rid } = await Deno.core.jsonOpAsync("accept", { rid: serverRid });
|
|
|
|
return rid;
|
2019-02-26 17:36:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reads a packet from the rid, presumably an http request. data is ignored.
|
|
|
|
* Returns bytes read.
|
|
|
|
*/
|
2020-08-21 05:47:57 -04:00
|
|
|
async function read(rid, data) {
|
|
|
|
const { nread } = await Deno.core.jsonOpAsync("read", { rid }, data);
|
|
|
|
return nread;
|
2019-02-26 17:36:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Writes a fixed HTTP response to the socket rid. Returns bytes written. */
|
2020-08-21 05:47:57 -04:00
|
|
|
async function write(rid, data) {
|
|
|
|
const { nwritten } = await Deno.core.jsonOpAsync("write", { rid }, data);
|
|
|
|
return nwritten;
|
2019-02-26 17:36:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
function close(rid) {
|
2020-08-21 05:47:57 -04:00
|
|
|
Deno.core.jsonOpSync("close", { rid });
|
2019-02-26 17:36:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
async function serve(rid) {
|
|
|
|
while (true) {
|
|
|
|
const nread = await read(rid, requestBuf);
|
|
|
|
if (nread <= 0) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
const nwritten = await write(rid, responseBuf);
|
|
|
|
if (nwritten < 0) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
close(rid);
|
|
|
|
}
|
|
|
|
|
|
|
|
async function main() {
|
2020-08-21 05:47:57 -04:00
|
|
|
Deno.core.ops();
|
2019-02-26 17:36:05 -05:00
|
|
|
|
2019-03-09 12:30:38 -05:00
|
|
|
const listenerRid = listen();
|
2020-08-21 11:14:47 -04:00
|
|
|
Deno.core.print(`http_bench_json_ops listening on http://127.0.0.1:4544/\n`);
|
2020-08-21 05:47:57 -04:00
|
|
|
|
|
|
|
for (;;) {
|
2019-03-09 12:30:38 -05:00
|
|
|
const rid = await accept(listenerRid);
|
2019-02-26 17:36:05 -05:00
|
|
|
if (rid < 0) {
|
2019-03-26 08:22:07 -04:00
|
|
|
Deno.core.print(`accept error ${rid}`);
|
2019-02-26 17:36:05 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
serve(rid);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
main();
|