|
| 1 | +// Bun-optimized server using Bun.sqlite instead of node-sqlite3 |
| 2 | +const { Database } = require("bun:sqlite"); |
| 3 | +const { v4: uuidv4 } = require('uuid'); |
| 4 | + |
| 5 | +// Use Bun's native SQLite (should be faster) |
| 6 | +const db = new Database(":memory:"); |
| 7 | + |
| 8 | +// Initialize table |
| 9 | +db.exec(`CREATE TABLE IF NOT EXISTS iot_payload ( |
| 10 | + id TEXT PRIMARY KEY, |
| 11 | + content TEXT, |
| 12 | + ts DATETIME DEFAULT CURRENT_TIMESTAMP |
| 13 | +)`); |
| 14 | + |
| 15 | +const insertStmt = db.prepare("INSERT INTO iot_payload (id, content, ts) VALUES (?, ?, datetime('now'))"); |
| 16 | + |
| 17 | +// Simulate async background work |
| 18 | +async function doBackgroundWork(id, payload) { |
| 19 | + return new Promise((resolve) => { |
| 20 | + setTimeout(() => { |
| 21 | + resolve(); |
| 22 | + }, 50); |
| 23 | + }); |
| 24 | +} |
| 25 | + |
| 26 | +// Bun server using native HTTP |
| 27 | +const server = Bun.serve({ |
| 28 | + port: 8080, |
| 29 | + async fetch(request) { |
| 30 | + const url = new URL(request.url); |
| 31 | + |
| 32 | + if (url.pathname === "/health") { |
| 33 | + return new Response(JSON.stringify({ |
| 34 | + status: "ok", |
| 35 | + timestamp: new Date().toISOString() |
| 36 | + }), { |
| 37 | + headers: { "Content-Type": "application/json" } |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + if (url.pathname === "/ingest" && request.method === "POST") { |
| 42 | + const startTime = performance.now(); |
| 43 | + |
| 44 | + try { |
| 45 | + const payload = await request.json(); |
| 46 | + const id = uuidv4(); |
| 47 | + const content = JSON.stringify(payload); |
| 48 | + |
| 49 | + // Use Bun's native SQLite (should be faster) |
| 50 | + insertStmt.run(id, content); |
| 51 | + |
| 52 | + // Start background work |
| 53 | + doBackgroundWork(id, payload).catch(err => { |
| 54 | + console.error('Background work failed:', err); |
| 55 | + }); |
| 56 | + |
| 57 | + const endTime = performance.now(); |
| 58 | + const elapsedMs = endTime - startTime; |
| 59 | + |
| 60 | + return new Response(JSON.stringify({ |
| 61 | + id: id, |
| 62 | + t_ms: Math.round(elapsedMs * 100) / 100 |
| 63 | + }), { |
| 64 | + headers: { "Content-Type": "application/json" } |
| 65 | + }); |
| 66 | + |
| 67 | + } catch (error) { |
| 68 | + console.error('Error processing request:', error); |
| 69 | + return new Response(JSON.stringify({ error: 'Internal server error' }), { |
| 70 | + status: 500, |
| 71 | + headers: { "Content-Type": "application/json" } |
| 72 | + }); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return new Response("Not Found", { status: 404 }); |
| 77 | + }, |
| 78 | +}); |
| 79 | + |
| 80 | +console.log(`Bun Native Server running on port 8080`); |
| 81 | +console.log(`Process ID: ${process.pid}`); |
| 82 | +console.log(`Runtime: Bun ${Bun.version}`); |
| 83 | +console.log('Ready to receive requests...'); |
0 commit comments