uptime-monitor/src/index.ts
2024-03-09 22:28:16 +11:00

45 lines
No EOL
1.6 KiB
TypeScript

import { ping } from "@network-utils/tcp-ping"
import { defaultInterval, config } from "./config"
import { sleep } from "./utils"
import { handleDown, handleUp } from "./handler"
let state = new Map(config.pollEndpoints.map(x => [x.name, {
lastExec: 0,
downStart: 0,
lastDownAlert: 0,
isDown: false
}]))
export type State = typeof state
const executor = async () => {
const curTime = Date.now()
const promises = config.pollEndpoints.map(async endpoint => {
const endpointState = state.get(endpoint.name)
if (endpointState === undefined) console.log(`Could not find endpoint for ${endpoint.name}`)
else if (curTime - endpointState.lastExec > ((endpoint.interval ?? defaultInterval) * 1000)) {
console.log(`Time to poll ${endpoint.name}`)
endpointState.lastExec = curTime
if (endpoint.type === "fetch" ) {
const r = await fetch(endpoint.endpoint, {method: "GET"})
if (r.ok) handleUp(endpointState, curTime, endpoint)
else handleDown(endpointState, curTime, endpoint)
}
else if (endpoint.type === "ping" ) {
const r = await ping({address: endpoint.endpoint})
console.log(r.errors)
if (r.errors.length === 0) handleUp(endpointState, curTime, endpoint)
else handleDown(endpointState, curTime, endpoint)
}
}
})
await Promise.all(promises)
}
const main = async () => {
while (true) {
await sleep(1000)
executor()
}
}
main()