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
|
import type { Service, Heartbeat } from '$lib/types';
export interface EnhancedService extends Service {
heartbeats: Heartbeat[];
}
export interface InitialLogEntry {
kind: 'check' | 'created' | 'deleted' | 'transition';
serviceName: string;
serviceUrl: string;
timestamp: Date;
hb?: Heartbeat;
wasUp?: boolean;
}
export async function load({ fetch }) {
let services: EnhancedService[] = [];
let error = '';
let initialLog: InitialLogEntry[] = [];
try {
const res = await fetch('/api/services');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const list: Service[] = await res.json();
services = await Promise.all(
list.map(async (svc) => {
try {
const hres = await fetch(`/api/services/${svc.id}/history`);
if (!hres.ok) throw new Error(`HTTP ${hres.status}`);
const json = await hres.json();
const heartbeats: Heartbeat[] = Array.isArray(json) ? json : (json.data ?? []);
return { ...svc, heartbeats };
} catch {
return { ...svc, heartbeats: [] };
}
})
);
initialLog = [];
for (const svc of services) {
const hbs = svc.heartbeats;
if (hbs.length === 0) continue;
const last = hbs[hbs.length - 1];
initialLog.push({
kind: 'check',
serviceName: svc.name,
serviceUrl: svc.url,
timestamp: new Date(last.tested_at),
hb: last
});
if (hbs.length >= 2) {
const prev = hbs[hbs.length - 2];
if (prev.is_up !== last.is_up) {
initialLog.push({
kind: 'transition',
serviceName: svc.name,
serviceUrl: svc.url,
timestamp: new Date(last.tested_at),
hb: last,
wasUp: prev.is_up
});
}
}
}
initialLog.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
initialLog = initialLog.slice(0, 50);
} catch (e) {
error = 'Não foi possível conectar ao servidor';
}
return { services, error, initialLog };
}
|