forked from statsig-io/statsigstatus
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
389 lines (340 loc) · 11.9 KB
/
index.js
File metadata and controls
389 lines (340 loc) · 11.9 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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
const slotHours = 8;
const maxDays = 30;
const maxSlots = maxDays * (24 / slotHours); // 90 slots
async function genReportLog(container, key, url) {
const response = await fetch("logs/" + key + "_report.log");
let statusLines = "";
if (response.ok) {
statusLines = await response.text();
}
const normalized = normalizeData(statusLines);
const statusStream = constructStatusStream(key, url, normalized);
container.appendChild(statusStream);
}
function constructStatusStream(key, url, uptimeData) {
let streamContainer = templatize("statusStreamContainerTemplate");
for (var ii = maxSlots - 1; ii >= 0; ii--) {
let line = constructStatusLine(key, ii, uptimeData[ii]);
streamContainer.appendChild(line);
}
const lastSet = uptimeData[0];
const color = getColor(lastSet);
const colorClasses = getColorClasses(color);
const title = key.replaceAll("_", " ").toUpperCase();
const container = templatize("statusContainerTemplate", {
title,
url: url,
"color-badge": colorClasses.badge,
"color-dot": colorClasses.dot,
status: getStatusText(color),
upTime: uptimeData.upTime,
});
container.appendChild(streamContainer);
return container;
}
function constructStatusLine(key, relSlot, upTimeArray) {
const now = new Date();
// Calculate the start of the current slot
const currentSlotStart = new Date(now);
currentSlotStart.setMinutes(0, 0, 0);
const currentHour = currentSlotStart.getHours();
currentSlotStart.setHours(currentHour - (currentHour % slotHours));
// Go back relSlot slots
const slotStart = new Date(currentSlotStart.getTime() - relSlot * slotHours * 3600 * 1000);
const slotEnd = new Date(slotStart.getTime() + slotHours * 3600 * 1000);
return constructStatusSquare(key, slotStart, slotEnd, upTimeArray);
}
function getColor(uptimeVal) {
return uptimeVal == null
? "nodata"
: uptimeVal == 1
? "success"
: uptimeVal < 0.3
? "failure"
: "partial";
}
function getColorClasses(color) {
const colorMap = {
success: {
badge: "bg-green-100 text-green-800",
dot: "bg-green-500",
square: "bg-green-500"
},
failure: {
badge: "bg-red-100 text-red-800",
dot: "bg-red-500",
square: "bg-red-500"
},
partial: {
badge: "bg-orange-100 text-orange-800",
dot: "bg-orange-500",
square: "bg-orange-500"
},
nodata: {
badge: "bg-gray-100 text-gray-600",
dot: "bg-gray-400",
square: "bg-gray-300"
}
};
return colorMap[color] || colorMap.nodata;
}
function constructStatusSquare(key, slotStart, slotEnd, uptimeVal) {
const color = getColor(uptimeVal);
const colorClasses = getColorClasses(color);
let square = templatize("statusSquareTemplate");
// Add the background color class
square.classList.add(colorClasses.square);
square.setAttribute("data-status", color);
const show = () => {
showTooltip(square, key, slotStart, slotEnd, color);
};
square.addEventListener("mouseover", show);
square.addEventListener("mousedown", show);
square.addEventListener("mouseout", hideTooltip);
return square;
}
let cloneId = 0;
function templatize(templateId, parameters) {
let clone = document.getElementById(templateId).cloneNode(true);
clone.id = "template_clone_" + cloneId++;
if (!parameters) {
return clone;
}
applyTemplateSubstitutions(clone, parameters);
return clone;
}
function applyTemplateSubstitutions(node, parameters) {
const attributes = node.getAttributeNames();
for (var ii = 0; ii < attributes.length; ii++) {
const attr = attributes[ii];
const attrVal = node.getAttribute(attr);
node.setAttribute(attr, templatizeString(attrVal, parameters));
}
// Process all child nodes, including text nodes
const childNodes = Array.from(node.childNodes);
childNodes.forEach((childNode) => {
if (childNode.nodeType === Node.TEXT_NODE) {
// Handle text nodes
childNode.textContent = templatizeString(childNode.textContent, parameters);
} else if (childNode.nodeType === Node.ELEMENT_NODE) {
// Recursively handle element nodes
applyTemplateSubstitutions(childNode, parameters);
}
});
}
function templatizeString(text, parameters) {
if (parameters) {
for (const [key, val] of Object.entries(parameters)) {
text = text.replaceAll("$" + key, val);
}
}
return text;
}
function getStatusText(color) {
return color == "nodata"
? "Offline"
: color == "success"
? "Online"
: color == "failure"
? "Offline"
: color == "partial"
? "Offline"
: "Offline";
}
function getStatusDescriptiveText(color) {
return color == "nodata"
? "No Data Available: Health check was not performed."
: color == "success"
? "No downtime recorded in this period."
: color == "failure"
? "Major outages recorded in this period."
: color == "partial"
? "Partial outages recorded in this period."
: "Unknown";
}
function formatSlotTime(date) {
const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const h = date.getHours().toString().padStart(2, "0") + ":00";
return `${months[date.getMonth()]} ${date.getDate()}, ${h}`;
}
function create(tag, className) {
let element = document.createElement(tag);
element.className = className;
return element;
}
function normalizeData(statusLines) {
const rows = statusLines.split("\n");
const slotData = splitRowsBySlot(rows);
let relativeSlotMap = {};
const now = Date.now();
for (const [key, val] of Object.entries(slotData)) {
if (key == "upTime") {
continue;
}
const relSlot = getRelativeSlot(now, Number(key));
if (relSlot < maxSlots) {
relativeSlotMap[relSlot] = getSlotAverage(val);
}
}
relativeSlotMap.upTime = slotData.upTime;
return relativeSlotMap;
}
function getSlotAverage(val) {
if (!val || val.length == 0) {
return null;
} else {
return val.reduce((a, v) => a + v) / val.length;
}
}
function getRelativeSlot(now, slotTimestamp) {
return Math.floor((now - slotTimestamp) / (slotHours * 3600 * 1000));
}
function getSlotKey(dateTime) {
// Returns the timestamp of the start of the 8h slot this dateTime falls into
const d = new Date(dateTime);
d.setMinutes(0, 0, 0);
const hour = d.getHours();
d.setHours(hour - (hour % slotHours));
return d.getTime();
}
function splitRowsBySlot(rows) {
let slotValues = {};
let sum = 0,
count = 0;
for (var ii = 0; ii < rows.length; ii++) {
const row = rows[ii];
if (!row) {
continue;
}
const [dateTimeStr, resultStr] = row.split(",", 2);
// Replace '-' with '/' because Safari
const dateTime = new Date(
Date.parse(dateTimeStr.replaceAll("-", "/") + " GMT")
);
const slotKey = getSlotKey(dateTime);
let resultArray = slotValues[slotKey];
if (!resultArray) {
resultArray = [];
slotValues[slotKey] = resultArray;
}
let result = 0;
if (resultStr.trim() == "success") {
result = 1;
}
sum += result;
count++;
resultArray.push(result);
}
const upTime = count ? ((sum / count) * 100).toFixed(2) + "%" : "--%";
slotValues.upTime = upTime;
return slotValues;
}
let tooltipTimeout = null;
function showTooltip(element, key, slotStart, slotEnd, color) {
clearTimeout(tooltipTimeout);
const toolTipDiv = document.getElementById("tooltip");
const colorClasses = getColorClasses(color);
document.getElementById("tooltipDateTime").innerText =
formatSlotTime(slotStart) + " – " + formatSlotTime(slotEnd);
document.getElementById("tooltipDescription").innerText =
getStatusDescriptiveText(color);
const statusDiv = document.getElementById("tooltipStatus");
statusDiv.innerText = getStatusText(color);
statusDiv.className = `inline-flex items-center px-2 py-1 rounded-full text-xs font-medium mb-2 ${colorClasses.badge}`;
// Position tooltip
const rect = element.getBoundingClientRect();
const tooltipRect = toolTipDiv.getBoundingClientRect();
toolTipDiv.style.top = rect.bottom + 10 + "px";
toolTipDiv.style.left = Math.max(10, rect.left + rect.width / 2 - tooltipRect.width / 2) + "px";
toolTipDiv.classList.remove("opacity-0");
toolTipDiv.classList.add("opacity-100");
}
function hideTooltip() {
tooltipTimeout = setTimeout(() => {
const toolTipDiv = document.getElementById("tooltip");
toolTipDiv.classList.add("opacity-0");
toolTipDiv.classList.remove("opacity-100");
}, 1000);
}
function updateOverallStatus() {
// Get all service containers
const serviceContainers = document.querySelectorAll('#reports > div');
let hasFailure = false;
let hasPartial = false;
let hasNoData = false;
let hasSuccess = false;
serviceContainers.forEach(container => {
// Get the status stream container for this service
const statusStream = container.querySelector('[id^="template_clone_"]');
if (statusStream) {
// Get all status squares and take the last one (most recent day)
const statusSquares = statusStream.querySelectorAll('[data-status]');
if (statusSquares.length > 0) {
const mostRecentSquare = statusSquares[statusSquares.length - 1];
const status = mostRecentSquare.getAttribute('data-status');
if (status === 'failure') hasFailure = true;
else if (status === 'partial') hasPartial = true;
else if (status === 'nodata') hasNoData = true;
else if (status === 'success') hasSuccess = true;
}
}
});
const overallStatusEl = document.getElementById('overall-status');
// Clear and rebuild the content based on priority: failure > partial > nodata > success
if (hasFailure) {
overallStatusEl.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800';
overallStatusEl.innerHTML = '<div class="w-2 h-2 bg-red-500 rounded-full mr-2"></div>Major System Outage';
} else if (hasPartial) {
overallStatusEl.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-orange-100 text-orange-800';
overallStatusEl.innerHTML = '<div class="w-2 h-2 bg-orange-500 rounded-full mr-2"></div>Partial System Outage';
} else if (hasNoData) {
overallStatusEl.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-600';
overallStatusEl.innerHTML = '<div class="w-2 h-2 bg-gray-400 rounded-full mr-2"></div>System Status Unknown';
} else if (hasSuccess) {
overallStatusEl.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800';
overallStatusEl.innerHTML = '<div class="w-2 h-2 bg-green-500 rounded-full mr-2"></div>All Systems Operational';
} else {
// Fallback case if no services are found
overallStatusEl.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-600';
overallStatusEl.innerHTML = '<div class="w-2 h-2 bg-gray-400 rounded-full mr-2"></div>Loading...';
}
}
async function genAllReports() {
const response = await fetch("urls.cfg");
const configText = await response.text();
const configLines = configText.split("\n");
for (let ii = 0; ii < configLines.length; ii++) {
const configLine = configLines[ii];
const [key, url] = configLine.split("=");
if (!key || !url) {
continue;
}
const [cleanUrl] = url.split(" ");
if (!cleanUrl) {
continue;
}
await genReportLog(
document.getElementById("reports"),
key,
cleanUrl.replaceAll('"', "")
);
}
// Update overall status after all reports are loaded
setTimeout(updateOverallStatus, 1000);
}
async function genIncidentReport() {
const response = await fetch(
"incident_report.md"
);
if (response.ok) {
const res = await response.text();
try {
const activeDom = DOMPurify.sanitize(
marked.parse(res ? res : "No active incidents")
);
document.getElementById("newsUpdates").innerHTML = activeDom;
} catch (e) {
console.log(e.message);
}
}
}