GeminiBot commited on
Commit ·
4bca23b
1
Parent(s): 7bfd1f6
Port server from Bun to Node.js http module
Browse files123429 unmodified lines3435363637383940414243444546474849505152535455565758596061626364653738394041424344454647484950515253545556575859606162636465666768676869697071727374757677787980818283848586878889909192939495717296979899100101102103104105106107108109110111112113114115116117757677787980818283848586118119120import { createServer, IncomingMessage, ServerResponse } from "node:http";import { OpenAIService } from "./openai-service";
const openAIService = new OpenAIService();29 unmodified lines</html>`;
try { const server = Bun.serve({ port: process.env.PORT || 7860, async fetch(req) { const url = new URL(req.url); // Маскировочный фронтенд if (url.pathname === "/") { return new Response(HTML_FRONTEND, { headers: { "Content-Type": "text/html" } }); }
const authHeader = req.headers.get("Authorization"); const API_KEY = process.env.API_KEY || "MySecretKey_12345"; if (authHeader !== `Bearer ${API_KEY}` && req.method !== "OPTIONS") { return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }); }
const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", };
if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
try { if (url.pathname === "/health") { return new Response(JSON.stringify({ status: "online", model: "distributed-v1" }), { headers: { "Content-Type": "application/json", ...corsHeaders } }); }const API_KEY = process.env.API_KEY || "MySecretKey_12345";const PORT = Number(process.env.PORT) || 7860;
const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { try { const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`); const method = req.method;
// CORS Headers const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", };
// Helper to send JSON response const sendJSON = (statusCode: number, data: any) => { res.writeHead(statusCode, { "Content-Type": "application/json", ...corsHeaders }); res.end(JSON.stringify(data)); };
// Helper to send HTML const sendHTML = (html: string) => { res.writeHead(200, { "Content-Type": "text/html", ...corsHeaders }); res.end(html); };
// Masking Frontend if (url.pathname === "/" && method === "GET") { return sendHTML(HTML_FRONTEND); }
if (url.pathname === "/v1/chat/completions" && req.method === "POST") { const body = await req.json(); const lastMsg = body.messages?.[body.messages.length - 1]?.content || ""; // Handle Preflight if (method === "OPTIONS") { res.writeHead(204, corsHeaders); res.end(); return; }
// Auth Check const authHeader = req.headers["authorization"]; if (url.pathname.startsWith("/v1/") && authHeader !== `Bearer ${API_KEY}`) { return sendJSON(401, { error: "Unauthorized" }); }
// Health Check if (url.pathname === "/health") { return sendJSON(200, { status: "online", model: "distributed-v1" }); }
// Chat Completions if (url.pathname === "/v1/chat/completions" && method === "POST") { let body = ""; req.on("data", (chunk) => { body += chunk; }); req.on("end", async () => { try { const jsonBody = JSON.parse(body); const lastMsg = jsonBody.messages?.[jsonBody.messages.length - 1]?.content || ""; log(`REQ: ${lastMsg.substring(0, 50)}...`); const completion = await openAIService.createChatCompletion(body); return new Response(JSON.stringify(completion), { headers: { "Content-Type": "application/json", ...corsHeaders } }); const completion = await openAIService.createChatCompletion(jsonBody); sendJSON(200, completion); } catch (error: any) { log(`ERR: ${error.message}`); sendJSON(500, { error: error.message }); } }); return; }
// Not Found res.writeHead(404, corsHeaders); res.end();
} catch (error: any) { log(`CRITICAL ERR: ${error.message}`); res.writeHead(500, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Internal Server Error" })); }});
return new Response(null, { status: 404 }); } catch (error) { log(`ERR: ${error.message}`); return new Response(JSON.stringify({ error: error.message }), { status: 500, headers: corsHeaders }); } }, });
log(`API Gateway started on port ${server.port}`);} catch (error) { process.exit(1);}server.listen(PORT, () => { log(`API Gateway started on port ${PORT}`);});src/server.ts+81-47