MCPcopy Create free account
hub / github.com/OpenHands/OpenHands / createProxyHandlers

Function createProxyHandlers

scripts/proxy-utils.mjs:286–435  ·  view source on GitHub ↗
({
  label = "proxy",
  timeout = DEFAULT_PROXY_TIMEOUT_MS,
  proxyTimeout = DEFAULT_PROXY_TIMEOUT_MS,
  xfwd = true,
  errorBody = textErrorBody,
  onProxySocket,
} = {})

Source from the content-addressed store, hash-verified

284 * Called with each upstream socket of an established WebSocket proxy
285 */
286export function createProxyHandlers({
287 label = "proxy",
288 timeout = DEFAULT_PROXY_TIMEOUT_MS,
289 proxyTimeout = DEFAULT_PROXY_TIMEOUT_MS,
290 xfwd = true,
291 errorBody = textErrorBody,
292 onProxySocket,
293} = {}) {
294 const proxy = createProxyServer({
295 ws: true,
296 changeOrigin: true,
297 xfwd,
298 timeout,
299 proxyTimeout,
300 });
301 if (onProxySocket) proxy.on("proxySocket", onProxySocket);
302 const metrics = {
303 activeHttpRequests: 0,
304 activeWebSockets: 0,
305 totalHttpRequests: 0,
306 totalWebSockets: 0,
307 totalErrors: 0,
308 };
309
310 /** Per-request `onResponse` handlers; see proxyHttp. */
311 const responseHandlers = new WeakMap();
312 proxy.on("proxyRes", (proxyRes, req, res) => {
313 responseHandlers.get(req)?.(proxyRes, req, res);
314 });
315
316 proxy.on("error", (err, _req, resOrSocket, target) => {
317 metrics.totalErrors += 1;
318 const targetText = target ? ` -> ${target}` : "";
319 if (!isBenignSocketError(err)) {
320 console.error(`[${label}] Proxy error${targetText}: ${err.message}`);
321 }
322 if (resOrSocket && typeof resOrSocket.writeHead === "function") {
323 writeProxyError(resOrSocket, err.message, errorBody);
324 } else if (resOrSocket && typeof resOrSocket.destroy === "function") {
325 resOrSocket.destroy();
326 }
327 });
328
329 /**
330 * @param {import("node:http").IncomingMessage} req
331 * @param {import("node:http").ServerResponse} res
332 * @param {string} target
333 * @param {object} [options]
334 * @param {Record<string, string>} [options.headers] Set on the upstream request
335 * @param {(proxyRes: import("node:http").IncomingMessage, req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => void} [options.onResponse]
336 * Writes the response itself instead of it being piped through (e.g.
337 * rewriteJsonResponse).
338 */
339 function proxyHttp(req, res, target, { headers, onResponse } = {}) {
340 metrics.activeHttpRequests += 1;
341 metrics.totalHttpRequests += 1;
342 const finish = once(() => {
343 metrics.activeHttpRequests = Math.max(0, metrics.activeHttpRequests - 1);

Callers 3

startStaticServerFunction · 0.90
createMarsWebBridgeFunction · 0.90
startIngressFunction · 0.90

Calls 3

isBenignSocketErrorFunction · 0.85
writeProxyErrorFunction · 0.85
errorMethod · 0.80

Tested by

no test coverage detected