61 lines
1.4 KiB
TypeScript
61 lines
1.4 KiB
TypeScript
import {Watcher} from "./types/state";
|
|
|
|
export function watcherLoop(
|
|
name: string,
|
|
connect: () => Promise<void>,
|
|
onConnectionClosed: () => Promise<void>,
|
|
waitingDelay: number,
|
|
recallDelay: number,
|
|
onStart: () => Promise<void>,
|
|
onDisconnection: (waitingDelay: number, recallDelay: number, error: any) => Promise<void>,
|
|
onRestart: () => Promise<void>,
|
|
onRestartSuccess: () => Promise<void>,
|
|
): Watcher {
|
|
|
|
let watcher: Watcher = new Watcher(name, recallDelay)
|
|
let hasStarted = false
|
|
|
|
;(async () => {
|
|
|
|
let connected = false
|
|
let i = 0
|
|
while (!connected) {
|
|
try {
|
|
|
|
if (hasStarted) {
|
|
await onRestart()
|
|
}
|
|
|
|
// Connection trial
|
|
await connect()
|
|
|
|
if (!hasStarted) {
|
|
hasStarted = true
|
|
await onStart()
|
|
watcher.stateOK()
|
|
} else {
|
|
await onRestartSuccess()
|
|
watcher.stateRecovered()
|
|
}
|
|
|
|
// We reset the delay of reconnection
|
|
i = 0
|
|
|
|
await onConnectionClosed()
|
|
|
|
} catch (e) {
|
|
watcher.stateFailure(e)
|
|
}
|
|
// Wait before reconnecting
|
|
if (watcher.stateChanged) {
|
|
// Notify only if state changed since
|
|
await onDisconnection(waitingDelay, recallDelay, watcher.error)
|
|
}
|
|
await new Promise(resolve => setTimeout(resolve, waitingDelay))
|
|
i++
|
|
}
|
|
})()
|
|
|
|
return watcher
|
|
}
|