Files
pikasTech-HWLAB/cmd/hwlab-edge-proxy/main.ts
T
2026-05-29 10:44:59 +08:00

94 lines
2.4 KiB
JavaScript

#!/usr/bin/env node
import {
healthPayload,
listen,
proxyHttpRequest,
resolveHostPort,
sendJson
} from "../../internal/dev-entrypoint/http.mjs";
import { createServer } from "node:http";
const serviceId = "hwlab-edge-proxy";
const upstream = process.env.HWLAB_EDGE_UPSTREAM || "http://hwlab-cloud-api.hwlab-dev.svc.cluster.local:6667";
const proxyTimeoutMs = parseTimeout(process.env.HWLAB_EDGE_PROXY_TIMEOUT_MS, 1260000, {
min: 1000,
max: 2400000
});
const { host, port } = resolveHostPort({
listenEnv: "HWLAB_EDGE_LISTEN",
hostEnv: "HWLAB_EDGE_HOST",
portEnv: "HWLAB_EDGE_PORT",
fallbackPort: 6667
});
function proxyDetails() {
return {
upstream,
timeoutMs: proxyTimeoutMs,
mode: "dev-edge-proxy"
};
}
function parseTimeout(value, fallback, { min, max }) {
const parsed = Number.parseInt(value || "", 10);
if (!Number.isInteger(parsed)) return fallback;
return Math.min(Math.max(parsed, min), max);
}
const server = createServer((request, response) => {
const url = new URL(request.url || "/", "http://hwlab-edge-proxy.local");
if (request.method === "GET" && url.pathname === "/health/live") {
proxyHttpRequest({ request, response, upstream, timeoutMs: proxyTimeoutMs });
return;
}
if (request.method === "GET" && (url.pathname === "/health" || url.pathname === "/edge/health")) {
sendJson(response, 200, healthPayload({
serviceId,
role: "public-dev-ingress",
details: proxyDetails()
}));
return;
}
if (request.method === "GET" && (url.pathname === "/status" || url.pathname === "/routes")) {
sendJson(response, 200, {
serviceId,
environment: "dev",
status: "ok",
upstream,
routes: [
{
pathPrefix: "/",
upstream,
mode: "http-proxy"
}
]
});
return;
}
if (request.method === "GET" && url.pathname === "/help") {
sendJson(response, 200, {
serviceId,
commands: ["GET /health", "GET /edge/health", "GET /health/live", "GET /status", "GET /routes"]
});
return;
}
if (url.pathname === "/v1/internal" || url.pathname.startsWith("/v1/internal/")) {
sendJson(response, 404, {
error: {
code: "not_found",
message: "Internal HWLAB routes are not exposed through the public edge proxy."
}
});
return;
}
proxyHttpRequest({ request, response, upstream, timeoutMs: proxyTimeoutMs });
});
listen(server, { serviceId, host, port });