Skip to content

Commit

Permalink
Short-circuit readRequest() and OP_ACCEPT
Browse files Browse the repository at this point in the history
  • Loading branch information
nayeemrmn committed Feb 19, 2020
1 parent 0e9a003 commit 46157d0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
27 changes: 16 additions & 11 deletions cli/js/net.ts
@@ -1,8 +1,10 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { ErrorKind, DenoError } from "./errors.ts";
import { EOF, Reader, Writer, Closer } from "./io.ts";
import { read, write, close } from "./files.ts";
import * as dispatch from "./dispatch.ts";
import { sendSync, sendAsync } from "./dispatch_json.ts";
import { createResolvable } from "./util.ts";

export type Transport = "tcp";
// TODO support other types:
Expand Down Expand Up @@ -85,30 +87,33 @@ export class ConnImpl implements Conn {
}

export class ListenerImpl implements Listener {
constructor(
readonly rid: number,
public addr: Addr,
private closing: boolean = false
) {}
private closed = createResolvable<void>();

constructor(readonly rid: number, public addr: Addr, closing = false) {
if (closing) {
this.closed.resolve();
}
}

async accept(): Promise<Conn> {
const res = await sendAsync(dispatch.OP_ACCEPT, { rid: this.rid });
const res = await Promise.race([
sendAsync(dispatch.OP_ACCEPT, { rid: this.rid }),
this.closed.then(() => {
throw new DenoError(ErrorKind.Other, "Listener has been closed");
})
]);
return new ConnImpl(res.rid, res.remoteAddr, res.localAddr);
}

close(): void {
this.closing = true;
this.closed.resolve();
close(this.rid);
}

async next(): Promise<IteratorResult<Conn>> {
if (this.closing) {
return { value: undefined, done: true };
}
return await this.accept()
.then(value => ({ value, done: false }))
.catch(e => {
// It wouldn't be correct to simply check this.closing here.
// TODO: Get a proper error kind for this case, don't check the message.
// The current error kind is Other.
if (e.message == "Listener has been closed") {
Expand Down
7 changes: 6 additions & 1 deletion std/http/server.ts
Expand Up @@ -474,11 +474,13 @@ class EventType<T> {

export class Server implements AsyncIterable<ServerRequest> {
private closing = false;
private closed = deferred<void>();

constructor(public listener: Listener) {}

close(): void {
this.closing = true;
this.closed.resolve();
this.listener.close();
}

Expand All @@ -493,7 +495,10 @@ export class Server implements AsyncIterable<ServerRequest> {

while (!this.closing) {
try {
req = await readRequest(conn, bufr);
req = await Promise.race([
readRequest(conn, bufr),
this.closed.then((): Deno.EOF => Deno.EOF)
]);
} catch (e) {
err = e;
break;
Expand Down

0 comments on commit 46157d0

Please sign in to comment.