From 6607b306d0d91354f47dbf3cd8f287e05a37e68f Mon Sep 17 00:00:00 2001 From: Martin Dimitrov Date: Sun, 27 Oct 2024 08:00:17 -0700 Subject: [PATCH] clear residual timers --- .../functions/buzzer-activated.js | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/doorman-client/functions/buzzer-activated.js b/packages/doorman-client/functions/buzzer-activated.js index e4f3108..909084e 100644 --- a/packages/doorman-client/functions/buzzer-activated.js +++ b/packages/doorman-client/functions/buzzer-activated.js @@ -72,21 +72,23 @@ exports.handler = async function(context, event, callback) { )); let discordLock = false; + let intervals = []; + let timeouts = []; const unlockPromise = new Promise((resolve, reject) => { - const interval = setInterval(() => { + intervals.push(setInterval(() => { fetch(context.DOORMAN_URL + `/api/door/status?door=${config.door}`) .then(async res => { if (res.status === 200) { - clearInterval(interval); + clearInterval(intervals[0]); const body = await res.json(); const twiml = new Twilio.twiml.VoiceResponse(); doorOpenTwiml(twiml, config); if (!discordLock) { + discordLock = true; console.log( "UnlockPromise: I was the fastest, so I will attempt to notify discord users before resolving with unlock" ); - discordLock = true; await notifyAllDiscord(context, config, `🔓 Doorman buzzed someone up @ Door "${config.door}"`, JSON.stringify(body.fingerprint)); resolve(twiml); } else { @@ -96,19 +98,20 @@ exports.handler = async function(context, event, callback) { } } }).catch(err => console.log(err)); - }, 500) + }, 500)); }); const gracefulFallbackPromise = new Promise((resolve, reject) => { - setTimeout(async () => { + timeouts.push(setTimeout(async () => { const twiml = new Twilio.twiml.VoiceResponse(); dialFallbackTwiml(twiml, config); if (!discordLock) { + discordLock = true; + console.log( "GracefulFallbackPromise: I was the fastest, so I will attempt to notify discord users before resolving with a call" ); - discordLock = true; await notifyAllDiscord( context, config, @@ -120,20 +123,23 @@ exports.handler = async function(context, event, callback) { "GracefulFallbackPromise: dropping out of the race, unlock is already notifying discord users" ); } - }, 6000); + }, 6000)); }); const ungracefulFallbackPromise = new Promise((resolve, reject) => { - setTimeout(async () => { + timeouts.push(setTimeout(async () => { const twiml = new Twilio.twiml.VoiceResponse(); dialFallbackTwiml(twiml, config); console.error( "UngracefulFallbackPromise: Cutting it too close to timeout! Skipping notifying users and calling fallback" ); resolve(twiml); - }, 8000); + }, 8000)); }); const twiml = await Promise.race([unlockPromise, gracefulFallbackPromise, ungracefulFallbackPromise]); + console.log("Race ended, clearing residual timers"); + timeouts.forEach(timeout => clearTimeout(timeout)); + intervals.forEach(interval => clearInterval(interval)); callback(null, twiml); };