-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastify-bun-optimized.js
More file actions
120 lines (103 loc) · 3.41 KB
/
fastify-bun-optimized.js
File metadata and controls
120 lines (103 loc) · 3.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const fastify = require('fastify')({
logger: false,
bodyLimit: 10 * 1024 * 1024
});
const { v4: uuidv4 } = require('uuid');
const port = 8080;
// Use Bun's native SQLite if available
let db, insertStmt, isBun = false;
if (typeof Bun !== 'undefined') {
isBun = true;
const { Database } = require('bun:sqlite');
db = new Database(':memory:');
console.log('Using Bun native SQLite');
// Initialize table
db.exec(`CREATE TABLE IF NOT EXISTS iot_payload (
id TEXT PRIMARY KEY,
content TEXT,
ts DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
// Pre-prepare statement
insertStmt = db.prepare('INSERT INTO iot_payload (id, content, ts) VALUES (?, ?, datetime("now"))');
} else {
const sqlite3 = require('sqlite3').verbose();
db = new sqlite3.Database(':memory:');
console.log('Using Node.js SQLite3');
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS iot_payload (
id TEXT PRIMARY KEY,
content TEXT,
ts DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
});
}
// Simulate async background work
async function doBackgroundWork(id, payload) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 50);
});
}
// Ingest endpoint
fastify.post('/ingest', async (request, reply) => {
const startTime = process.hrtime.bigint();
try {
const id = uuidv4();
const payload = request.body;
const content = JSON.stringify(payload);
// Insert into database
if (isBun) {
// Bun native - use pre-prepared statement
insertStmt.run(id, content);
} else {
// Node.js - async
await new Promise((resolve, reject) => {
db.run(
'INSERT INTO iot_payload (id, content, ts) VALUES (?, ?, datetime("now"))',
[id, content],
function(err) {
if (err) reject(err);
else resolve();
}
);
});
}
// Start background work (fire and forget)
doBackgroundWork(id, payload).catch(err => {
console.error('Background work failed:', err);
});
const endTime = process.hrtime.bigint();
const elapsedMs = Number(endTime - startTime) / 1000000;
return {
id: id,
t_ms: Math.round(elapsedMs * 100) / 100
};
} catch (error) {
console.error('Error processing request:', error);
reply.code(500);
return { error: 'Internal server error' };
}
});
// Health check endpoint
fastify.get('/health', async (request, reply) => {
return {
status: 'ok',
timestamp: new Date().toISOString(),
runtime: typeof Bun !== 'undefined' ? `Bun ${Bun.version}` : `Node.js ${process.version}`
};
});
// Start server
const start = async () => {
try {
await fastify.listen({ port: port, host: '0.0.0.0' });
console.log(`Fastify + Bun Optimized Server running on port ${port}`);
console.log(`Process ID: ${process.pid}`);
console.log(`Runtime: ${process.version || 'Bun'}`);
console.log('Ready to receive requests...');
} catch (err) {
console.error('Error starting server:', err);
process.exit(1);
}
};
start();