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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
|
// This file is a part of Taskflow.
// Copyright (C) 2025 Robby Zambito
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package api
import (
"encoding/json"
"fmt"
"io"
"math"
"math/rand"
"net"
"net/http"
"regexp"
"strings"
"time"
)
var fs http.Handler
func init() {
fs = http.FileServer(http.Dir("static"))
}
const LogLength = 100
type accessLog struct {
ClientAddr string `json:"clientAddr"`
RequestedPath string `json:"requestedPath"`
RequestTime time.Time `json:"requestTime"`
HttpMethod string `json:"httpMethod"`
}
func CreateFilesHandler(logs *[LogLength]string, n *int, toLogParser chan string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
jsonData, _ := json.Marshal(accessLog{
ClientAddr: redactIP(r.RemoteAddr),
RequestedPath: r.URL.Path,
RequestTime: time.Now().UTC(),
HttpMethod: r.Method,
})
addRotLog(logs, n, toLogParser, string(jsonData))
// Serve the index.html file from the static directory
http.StripPrefix("/", fs).ServeHTTP(w, r)
}
}
func CreateGetLogs(logs *[LogLength]string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
for _, s := range logs {
fmt.Fprintln(w, s)
}
}
}
func CreateLoginHandler(logs *[LogLength]string, n *int, toLogParser chan string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
defer r.Body.Close()
var data map[string]any
if json.Unmarshal(body, &data) != nil {
addRotLog(logs, n, toLogParser, fmt.Sprintf(`{"authRequest": %s}`, string(body)))
http.Error(w, `{"message": "Unauthorized"}`, http.StatusUnauthorized)
return
}
if email, ok := data["email"].(string); ok {
if rememberMe, ok := data["rememberMe"].(bool); ok {
addRotLog(logs, n, toLogParser, fmt.Sprintf(`{"authRequest": {"email": "%s", "password": "XXXXXXXX", "loginTime": "%s", "success": false, "rememberMe": %t}}`, email, time.Now().UTC(), rememberMe))
}
}
http.Error(w, `{"message": "Unauthorized"}`, http.StatusUnauthorized)
}
}
const (
StatusOperational = "operational"
StatusDegraded = "degraded"
StatusDown = "down"
)
const (
IconAPIGateway = "🔗"
IconWeb = "🌐"
IconAuth = "🔐"
IconDB = "🗄️"
IconStorage = "📁"
IconNotifications = "📧"
IconSearch = "🔍"
IconAnalytics = "📊"
)
const (
SeverityMinor = "minor"
SeverityMajor = "major"
)
const (
ServiceAPIGateway = "api"
ServiceWeb = "web"
ServiceAuth = "auth"
ServiceDB = "database"
ServiceStorage = "storage"
ServiceNotifications = "notifications"
ServiceSearch = "search"
ServiceAnalytics = "analytics"
)
type statusData struct {
overallStatus overallStatus
services []service
metrics metrics
incidents []incident
maintenanceEvents []maintenanceEvent
uptimeEvents []uptimeEvent
}
var status statusData
func init() {
// Backfill status
// status.overallStatus = overallStatus{
// Status: StatusDown,
// Description: "Everything is on fire",
// Uptime: 0.0,
// ResponseTime: 0.0,
// ActiveIncidents: 9001,
// ScheduledMaintenance: 0,
// }
status.overallStatus = overallStatus{
Status: StatusDegraded,
Description: "Everything is not great",
Uptime: 50.0,
ResponseTime: 20000,
ActiveIncidents: 9001,
ScheduledMaintenance: 1,
}
status.services = []service{}
status.services = append(status.services, service{
Id: ServiceAPIGateway,
Name: "API Gateway",
Description: "Core API services",
Icon: IconAPIGateway,
Status: StatusOperational,
ResponseTime: 50,
Uptime: 69.420,
})
status.services = append(status.services, service{
Id: "logs",
Name: "Log Warden",
Description: "The master of the Logs",
Icon: "📜",
Status: StatusOperational,
ResponseTime: 69,
Uptime: 99.999,
})
status.metrics = metrics{
Uptime: 90.5,
ResponseTime: 169,
RequestVolume: 5,
ErrorRate: 106.0,
}
status.incidents = []incident{}
status.maintenanceEvents = []maintenanceEvent{}
status.uptimeEvents = []uptimeEvent{}
// For runChance
rand.Seed(time.Now().UnixNano())
incidentId := 42
go func() {
tick20ms := time.NewTicker(20 * time.Millisecond)
tick1s := time.NewTicker(1 * time.Second)
tick10s := time.NewTicker(10 * time.Second)
defer tick20ms.Stop()
defer tick1s.Stop()
defer tick10s.Stop()
for {
select {
case <-tick20ms.C:
// Update response times
for i := range status.services {
runChance(0.08, func() {
status.services[i].ResponseTime = int(math.Max(7.0, float64(status.services[i].ResponseTime+rand.Intn(10)-5)))
})
}
status.overallStatus.ResponseTime = 0
for _, s := range status.services {
status.overallStatus.ResponseTime = int(math.Max(float64(status.overallStatus.ResponseTime), float64(s.ResponseTime)))
}
status.metrics.ResponseTime = status.overallStatus.ResponseTime
case <-tick1s.C:
fmt.Println("1 s tick")
case <-tick10s.C:
runChance(1.0, func() {
severity := SeverityMinor
runChance(0.3, func(){
severity = SeverityMajor
})
i := rand.Intn(int(math.Min(float64(len(allIncidentTitles)), float64(len(allIncidentDescriptions)))))
serviceStatus := StatusDown
runChance(0.5, func(){
serviceStatus = StatusDegraded
})
status.incidents = append(status.incidents, incident{
Id: fmt.Sprintf("%d", incidentId),
Title: allIncidentTitles[i],
Description: allIncidentDescriptions[i],
Status: serviceStatus,
Severity: severity,
StartTime: time.Now().UTC(),
AffectedServices: []string{},
})
incidentId++
})
status.overallStatus.ActiveIncidents = len(status.incidents)
}
}
}()
}
func runChance(likelihood float64, action func()) {
if likelihood <= 0 {
return // never run
}
if likelihood >= 1 {
action()
return
}
if rand.Float64() < likelihood {
action()
}
}
type overallStatus struct {
Status string `json:"status"`
Description string `json:"description"`
Uptime float64 `json:"uptime"`
ResponseTime int `json:"responseTime"`
ActiveIncidents int `json:"activeIncidents"`
ScheduledMaintenance int `json:"scheduledMaintenance"`
}
type service struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Icon string `json:"icon"`
Status string `json:"status"`
ResponseTime int `json:"responseTime"`
Uptime float64 `json:"uptime"`
}
type metrics struct {
Uptime float64 `json:"uptime"`
ResponseTime int `json:"responseTime"`
RequestVolume int `json:"requestVolume"`
ErrorRate float64 `json:"errorRate"`
}
type incident struct {
Id string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Status string `json:"status"`
Severity string `json:"severity"`
StartTime time.Time `json:"startTime"`
AffectedServices []string `json:"affectedServices"`
}
type maintenanceEvent struct {
Id string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
StartTime time.Time `json:"startTime"`
EndTime time.Time `json:"endTime"`
AffectedServices []string `json:"affectedServices"`
}
type uptimeEvent struct {
Date time.Time `json:"date"`
Uptime float64 `json:"uptime"`
}
func StatusHandler(w http.ResponseWriter, r *http.Request) {
jsonData, _ := json.Marshal(status.overallStatus)
fmt.Fprint(w, string(jsonData))
}
func StatusServicesHandler(w http.ResponseWriter, r *http.Request) {
jsonData, _ := json.Marshal(status.services)
fmt.Fprint(w, string(jsonData))
}
func StatusMetricsHandler(w http.ResponseWriter, r *http.Request) {
jsonData, _ := json.Marshal(status.metrics)
fmt.Fprintf(w, string(jsonData))
}
func StatusIncidentsHandler(w http.ResponseWriter, r *http.Request) {
jsonData, _ := json.Marshal(status.incidents)
fmt.Fprintf(w, string(jsonData))
}
func StatusMaintenanceHandler(w http.ResponseWriter, r *http.Request) {
jsonData, _ := json.Marshal(status.maintenanceEvents)
fmt.Fprintf(w, string(jsonData))
}
func StatusUptimeHandler(w http.ResponseWriter, r *http.Request) {
jsonData, _ := json.Marshal(status.uptimeEvents)
fmt.Fprintf(w, string(jsonData))
}
func CreateStatusSubscribeHandler(logs *[LogLength]string, n *int, toLogParser chan string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
defer r.Body.Close()
addRotLog(logs, n, toLogParser, fmt.Sprintf(`{"subscribeEmails": %s}`, string(body)))
fmt.Fprint(w, "{}")
}
}
func CreateContactHandler(logs *[LogLength]string, n *int, toLogParser chan string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
defer r.Body.Close()
addRotLog(logs, n, toLogParser, fmt.Sprintf(`{"contactMessage": %s}`, string(body)))
fmt.Fprint(w, "{}")
}
}
func redactIP(input string) string {
ipRegex := `\b(?:\d{1,3}\.){3}\d{1,3}\b`
re := regexp.MustCompile(ipRegex)
return re.ReplaceAllStringFunc(input, func(match string) string {
if ip := net.ParseIP(match); ip != nil {
parts := strings.Split(match, ".")
if len(parts) == 4 {
parts[3] = "XXX"
return strings.Join(parts, ".")
}
}
return match
})
}
func addRotLog(logs *[LogLength]string, last *int, parser chan string, value string) {
if strings.Contains(value, "\n") {
for _, v := range strings.Split(value, "\n") {
addRotLog(logs, last, parser, v)
}
} else {
if *last == LogLength {
for i := 0; i < LogLength-1; i++ {
logs[i] = logs[i+1]
}
logs[LogLength-1] = value
parser <- value
} else {
logs[*last] = value
*last++
parser <- value
}
}
}
// Not const because can't use runtime append in const definition
var (
normalIncidentTitles = []string{
"Database connection timeout",
"Unexpected 500 Internal Server Error",
"API rate limit exceeded",
"Missing authentication token",
"Service unavailable due to maintenance",
"Invalid request payload",
"Cross‑domain request blocked",
"SSL certificate expired",
"Memory leak detected in worker process",
"Database deadlock detected",
"Failed to serialize response",
"Cache miss leading to latency spike",
"Outdated API endpoint usage",
"Insufficient permissions for resource",
"Concurrent request overload",
"Unexpected null reference",
"Data consistency violation",
"Failed to enqueue background job",
"Rate limiter misconfigured",
"Unexpected null pointer exception",
}
normalIncidentDescriptions = []string{
"The database server failed to establish a connection within the allotted timeout period, causing API requests to hang and eventually fail.",
"The web service returned a generic 500 Internal Server Error due to an unhandled exception in the request handler.",
"Clients exceeded the predefined rate limit, resulting in throttled responses and temporary denial of service.",
"Incoming requests lacked a valid authentication token, leading to unauthorized access attempts.",
"The service was temporarily unavailable because of scheduled maintenance and infrastructure upgrades.",
"The request payload was malformed or missing required fields, causing validation errors.",
"Cross‑origin resource sharing (CORS) policy blocked the request from an unauthorized domain.",
"The SSL/TLS certificate had expired, preventing secure connections from clients.",
"A memory leak in the worker process caused gradual exhaustion of available RAM.",
"A deadlock occurred between database transactions, blocking all pending queries.",
"The response could not be serialized into JSON, leading to malformed output.",
"Cache misses caused a spike in latency as the backend had to recompute data.",
"Clients used deprecated API endpoints that are no longer supported.",
"The user lacked sufficient permissions to access the requested resource.",
"The server was overwhelmed by concurrent requests, exceeding its capacity limits.",
"A null reference exception was thrown during request processing.",
"Data integrity constraints were violated, causing transaction rollbacks.",
"Background job enqueuing failed due to a full queue or missing worker.",
"The rate limiter was misconfigured, allowing too many requests per interval.",
"A null pointer exception caused the service to crash during execution.",
}
mixedIncidentTitels = []string{
"Database connection timeout",
"Unexpected 500 error on /api/v1/users",
"Missing authentication token",
"Rate limit exceeded for client IP 192.168.1.42",
"Service unavailable due to maintenance",
"Malformed JSON payload",
"Cache miss leading to slow response",
"Duplicate request IDs detected",
"Circular dependency in microservices",
"Out-of-memory exception in worker thread",
"DNS resolution failure for external API",
"Malformed URL in webhook callback",
"Cat in the server room",
"Unexpected emoji in user profile",
"Randomly generated error: 42 is the answer",
}
mixedIncidentDescriptions = []string{
"The database server stopped accepting connections, causing a timeout for all client queries.",
"The `/api/v1/users` endpoint returned a 500 Internal Server Error due to an unhandled exception.",
"Requests were rejected because the authentication token was missing or malformed.",
"Requests from the IP `192.168.1.42` exceeded the rate limit, resulting in 429 responses.",
"The service was temporarily unavailable due to scheduled maintenance.",
"The API received malformed JSON, leading to a 400 Bad Request response.",
"The cache layer missed the key, forcing a slow database lookup.",
"Duplicate request IDs were detected, causing duplicate processing.",
"A circular dependency in the microservice architecture caused a deadlock.",
"The worker thread ran out of memory and crashed.",
"DNS resolution failed for an external API, blocking outbound calls.",
"A webhook callback URL contained invalid characters, causing a 400 error.",
"A stray cat wandered into the server room and triggered a physical security alarm.",
"User profiles contained unexpected emoji characters that broke rendering.",
"A random error message appeared: \"42 is the answer\", indicating a placeholder bug.",
}
sillyIncidentTitles = []string{
"The API returned a rainbow instead of JSON",
"All requests were answered with a GIF of a dancing cat",
"The service responded with a random haiku",
"The endpoint started singing opera",
"All data was encrypted with a secret handshake",
"The server replied with a fortune cookie message",
"The service accidentally sent a selfie of the developer",
"All responses were wrapped in a Shakespearean sonnet",
"The API returned a random meme image",
"The service responded with a countdown to the moon landing",
"All requests were answered with a joke about HTTP",
"The server sent back a playlist of elevator music",
"The endpoint replied with a random dad joke",
"All data was sorted alphabetically by the last letter",
"The service responded with a random emoji string",
"The API returned a random recipe",
"All responses were encoded in Morse code",
"The server replied with a random motivational quote",
"The endpoint responded with a random crossword clue",
"All requests were answered with a random song lyric",
"The service returned a random conspiracy theory",
"The API responded with a random horoscope",
"All data was shuffled like a deck of cards",
"The server replied with a random conspiracy theory",
"The endpoint responded with a random tongue twister",
}
sillyIncidentDescriptions = []string{
"The JSON parser returned a holographic rainbow that demanded cookies in exchange for schema validation.",
"Every API response included a looping dancing cat that judged your headers and sashayed through your CORS policy.",
"The server replied only in haiku and refused to switch out of seventeen syllables even when begged with ramen.",
"The endpoint belted operatic arias at 120 dB and required earplugs for POST requests.",
"Payloads were encrypted with a secret handshake, a wink, and a kazoo solo — mobile apps kept failing the kazoo step.",
"Responses arrived as fortune-cookie slips predicting uncanny laptop weather and advising investments in rubber ducks.",
"The API accidentally uploaded the lead dev's selfie wearing a cape and labeled it 'new JSON schema'.",
"Every error was delivered as a Shakespearean sonnet, complete with stage directions and a tragic '404 Romeo'.",
"Endpoints served meme PNGs captioned 'When your query times out but you're still fabulous' instead of data.",
"Responses counted down to the next moon landing in reverse, prompting clients to RSVP and NASA to ask why.",
"Headers contained nothing but increasingly elaborate HTTP puns, causing an epidemic of groans across the office.",
"Requests yielded a 45-minute elevator-music playlist narrated by a bored brass section and an oddly philosophical sheep.",
"Each response began with a groan-inducing dad joke and ended with 'Did you get it? No? Okay.'",
"Data was alphabetized by the last letter of each word, resulting in sentences like 'zoo apes banana' and much confusion.",
"Every field turned into a cryptic emoji cipher that required a three-hour romance with an online emoji oracle to decode.",
"The API returned microwave recipes involving glitter, two bananas, and an optional unicycle for garnish.",
"Responses blinked in Morse via server LEDs; clients had to tap along on toast to translate the payload.",
"The server replied with overenthusiastic motivational quotes, some signed 'Sincerely, Your Router'.",
"Each endpoint answered with a crossword clue so obscure it demanded a PhD in Breakfast Cereals.",
"Responses contained obscure song lyrics that led to several lawsuits from very offended shower singers.",
"The service offered a handcrafted conspiracy about pigeons, quantum routers, and a secret society of baristas.",
"Users received horoscopes telling their IPs to avoid Tuesdays and to invest heavily in chamomile tea.",
"Records were shuffled like a magician's deck, with the ace of spades mysteriously serving as the primary key.",
"The server spun a conspiracy about sentient staplers plotting to replace USB‑C with fashionable shoelaces.",
"Replies were impossible tongue twisters typed by the server while giggling, causing voice assistants to short out.",
}
allIncidentTitles = append(append(append([]string{}, normalIncidentTitles...), mixedIncidentTitels...), sillyIncidentTitles...)
allIncidentDescriptions = append(append(append([]string{}, normalIncidentDescriptions...), mixedIncidentTitels...), sillyIncidentDescriptions...)
)
|