uptime-monitor/src/index.ts

54 lines
No EOL
1.7 KiB
TypeScript

import { ping } from "@network-utils/tcp-ping"
import { defaultInterval, config } from "./config"
import { sleep } from "./utils"
import { handleDown, handleUp } from "./handler"
import { Config } from "./config"
import { promise as pingPromise } from "ping"
let state = new Map(config.pollEndpoints.map(x => [x.name, {
lastExec: 0,
downStart: 0,
lastDownAlert: 0,
attemptsFailed: 0,
isDown: false
}]))
export type State = typeof state
const isEndpointUp = async (endpoint: Config["pollEndpoints"][number]) => {
if (endpoint.type === "fetch" ) {
const r = await fetch(endpoint.url, {method: "GET"}).catch(e => ({ok: false}))
return r.ok
}
else if (endpoint.type === "tcp-ping" ) {
const r = await ping({address: endpoint.address, port:endpoint.port})
return r.errors.length === 0
}
else if (endpoint.type === "ping") {
const r = await pingPromise.probe(endpoint.address)
return r.alive
}
else return true
}
const executor = async () => {
const curTime = Date.now()
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 ?? config.defaults.interval) * 1000)) {
console.log(`Time to poll ${endpoint.name}`)
endpointState.lastExec = curTime
if (await isEndpointUp(endpoint)) handleUp(endpointState, curTime, endpoint)
else handleDown(endpointState, curTime, endpoint)
}
})
}
const main = async () => {
while (true) {
await sleep(1000)
executor()
}
}
main()