From d122b224b033582f74a14bcb542b91812b029d47 Mon Sep 17 00:00:00 2001 From: Zaid Humaimidi Date: Thu, 16 Nov 2023 15:58:26 -0800 Subject: [PATCH] Resolve issues from DB lock collection migration --- lib/api-functions.ts | 7 +++---- lib/local-cache.ts | 4 ++-- lib/lock.ts | 5 +++++ 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/lib/api-functions.ts b/lib/api-functions.ts index a5d5e88..898fbec 100644 --- a/lib/api-functions.ts +++ b/lib/api-functions.ts @@ -39,6 +39,7 @@ import { } from "./ui/db"; import * as common from "./util"; import * as cache from "./cache"; +import { lockExists } from "./lock"; import { getRevision, getConfig, @@ -211,8 +212,7 @@ export async function awaitSessionStart( ); const li = (device["_lastInform"] as Date).getTime(); if (li > lastInform) return true; - const token = await cache.get(`cwmp_session_${deviceId}`); - if (token) return true; + if (await lockExists(`cwmp_session_${deviceId}`)) return true; if (timeout < 500) return false; await new Promise((resolve) => setTimeout(resolve, 500)); timeout -= Date.now() - now; @@ -224,8 +224,7 @@ export async function awaitSessionEnd( timeout: number ): Promise { const now = Date.now(); - const token = await cache.get(`cwmp_session_${deviceId}`); - if (!token) return true; + if (!(await lockExists(`cwmp_session_${deviceId}`))) return true; if (timeout < 500) return false; await new Promise((resolve) => setTimeout(resolve, 500)); timeout -= Date.now() - now; diff --git a/lib/local-cache.ts b/lib/local-cache.ts index 3b6bb59..640cf6c 100644 --- a/lib/local-cache.ts +++ b/lib/local-cache.ts @@ -67,7 +67,7 @@ export class LocalCache { return; } - const lockToken = await acquireLock(this.cacheKey + "_lock", 5000); + const lockToken = await acquireLock(this.cacheKey, 5000); const [hash, snapshot] = await this.callback(); @@ -84,7 +84,7 @@ export class LocalCache { if (lockToken) { if (hash !== dbHash) await set(this.cacheKey, hash, 300); - await releaseLock(this.cacheKey + "_lock", lockToken); + await releaseLock(this.cacheKey, lockToken); } this.nextRefresh = now + (REFRESH - (now % REFRESH)); diff --git a/lib/lock.ts b/lib/lock.ts index d2eac0e..623a294 100644 --- a/lib/lock.ts +++ b/lib/lock.ts @@ -43,3 +43,8 @@ export async function releaseLock( }); if (res.deletedCount !== 1) throw new Error("Lock expired"); } + +export async function lockExists(lockName: string): Promise { + const res = await collections.locks.findOne({ _id: lockName }); + return res != null; +}