forked from daytonaio/ai-enablement-stack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
173 lines (147 loc) · 5.04 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
const { promises: fsPromises } = require('fs');
const fs = require('fs');
const path = require('path');
const http = require('http');
const morgan = require('morgan');
const compression = require('compression');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const express = require('express');
const generateHTML = require('./template');
// Load environment variables
const port = process.env.PORT || 4000;
const env = process.env.NODE_ENV || 'development';
// Initialize express app
const app = express();
const server = http.createServer(app);
// Security middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
imgSrc: ["'self'", "data:", "https:"],
},
}
}));
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 1000, // Increased from 100 to 1000 requests per windowMs
message: 'Too many requests, please try again later',
standardHeaders: true,
legacyHeaders: false
});
app.use(limiter);
// Middleware
app.use(compression()); // Compress responses
app.use(express.json());
app.use(express.static('public', {
maxAge: '1d', // Cache static files for 1 day
etag: true
}));
// Logging configuration
if (env === 'production') {
app.use(morgan('combined'));
} else {
app.use(morgan('dev'));
}
// Error handler middleware
const errorHandler = (err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
error: env === 'production' ? 'Internal Server Error' : err.message
});
};
// Async request handler wrapper
const asyncHandler = fn => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
app.get('/', asyncHandler(async (req, res) => {
const data = await fsPromises.readFile('./ai-enablement-stack.json', 'utf8');
const jsonData = JSON.parse(data);
const processedData = {
...jsonData,
layers: jsonData.layers.map(layer => ({
...layer,
sections: layer.sections.map(section => ({
...section,
companies: section.companies.map(company => {
if (typeof company === 'string') {
return { name: company, logo: '' };
}
// Handle different image extensions and paths
let logoPath = '';
if (company.logo) {
const logoName = path.basename(company.logo);
logoPath = `/images/${logoName}`;
// Check if file exists in public/images
const publicPath = path.join(process.cwd(), 'public', 'images', logoName);
if (!fs.existsSync(publicPath)) {
console.warn(`Warning: Image not found: ${logoName} for company ${company.name}`);
}
}
return {
...company,
logo: logoPath
};
})
}))
}))
};
if (processedData.layers) {
processedData.layers = processedData.layers.reverse();
}
const dtnLogoUrl = '/images/daytonaio.png';
const bgImageDataUrl = '/bg.png';
const html = generateHTML(processedData, bgImageDataUrl, dtnLogoUrl); // Pass all three parameters
res.set({
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Cache-Control': 'no-cache'
});
res.type('html').send(html);
}));
// Add a route to check image availability
app.get('/check-images', asyncHandler(async (req, res) => {
const imagesDir = path.join(process.cwd(), 'public', 'images');
const files = await fsPromises.readdir(imagesDir);
res.json({
availableImages: files,
directory: imagesDir
});
}));
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Not Found' });
});
// Error handler
app.use(errorHandler);
// Graceful shutdown
const gracefulShutdown = () => {
console.log('Received shutdown signal. Starting graceful shutdown...');
server.close(() => {
console.log('Server closed. Process exiting...');
process.exit(0);
});
// Force shutdown after 30 seconds
setTimeout(() => {
console.error('Could not close connections in time, forcefully shutting down');
process.exit(1);
}, 30000);
};
// Start server
server.listen(port, () => {
console.log(`Server running in ${env} mode at http://localhost:${port}`);
});
// Handle shutdown signals
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
gracefulShutdown();
});
process.on('unhandledRejection', (err) => {
console.error('Unhandled Rejection:', err);
gracefulShutdown();
});