-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
41 lines (31 loc) · 1.17 KB
/
server.ts
File metadata and controls
41 lines (31 loc) · 1.17 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
import express from "express";
import mongoose from "mongoose";
import { BulkHead } from "./BulkHead";
const app = express();
// A very strict bulkhead for demonstration: 2 concurrent tasks, 5 in queue
const dbBulkhead = new BulkHead(2, 5);
// A simple Schema
const User = mongoose.model('User', new mongoose.Schema({ name: String }));
app.get('/slow-db', async (req, res) => {
try {
const data = await dbBulkhead.run(async () => {
// Simulate a slow DB operation
await new Promise(resolve => setTimeout(resolve, 2000));
return User.find().exec();
});
res.json(data);
} catch (error) {
// If the bulkhead queue is full, this will catch the "Server Busy" error
res.status(503).json({ error: (error as Error).message });
}
})
// THE HEALTHY ROUTE(Should stay responsive)
app.get('/ping', (req, res) => res.send('pong!'));
mongoose.connect('mongodb://localhost:27017/bulkhead').then(() => {
console.log('Connected to MongoDB');
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
}).catch(err => {
console.error('Failed to connect to MongoDB', err);
});