-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrealistic-server.js
More file actions
212 lines (178 loc) · 6.46 KB
/
realistic-server.js
File metadata and controls
212 lines (178 loc) · 6.46 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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, otherwise node-sqlite3
let db, insertStmt, isBun = false;
if (typeof Bun !== 'undefined') {
isBun = true;
const { Database } = require('bun:sqlite');
db = new Database(':memory:');
// 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"))');
console.log('Using Bun native SQLite');
} else {
const sqlite3 = require('sqlite3').verbose();
db = new sqlite3.Database(':memory:');
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS iot_payload (
id TEXT PRIMARY KEY,
content TEXT,
ts DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
});
console.log('Using Node.js SQLite3');
}
// Realistic IoT processing functions (no artificial sleep!)
function validateAndEnrichPayload(payload) {
// 1. Data validation and enrichment (like Java version)
for (const [key, value] of Object.entries(payload)) {
// Data type validation
if (typeof value === 'string' && value.length > 100) {
throw new Error(`Field ${key} too long`);
}
}
// Add enrichment fields
payload.processed_at = Date.now();
payload.processor_id = process.pid;
return payload;
}
function calculateDeviceMetrics(payload) {
// 2. Simulate realistic metric calculations
let sum = 0;
let count = 0;
for (const value of Object.values(payload)) {
if (typeof value === 'string') {
// Simple hash calculation
let hash = 0;
for (let i = 0; i < value.length; i++) {
const char = value.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
sum += hash;
count++;
}
}
if (count > 0) {
payload.avg_hash = sum / count;
payload.field_count = count;
}
return payload;
}
function calculateRiskScore(payload) {
// 3. Monte Carlo style risk calculation (CPU intensive like your benchmark)
let risk = 0.0;
const iterations = 1000; // Realistic computation load
for (let i = 0; i < iterations; i++) {
const x = Math.random();
const y = Math.random();
// Environmental stress calculation
const temp = 20 + (x * 40); // 20-60°C range
const humidity = y * 100; // 0-100% range
// Risk formula (similar to your benchmark)
const stress = Math.sin(temp * Math.PI / 180) * Math.cos(humidity * Math.PI / 180);
risk += Math.exp(-stress * stress);
}
return risk / iterations;
}
function logProcessingResult(id, riskScore) {
// 4. Simulate realistic logging (minimal I/O)
if (riskScore > 0.5) {
console.log(`HIGH RISK detected for device ${id}: ${riskScore}`);
}
}
// Realistic background work (CPU intensive, no sleep!)
async function doRealisticBackgroundWork(id, payload) {
// Process in next tick to not block the main request
return new Promise((resolve) => {
setImmediate(() => {
try {
// 1. Data validation and enrichment
validateAndEnrichPayload(payload);
// 2. Calculate device metrics
calculateDeviceMetrics(payload);
// 3. Risk assessment computation
const riskScore = calculateRiskScore(payload);
// 4. Log processing result
logProcessingResult(id, riskScore);
resolve();
} catch (error) {
console.error('Error processing payload', id, ':', error.message);
resolve(); // Don't fail the request
}
});
});
}
// Ingest endpoint - realistic IoT processing
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 (fast operation)
if (isBun) {
// Bun native - 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 realistic background work (fire and forget)
doRealisticBackgroundWork(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}`,
totalProcessed: totalProcessed
};
});
// Start server
const start = async () => {
try {
await fastify.listen({ port: port, host: '0.0.0.0' });
console.log(`Realistic IoT Server running on port ${port}`);
console.log(`Process ID: ${process.pid}`);
console.log(`Runtime: ${typeof Bun !== 'undefined' ? `Bun ${Bun.version}` : process.version}`);
console.log('Ready to receive requests...');
} catch (err) {
console.error('Error starting server:', err);
process.exit(1);
}
};
let totalProcessed = 0;
start();