| 112 | } |
| 113 | |
| 114 | function forwardToCapiProxy( |
| 115 | clientReq: http.IncomingMessage, |
| 116 | clientRes: http.ServerResponse, |
| 117 | capiProxyUrl: string, |
| 118 | ): Promise<boolean> { |
| 119 | return new Promise((resolve) => { |
| 120 | const target = new URL(capiProxyUrl); |
| 121 | const chunks: Buffer[] = []; |
| 122 | clientReq.on("data", (chunk: Buffer) => chunks.push(chunk)); |
| 123 | clientReq.on("error", (err) => { |
| 124 | if (!clientRes.headersSent) { |
| 125 | clientRes.writeHead(502, { "content-type": "text/plain" }); |
| 126 | clientRes.end(`E2E proxy: client request error: ${err.message}`); |
| 127 | } else { |
| 128 | clientRes.destroy(err); |
| 129 | } |
| 130 | resolve(true); |
| 131 | }); |
| 132 | clientReq.on("end", () => { |
| 133 | const proxyReq = http.request( |
| 134 | { |
| 135 | hostname: target.hostname, |
| 136 | port: target.port, |
| 137 | path: clientReq.url, |
| 138 | method: clientReq.method, |
| 139 | headers: { |
| 140 | ...clientReq.headers, |
| 141 | host: target.host, |
| 142 | }, |
| 143 | }, |
| 144 | (proxyRes) => { |
| 145 | clientRes.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers); |
| 146 | proxyRes.pipe(clientRes); |
| 147 | proxyRes.on("end", () => resolve(true)); |
| 148 | proxyRes.on("error", (err) => { |
| 149 | clientRes.destroy(err); |
| 150 | resolve(true); |
| 151 | }); |
| 152 | }, |
| 153 | ); |
| 154 | proxyReq.on("error", (err) => { |
| 155 | if (!clientRes.headersSent) { |
| 156 | clientRes.writeHead(502, { |
| 157 | "content-type": "application/json", |
| 158 | "x-github-request-id": "e2e-proxy-error", |
| 159 | }); |
| 160 | clientRes.end( |
| 161 | JSON.stringify({ |
| 162 | error: `E2E proxy: CAPI forward error: ${err.message}`, |
| 163 | }), |
| 164 | ); |
| 165 | } |
| 166 | resolve(true); |
| 167 | }); |
| 168 | if (chunks.length > 0) { |
| 169 | proxyReq.write(Buffer.concat(chunks)); |
| 170 | } |
| 171 | proxyReq.end(); |