[enh] add BMA watcher + reorganize code
This commit is contained in:
50
src/lib/watcherLoop.ts
Normal file
50
src/lib/watcherLoop.ts
Normal 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++
|
||||
}
|
||||
})()
|
||||
}
|
||||
Reference in New Issue
Block a user