-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcapturingHttpProxy.ts
More file actions
206 lines (176 loc) · 5.75 KB
/
Copy pathcapturingHttpProxy.ts
File metadata and controls
206 lines (176 loc) · 5.75 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
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
201
202
203
204
205
206
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import http, { RequestOptions } from "http";
import https from "https";
/**
* Intended to be used in E2E tests so they can assert about requests/responses.
*/
export class CapturingHttpProxy {
private readonly capturedExchanges: CapturedExchange[] = [];
private server?: http.Server;
constructor(private targetUrl: string) {}
get exchanges(): ReadonlyArray<CapturedExchange> {
return this.capturedExchanges;
}
async start(): Promise<string> {
const targetUrlObj = new URL(this.targetUrl);
const isHttps = targetUrlObj.protocol === "https:";
this.server = http.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => {
chunks.push(chunk);
});
req.on("end", () => {
const body = Buffer.concat(chunks).toString("utf8");
const startTime = Date.now();
const capturedRequest: CapturedRequest = {
method: req.method || "GET",
url: req.url || "/",
headers: req.headers,
body,
startTime,
};
const exchange: CapturedExchange = {
request: capturedRequest,
};
this.capturedExchanges.push(exchange);
// Copy headers but update Host to match target
const proxyHeaders = { ...req.headers };
proxyHeaders.host = targetUrlObj.host;
delete proxyHeaders.connection;
let responseStatusCode: number | undefined;
let responseHeaders: http.IncomingHttpHeaders | undefined;
const responseChunks: Buffer[] = [];
this.performRequest({
isHttps,
requestOptions: {
hostname: targetUrlObj.hostname,
port: targetUrlObj.port || (isHttps ? 443 : 80),
path: req.url,
method: req.method,
headers: proxyHeaders,
},
body,
onResponseStart: (statusCode, headers) => {
responseStatusCode = statusCode;
responseHeaders = headers;
res.writeHead(statusCode, responseHeaders);
},
onData: (chunk) => {
responseChunks.push(chunk);
res.write(chunk);
},
onResponseEnd: () => {
const endTime = Date.now();
const responseBody = Buffer.concat(responseChunks).toString("utf8");
exchange.response = {
statusCode: responseStatusCode || 500,
headers: responseHeaders || {},
body: responseBody,
endTime,
};
exchange.durationMs = endTime - startTime;
res.end();
},
onError: (err) => {
console.error("Error in proxying request:", err);
const endTime = Date.now();
const formattedError =
err instanceof Error
? `${err.message}\n${err.stack}`
: String(err);
const errorHeaders = { "x-github-request-id": "proxy-error" };
exchange.response = {
statusCode: 500,
headers: errorHeaders,
body: `Proxy error: ${formattedError}`,
endTime,
};
exchange.durationMs = endTime - startTime;
res.writeHead(exchange.response.statusCode, errorHeaders);
res.end("Proxy error");
},
});
});
});
return new Promise((resolve, reject) => {
this.server!.on("error", (err) => {
reject(err);
});
this.server!.listen(0, "127.0.0.1", () => {
const addr = this.server!.address();
if (addr instanceof Object) {
resolve(`http://${addr.address}:${addr.port}`);
} else {
reject(new Error("Failed to start proxy server"));
}
});
});
}
async stop(): Promise<void> {
if (this.server) {
return new Promise((resolve, reject) => {
this.server!.close((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
}
performRequest(options: PerformRequestOptions): void {
const protocol = options.isHttps ? https : http;
const upstreamRequest = protocol.request(
options.requestOptions,
(upstreamResponse) => {
options.onResponseStart(
upstreamResponse.statusCode || 500,
upstreamResponse.headers,
);
upstreamResponse.on("data", options.onData);
upstreamResponse.on("end", options.onResponseEnd);
},
);
upstreamRequest.on("error", options.onError);
if (options.body) {
upstreamRequest.write(options.body);
}
upstreamRequest.end();
}
protected clearExchanges(): void {
this.capturedExchanges.length = 0;
}
}
export interface PerformRequestOptions {
isHttps: boolean;
requestOptions: RequestOptions;
body: string | undefined;
onResponseStart: (
statusCode: number,
responseHeaders: http.IncomingHttpHeaders,
) => void;
onData: (chunk: Buffer) => void;
onResponseEnd: () => void;
onError: (err: Error | string) => void;
}
export interface CapturedRequest {
readonly method: string;
readonly url: string;
readonly headers: http.IncomingHttpHeaders;
readonly body: string;
readonly startTime: number;
}
export interface CapturedResponse {
readonly statusCode: number;
readonly headers: http.IncomingHttpHeaders;
readonly body: string;
readonly endTime: number;
}
export interface CapturedExchange {
request: CapturedRequest;
response?: CapturedResponse;
durationMs?: number;
}