Repository navigation
Expand file tree
/
Copy pathresponse.ts
More file actions
171 lines (150 loc) · 5.02 KB
/
Copy pathresponse.ts
File metadata and controls
171 lines (150 loc) · 5.02 KB
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { ServerResponse } from 'node:http';
import type { Http2ServerResponse } from 'node:http2';
/**
* Checks whether a Node.js `ServerResponse` or `Http2ServerResponse` is destroyed, closed, or ended.
*
* @param destination - The HTTP/1.1 or HTTP/2 server response to check.
* @returns `true` if the response or its underlying stream is destroyed, closed, or ended; otherwise `false`.
*/
function isResponseDestroyedOrClosed(destination: ServerResponse | Http2ServerResponse): boolean {
return (
destination.destroyed ||
destination.closed ||
destination.writableEnded ||
('stream' in destination &&
(!destination.stream || destination.stream.destroyed || destination.stream.closed))
);
}
/**
* Streams a web-standard `Response` into a Node.js `ServerResponse`
* or `Http2ServerResponse`.
*
* This function adapts the web `Response` object to write its content
* to a Node.js response object, handling both HTTP/1.1 and HTTP/2.
*
* @param source - The web-standard `Response` object to stream from.
* @param destination - The Node.js response object (`ServerResponse` or `Http2ServerResponse`) to stream into.
* @returns A promise that resolves once the streaming operation is complete.
*/
export async function writeResponseToNodeResponse(
source: Response,
destination: ServerResponse | Http2ServerResponse,
): Promise<void> {
if (isResponseDestroyedOrClosed(destination)) {
if (source.body && !source.body.locked) {
await source.body.cancel().catch((err) => {
// eslint-disable-next-line no-console
console.error(
`An error occurred while cancelling the response body for: ${destination.req?.url ?? 'unknown'}.`,
err,
);
});
}
return;
}
const { status, headers, body } = source;
destination.statusCode = status;
let cookieHeaderSet = false;
for (const [name, value] of headers.entries()) {
if (name === 'set-cookie') {
if (cookieHeaderSet) {
continue;
}
// Sets the 'set-cookie' header only once to ensure it is correctly applied.
// Concatenating 'set-cookie' values can lead to incorrect behavior, so we use a single value from `headers.getSetCookie()`.
destination.setHeader(name, headers.getSetCookie());
cookieHeaderSet = true;
} else {
destination.setHeader(name, value);
}
}
if ('flushHeaders' in destination) {
destination.flushHeaders();
}
if (!body) {
if (!isResponseDestroyedOrClosed(destination)) {
destination.end();
}
return;
}
let isClosed = isResponseDestroyedOrClosed(destination);
const isDestroyedOrClosed = () => isClosed || isResponseDestroyedOrClosed(destination);
let readerCancelled = false;
const reader = body.getReader();
const cancelReader = (error?: unknown) => {
if (readerCancelled) {
return;
}
readerCancelled = true;
isClosed = true;
destination.off('close', cancelReader);
destination.off('error', cancelReader);
reader.cancel(error).catch((err) => {
// eslint-disable-next-line no-console
console.error(
`An error occurred while writing the response body for: ${destination.req?.url ?? 'unknown'}.`,
err,
);
});
};
destination.once('close', cancelReader);
destination.once('error', cancelReader);
try {
// eslint-disable-next-line no-constant-condition
while (true) {
if (isDestroyedOrClosed()) {
cancelReader();
break;
}
const { done, value } = await reader.read();
if (isDestroyedOrClosed()) {
cancelReader();
break;
}
if (done) {
destination.end();
break;
}
const canContinue = (destination as ServerResponse).write(value);
if (canContinue === false) {
// Explicitly check for `false`, as AWS may return `undefined` even though this is not valid.
// See: https://github.com/CodeGenieApp/serverless-express/issues/683
await new Promise<void>((resolve) => {
if (isDestroyedOrClosed()) {
resolve();
return;
}
const onDrain = () => {
destination.off('close', onClose);
destination.off('error', onClose);
resolve();
};
const onClose = () => {
destination.off('drain', onDrain);
destination.off('close', onClose);
destination.off('error', onClose);
cancelReader();
resolve();
};
destination.once('drain', onDrain);
destination.once('close', onClose);
destination.once('error', onClose);
});
}
}
} catch {
if (!isDestroyedOrClosed()) {
destination.end('Internal server error.');
}
} finally {
destination.off('close', cancelReader);
destination.off('error', cancelReader);
}
}