Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): keep a refresh requested as the key index load ends

Yudhi Armyndharisabf9c2a94a4d
diff --git a/src/modules/auth/active-key-index.spec.ts b/src/modules/auth/active-key-index.spec.ts
index 6bbfa3f58..4c0c7736c 100644
--- a/src/modules/auth/active-key-index.spec.ts
+++ b/src/modules/auth/active-key-index.spec.ts
@@ -99,6 +99,28 @@ describe('ActiveKeyIndex', () => {
expect(find).toHaveBeenCalledTimes(3);
});
+ it('never drops a refresh requested as the running load finishes', async () => {
+ // A write's continuation can run in any microtask around the end of the running load; each
+ // depth must still get the load after the one in flight.
+ for (let depth = 0; depth < 8; depth++) {
+ let calls = 0;
+ const { index, find } = indexOver(() => {
+ calls++;
+ if (calls === 2) {
+ let hop: Promise<void> = Promise.resolve();
+ for (let i = 0; i < depth; i++) hop = hop.then(() => undefined);
+ void hop.then(() => index.refreshSoon());
+ }
+ return Promise.resolve([row('k1')]);
+ });
+ await index.onApplicationBootstrap();
+ index.refreshSoon();
+ await new Promise(resolve => setImmediate(resolve));
+ index.onModuleDestroy();
+ expect({ depth, loads: find.mock.calls.length }).toEqual({ depth, loads: 3 });
+ }
+ });
+
it('refreshes on an interval until destroyed', async () => {
jest.useFakeTimers();
const { index, find } = indexOver([row('k1')]);
diff --git a/src/modules/auth/active-key-index.ts b/src/modules/auth/active-key-index.ts
index 842c7d65e..50b4922d7 100644
--- a/src/modules/auth/active-key-index.ts
+++ b/src/modules/auth/active-key-index.ts
@@ -60,14 +60,19 @@ export class ActiveKeyIndex implements OnApplicationBootstrap, OnModuleDestroy {
this.reloadAgain = true;
return;
}
+ // Cleared in the same continuation that leaves the loop: a `.finally` on the returned promise
+ // would run a microtask later, and a call landing in that gap would set reloadAgain after the
+ // loop had stopped reading it. load() always awaits, so the assignment lands first.
this.loading = (async () => {
- do {
- this.reloadAgain = false;
- await this.load();
- } while (this.reloadAgain && !this.destroyed);
- })().finally(() => {
- this.loading = undefined;
- });
+ try {
+ do {
+ this.reloadAgain = false;
+ await this.load();
+ } while (this.reloadAgain && !this.destroyed);
+ } finally {
+ this.loading = undefined;
+ }
+ })();
}
/**