-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
244 lines (219 loc) · 7.29 KB
/
server.js
File metadata and controls
244 lines (219 loc) · 7.29 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
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
const express = require('express');
const path = require('path');
const fs = require('fs');
const Database = require('better-sqlite3');
const CONFIG_PATH = path.join(__dirname, 'config.json');
const DB_PATH = path.join(__dirname, 'data', 'status.db');
const app = express();
const PORT = process.env.PORT || 3110;
// Serve static files
app.use(express.static(path.join(__dirname, 'public'), {
maxAge: '1h',
setHeaders(res, filePath) {
if (filePath.endsWith('.html')) {
res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate');
}
}
}));
// SEO headers
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});
// Dynamic sitemap
app.get('/sitemap.xml', (req, res) => {
const now = new Date().toISOString().split('T')[0];
res.setHeader('Content-Type', 'application/xml');
res.send(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://status.developer.krd/</loc>
<lastmod>${now}</lastmod>
<changefreq>always</changefreq>
<priority>1.0</priority>
</url>
</urlset>`);
});
// API: Get config (public parts only)
app.get('/api/config', (req, res) => {
const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
res.json({
site: config.site,
services: config.services.map((s) => ({
name: s.name,
url: s.url,
description: s.description,
category: s.category,
})),
settings: {
check_interval_minutes: config.settings.check_interval_minutes,
history_days: config.settings.history_days,
timezone: config.settings.timezone,
},
});
});
// API: Current status of all services
app.get('/api/status', (req, res) => {
const db = new Database(DB_PATH, { readonly: true });
try {
const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
const latestChecks = db
.prepare(
`
SELECT c.* FROM checks c
INNER JOIN (
SELECT service_name, MAX(checked_at) as max_date
FROM checks
GROUP BY service_name
) latest ON c.service_name = latest.service_name AND c.checked_at = latest.max_date
ORDER BY c.service_name
`
)
.all();
// Calculate overall status
let overall = 'operational';
if (latestChecks.some((c) => c.status === 'down')) {
overall = latestChecks.every((c) => c.status === 'down') ? 'major_outage' : 'partial_outage';
} else if (latestChecks.some((c) => c.status === 'degraded')) {
overall = 'degraded';
}
// Group by category
const categories = {};
for (const check of latestChecks) {
const svc = config.services.find((s) => s.name === check.service_name);
const cat = svc ? svc.category : 'Other';
if (!categories[cat]) categories[cat] = [];
categories[cat].push({
name: check.service_name,
url: check.service_url,
description: svc ? svc.description : '',
status: check.status,
response_time: check.response_time,
status_code: check.status_code,
checked_at: check.checked_at,
});
}
res.json({
overall,
categories,
last_updated: latestChecks.length > 0 ? latestChecks[0].checked_at : null,
});
} finally {
db.close();
}
});
// API: 90-day history for a specific service or all services
app.get('/api/history/:serviceName?', (req, res) => {
const db = new Database(DB_PATH, { readonly: true });
try {
const days = Math.min(parseInt(req.query.days) || 90, 90);
const serviceName = req.params.serviceName;
let query;
let params;
if (serviceName) {
// Daily aggregated data for a specific service
query = `
SELECT
date(checked_at) as date,
service_name,
COUNT(*) as total_checks,
SUM(CASE WHEN status = 'up' THEN 1 ELSE 0 END) as up_checks,
SUM(CASE WHEN status = 'down' THEN 1 ELSE 0 END) as down_checks,
SUM(CASE WHEN status = 'degraded' THEN 1 ELSE 0 END) as degraded_checks,
ROUND(AVG(response_time)) as avg_response_time,
MIN(response_time) as min_response_time,
MAX(response_time) as max_response_time
FROM checks
WHERE service_name = ? AND checked_at >= datetime('now', ?)
GROUP BY date(checked_at), service_name
ORDER BY date(checked_at) ASC
`;
params = [serviceName, `-${days} days`];
} else {
// Daily aggregated data for all services
query = `
SELECT
date(checked_at) as date,
service_name,
COUNT(*) as total_checks,
SUM(CASE WHEN status = 'up' THEN 1 ELSE 0 END) as up_checks,
SUM(CASE WHEN status = 'down' THEN 1 ELSE 0 END) as down_checks,
SUM(CASE WHEN status = 'degraded' THEN 1 ELSE 0 END) as degraded_checks,
ROUND(AVG(response_time)) as avg_response_time
FROM checks
WHERE checked_at >= datetime('now', ?)
GROUP BY date(checked_at), service_name
ORDER BY service_name, date(checked_at) ASC
`;
params = [`-${days} days`];
}
const rows = db.prepare(query).all(...params);
// Transform into per-service format
const history = {};
for (const row of rows) {
if (!history[row.service_name]) {
history[row.service_name] = [];
}
const uptime = row.total_checks > 0 ? ((row.up_checks / row.total_checks) * 100).toFixed(2) : 0;
let dayStatus = 'up';
if (row.down_checks > 0) dayStatus = 'down';
else if (row.degraded_checks > 0) dayStatus = 'degraded';
history[row.service_name].push({
date: row.date,
status: dayStatus,
uptime: parseFloat(uptime),
total_checks: row.total_checks,
avg_response_time: row.avg_response_time,
min_response_time: row.min_response_time || null,
max_response_time: row.max_response_time || null,
});
}
res.json({ days, history });
} finally {
db.close();
}
});
// API: Uptime summary
app.get('/api/uptime', (req, res) => {
const db = new Database(DB_PATH, { readonly: true });
try {
const periods = [
{ label: '24h', sql: '-1 day' },
{ label: '7d', sql: '-7 days' },
{ label: '30d', sql: '-30 days' },
{ label: '90d', sql: '-90 days' },
];
const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
const uptimes = {};
for (const svc of config.services) {
uptimes[svc.name] = {};
for (const period of periods) {
const row = db
.prepare(
`
SELECT
COUNT(*) as total,
SUM(CASE WHEN status = 'up' THEN 1 ELSE 0 END) as up_count
FROM checks
WHERE service_name = ? AND checked_at >= datetime('now', ?)
`
)
.get(svc.name, period.sql);
uptimes[svc.name][period.label] =
row && row.total > 0 ? parseFloat(((row.up_count / row.total) * 100).toFixed(3)) : null;
}
}
res.json(uptimes);
} finally {
db.close();
}
});
// Fallback to index.html for SPA
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT, () => {
console.log(`Status page running on port ${PORT}`);
});