-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
341 lines (307 loc) · 10.5 KB
/
server.js
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
const express = require("express");
const path = require("path");
const { MongoClient } = require("mongodb");
const { Client } = require("pg");
const { createClient } = require("redis");
const amqp = require("amqplib/callback_api");
const { Kafka } = require("kafkajs");
const {produceMessages} = require("./producer");
const app = express();
const PORT = 3000;
const mongo_uri = "mongodb://localhost:27017";
const postgres_uri = "postgresql://postgres:password@localhost:5432/performanceTest";
const redis_uri = "redis://localhost:6379";
const dbName = "performanceTest";
const collectionName = "entries";
let db;
let channel;
// Middleware to parse JSON requests
app.use(express.json({ limit: "100mb" }));
// Connect to MongoDB
MongoClient.connect(mongo_uri)
.then((client) => {
db = client.db(dbName);
console.log(`Connected to MongoDB: ${mongo_uri}`);
})
.catch((err) => console.error(err));
// Connect to Redis
const redisClient = createClient({
url: redis_uri, // Use the container name as the host
});
redisClient.on("connect", () => {
console.log(`Connected to Redis: ${redis_uri}`);
});
redisClient.on("error", (err) => {
console.error("Redis connection error:", err);
});
// Kafka Admin Client to ensure topic partitions
const kafka = new Kafka({
clientId: "test-performance-app",
brokers: ["localhost:9092"],
});
const admin = kafka.admin();
async function ensureTopicPartitions() {
await admin.connect();
const topics = await admin.listTopics();
if (!topics.includes("test-performance")) {
await admin.createTopics({
topics: [
{
topic: "test-performance",
numPartitions: 4,
replicationFactor: 1,
},
],
});
console.log("Created topic 'test-performance' with 4 partitions");
} else {
const topicMetadata = await admin.fetchTopicMetadata({ topics: ["test-performance"] });
const partitions = topicMetadata.topics[0].partitions.length;
if (partitions < 4) {
await admin.createPartitions({
topicPartitions: [
{
topic: "test-performance",
count: 4,
},
],
});
console.log("Updated topic 'test-performance' to 4 partitions");
}
}
await admin.disconnect();
}
(async () => {
try {
// Connect to Redis
await redisClient.connect();
// Connect to RabbitMQ
amqp.connect("amqp://localhost", (err, connection) => {
if (err) throw err;
connection.createChannel((err, ch) => {
if (err) throw err;
channel = ch;
channel.assertQueue("request_queue", { durable: true });
console.log("Connected to RabbitMQ and channel created");
});
});
// Connect to Kafka Admin
await ensureTopicPartitions();
console.log(
"Kafka topic 'test-performance' is ensured to have 4 partitions"
);
// Serve the index.html file
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
app.listen(PORT, () => {
console.log(`Server is running on port http://localhost:${PORT}`);
});
// API to test the server on many requests
app.get("/api/test", (req, res) => {
res.json({ message: "Hello, World!" });
});
// API to insert entries into mongoDB
app.post("/api/populate", async (req, res) => {
try {
const { entryCount } = req.body;
if (!entryCount || entryCount <= 0) {
return res.status(400).json({ message: "Invalid entry count" });
}
const entries = Array.from({ length: entryCount }, (_, i) => ({
value: `${i + 1}`,
createdAt: new Date(),
}));
const start = performance.now(); // Start timing the operation
// Insert 100 entries into the collection
await db.collection(collectionName).insertMany(entries);
const end = performance.now(); // End timing the operation
if (end - start > 1000) {
res.json({
message: `Inserted ${entryCount} entries successfully in ${(
(end - start) /
1000
).toFixed(2)} s`,
});
} else {
res.json({
message: `Inserted ${entryCount} entries successfully in ${(
end - start
).toFixed(2)} ms`,
});
}
} catch (error) {
console.error("Error inserting entries:", error);
res.status(500).json({ message: "Failed to insert entries" });
}
});
// API to retrieve a specific entry by value from mongoDB
app.get("/api/retrieve/:entryValue", async (req, res) => {
const entryValue = req.params.entryValue;
const collection = db.collection(collectionName);
const entry = await collection.findOne({ value: entryValue });
if (entry) {
res.json({ message: `Found: ${entry.value}`, entry });
} else {
res.json({ message: "Entry not found" });
}
});
// API to clear the database
app.delete("/api/clear", async (req, res) => {
try {
const result = await db.collection(collectionName).deleteMany({});
res.json({
message: `Cleared ${result.deletedCount} entries from the database`,
});
} catch (error) {
console.error("Error clearing the database:", error);
res.status(500).json({ message: "Failed to clear the database" });
}
});
// API to insert entries into PostgreSQL
app.post("/api/populate-postgres", async (req, res) => {
try {
const { entryCount } = req.body;
if (!entryCount || entryCount <= 0) {
return res.status(400).json({ message: "Invalid entry count" });
}
const startTime = Date.now();
for (let i = 0; i < entryCount; i++) {
await client.query(`INSERT INTO entries (value) VALUES ($1)`, [i]);
}
const endTime = Date.now();
const duration = endTime - startTime;
if (duration > 1000) {
res.json({
message: `${entryCount} entries inserted into PostgreSQL in ${
duration / 1000
} s`,
});
} else {
res.json({
message: `${entryCount} entries inserted into PostgreSQL in ${duration} ms`,
});
}
} catch (err) {
console.error("Error populating PostgreSQL:", err);
res.status(500).json({ message: "Error populating PostgreSQL" });
}
});
// API to retrieve a specific entry by value from PostgreSQL
app.get("/api/retrieve-postgres/:key", async (req, res) => {
try {
const key = req.params.key;
const result = await client.query(`SELECT * FROM entries WHERE value = $1`, [key]);
if (result.rows.length) {
res.json({ message: `Found: ${result.rows[0].value}` });
} else {
res.json({ message: "Entry not found" });
}
} catch (err) {
console.error("Error retrieving from PostgreSQL:", err);
res.status(500).json({ message: "Error retrieving from PostgreSQL" });
}
});
// API to clear the PostgreSQL
app.delete("/api/clear-postgres", async (req, res) => {
try {
const result = await client.query(`DELETE FROM entries`);
res.json({
message: `Cleared ${result.rowCount} entries from PostgreSQL`,
});
} catch (err) {
console.error("Error clearing PostgreSQL:", err);
res.status(500).json({ message: "Error clearing PostgreSQL" });
}
});
// API to insert entries into redis
app.post("/api/populate-redis", async (req, res) => {
try {
const { entryCount } = req.body;
if (!entryCount || entryCount <= 0) {
return res.status(400).json({ message: "Invalid entry count" });
}
const startTime = Date.now();
for (let i = 0; i < entryCount; i++) {
await redisClient.set(`${i}`, `${i}`);
}
const endTime = Date.now();
const duration = endTime - startTime;
await redisClient.set("latestPopulateTime", duration.toString());
if (duration > 1000) {
res.json({
message: `${entryCount} entries inserted into Redis in ${
duration / 1000
} s`,
});
} else {
res.json({
message: `${entryCount} entries inserted into Redis in ${duration} ms`,
});
}
} catch (err) {
console.error("Error populating Redis:", err);
res.status(500).json({ message: "Error populating Redis" });
}
});
// API to retrieve a specific entry by value from Redis
app.get("/api/retrieve-redis/:key", async (req, res) => {
try {
const key = req.params.key;
const value = await redisClient.get(key);
if (value) {
res.json({ message: `Found: ${value}` });
} else {
res.json({ message: "Entry not found" });
}
} catch (err) {
console.error("Error retrieving from Redis:", err);
res.status(500).json({ message: "Error retrieving from Redis" });
}
});
// API to clear the redis
app.delete("/api/clear-redis", async (req, res) => {
try {
const result = await db.collection(collectionName).deleteMany({});
console.log(result);
await redisClient.flushAll();
res.json({
message: `Cleared ${result.deletedCount} entries from Redis`,
});
} catch (err) {
console.error("Error clearing Redis:", err);
res.status(500).json({ message: "Error clearing Redis" });
}
});
// API Route to send message to the queue
app.get("/api/test-mq", (req, res) => {
const index = req.query.index;
if (channel) {
channel.sendToQueue(
"request_queue",
Buffer.from(JSON.stringify(index)),
{
persistent: true,
}
);
res.status(200).json({ message: "Request queued" });
} else {
res.status(500).json({ message: "Channel not available" });
}
});
app.post("/api/test-kafka", async (req, res) => {
const reqCount = req.body.reqCount;
const startBulk = performance.now();
await produceMessages(reqCount);
const endBulk = performance.now();
const bulkDuration = endBulk - startBulk;
res.json({
message: `${reqCount} requests sent to Kafka took ${(
bulkDuration / 1000
).toFixed(2)} seconds.`,
});
});
} catch (error) {
console.error("Failed to connect to Redis:", error);
}
})();