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

Function createProxyHandlers

scripts/proxy-utils.mjs:318–469  ·  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

316 * Called with each upstream socket of an established WebSocket proxy
317 */
318export function createProxyHandlers({
319 label = "proxy",
320 timeout = DEFAULT_PROXY_TIMEOUT_MS,
321 proxyTimeout = DEFAULT_PROXY_TIMEOUT_MS,
322 xfwd = true,
323 errorBody = textErrorBody,
324 onProxySocket,
325} = {}) {
326 const proxy = createProxyServer({
327 ws: true,
328 changeOrigin: true,
329 xfwd,
330 timeout,
331 proxyTimeout,
332 });
333 if (onProxySocket) proxy.on("proxySocket", onProxySocket);
334 const metrics = {
335 activeHttpRequests: 0,
336 activeWebSockets: 0,
337 totalHttpRequests: 0,
338 totalWebSockets: 0,
339 totalErrors: 0,
340 };
341
342 /** Per-request `onResponse` handlers; see proxyHttp. */
343 const responseHandlers = new WeakMap();
344 proxy.on("proxyRes", (proxyRes, req, res) => {
345 responseHandlers.get(req)?.(proxyRes, req, res);
346 });
347
348 proxy.on("error", (err, _req, resOrSocket, target) => {
349 metrics.totalErrors += 1;
350 const targetText = target ? ` -> ${target}` : "";
351 if (!isBenignSocketError(err)) {
352 console.error(`[${label}] Proxy error${targetText}: ${err.message}`);
353 }
354 if (resOrSocket && typeof resOrSocket.writeHead === "function") {
355 writeProxyError(resOrSocket, err.message, errorBody);
356 } else if (resOrSocket && typeof resOrSocket.destroy === "function") {
357 resOrSocket.destroy();
358 }
359 });
360
361 /**
362 * @param {import("node:http").IncomingMessage} req
363 * @param {import("node:http").ServerResponse} res
364 * @param {string} target
365 * @param {object} [options]
366 * @param {Record<string, string>} [options.headers] Set on the upstream request
367 * @param {(proxyRes: import("node:http").IncomingMessage, req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => void} [options.onResponse]
368 * Writes the response itself instead of it being piped through (e.g.
369 * rewriteJsonResponse).
370 */
371 function proxyHttp(req, res, target, { headers, onResponse } = {}) {
372 if (xfwd) forwardClientOrigin(req);
373 metrics.activeHttpRequests += 1;
374 metrics.totalHttpRequests += 1;
375 const finish = once(() => {

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