import * as config from './config'; import * as storage from './storage'; import * as http_server from './http'; import * as math from './math'; import * as ser from './serializer'; import * as des from './deserializer'; import * as send from './send'; import * as recv from './recv'; import { MESSAGE, EVENT, SESSION, SNS } from './enums'; import { sessions, desks } from './storage'; export function startup() { Bun.serve({ hostname: config.HOST, port: config.PORT, fetch(req, server) { const url = new URL(req.url); if (url.pathname == '/ws/') { const desk_id = url.searchParams.get('deskId') || '0'; const session_id = url.searchParams.get('sessionId') || '0'; if (!(desk_id in desks)) { const desk = { id: desk_id, sn: 0, events: [], }; storage.create_desk(desk_id); desks[desk_id] = desk; } server.upgrade(req, { data: { desk_id: desk_id, session_id: session_id, } }); return; } return http_server.route(req); }, websocket: { open(ws) { send.send_init(ws); }, async message(ws, u8array) { const dataview = new DataView(u8array.buffer); const d = des.create(dataview); await recv.handle_message(ws, d); }, close(ws, code, message) { if (ws.data.session_id in sessions) { console.log(`session ${ws.data.session_id} closed`); sessions[ws.data.session_id].state = SESSION.CLOSED; sessions[ws.data.session_id].ws = null; } }, error(ws, error) { close(ws, 1000, error); // Treat error as normal close } } }); console.log(`Running on ${config.HOST}:${config.PORT}`) }