[enh] add BMA watcher + reorganize code

This commit is contained in:
2019-06-08 18:34:39 +02:00
parent d02de7842f
commit 5544d56ebb
13 changed files with 232 additions and 606 deletions

50
src/lib/watcherLoop.ts Normal file
View File

@@ -0,0 +1,50 @@
export async function watcherLoop(
connect: () => Promise<void>,
onConnectionClosed: () => Promise<void>,
reconnectionDelays: number[],
onStart: () => Promise<void>,
onDisconnection: (waitingDelay: number) => Promise<void>,
onRestart: () => Promise<void>,
onRestartSuccess: () => Promise<void>,
onError: (e: Error) => Promise<void>,
) {
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()
} else {
await onRestartSuccess()
}
// We reset the delay of reconnection
i = 0
await onConnectionClosed()
} catch (e) {
await onError(e)
}
// Wait before reconnecting
const waitingDelay = reconnectionDelays[Math.min(reconnectionDelays.length - 1, i)]
await onDisconnection(waitingDelay)
await new Promise(resolve => setTimeout(resolve, waitingDelay))
i++
}
})()
}