GeminiBot commited on
Commit ·
4bca23b
1
Parent(s): 7bfd1f6
Port server from Bun to Node.js http module
Browse files12329 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import { 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 } });}if (url.pathname === "/v1/chat/completions" && req.method === "POST") {const body = await req.json();const lastMsg = body.messages?.[body.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 } });}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);}123429 unmodified lines343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import { createServer, IncomingMessage, ServerResponse } from "node:http";import { OpenAIService } from "./openai-service";const openAIService = new OpenAIService();29 unmodified lines</html>`;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 Headersconst corsHeaders = {"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "GET, POST, OPTIONS","Access-Control-Allow-Headers": "Content-Type, Authorization",};// Helper to send JSON responseconst sendJSON = (statusCode: number, data: any) => {res.writeHead(statusCode, { "Content-Type": "application/json", ...corsHeaders });res.end(JSON.stringify(data));};// Helper to send HTMLconst sendHTML = (html: string) => {res.writeHead(200, { "Content-Type": "text/html", ...corsHeaders });res.end(html);};// Masking Frontendif (url.pathname === "/" && method === "GET") {return sendHTML(HTML_FRONTEND);}// Handle Preflightif (method === "OPTIONS") {res.writeHead(204, corsHeaders);res.end();return;}// Auth Checkconst authHeader = req.headers["authorization"];if (url.pathname.startsWith("/v1/") && authHeader !== `Bearer ${API_KEY}`) {return sendJSON(401, { error: "Unauthorized" });}// Health Checkif (url.pathname === "/health") {return sendJSON(200, { status: "online", model: "distributed-v1" });}// Chat Completionsif (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(jsonBody);sendJSON(200, completion);} catch (error: any) {log(`ERR: ${error.message}`);sendJSON(500, { error: error.message });}});return;}// Not Foundres.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" }));}});server.listen(PORT, () => {log(`API Gateway started on port ${PORT}`);});
src/server.ts+81-47