Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discard writes made to an aborted uWS response #682

Merged
merged 1 commit into from
May 31, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 16 additions & 1 deletion lib/userver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ export class uServer extends BaseServer {
class ResponseWrapper {
private statusWritten: boolean = false;
private headers = [];
private isAborted = false;

constructor(readonly res: HttpResponse) {}

Expand Down Expand Up @@ -291,13 +292,17 @@ class ResponseWrapper {
public getHeader() {}

public writeStatus(status: string) {
if (this.isAborted) return;

this.res.writeStatus(status);
this.statusWritten = true;
this.writeBufferedHeaders();
return this;
}

public writeHeader(key: string, value: string) {
if (this.isAborted) return;

if (key === "Content-Length") {
// the content length is automatically added by uWebSockets.js
return;
Expand All @@ -316,6 +321,8 @@ class ResponseWrapper {
}

public end(data) {
if (this.isAborted) return;

if (!this.statusWritten) {
// status will be inferred as "200 OK"
this.writeBufferedHeaders();
Expand All @@ -324,10 +331,18 @@ class ResponseWrapper {
}

public onData(fn) {
if (this.isAborted) return;

this.res.onData(fn);
}

public onAborted(fn) {
this.res.onAborted(fn);
if (this.isAborted) return;

this.res.onAborted(() => {
// Any attempt to use the UWS response object after abort will throw!
this.isAborted = true;
fn();
});
}
}