Skip to content

Commit 652486c

Browse files
committed
feat(NODE-5035): cleanup cache ono each request
1 parent a466fb6 commit 652486c

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

src/cmap/auth/mongodb_oidc/callback_workflow.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ export class CallbackWorkflow implements Workflow {
131131
): Promise<Document> {
132132
// Call the request callback.
133133
const request = credentials.mechanismProperties.REQUEST_TOKEN_CALLBACK;
134+
// Always clear expired entries from the cache on each finish as cleanup.
135+
this.cache.deleteExpiredEntries();
134136
if (request) {
135137
const tokenResult = await request(credentials.username, stepOneResult, TIMEOUT);
136138
// Cache a new entry and continue with the saslContinue.

src/cmap/auth/mongodb_oidc/token_entry_cache.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,17 @@ export class TokenEntryCache {
8282
getEntry(address: string, username = ''): TokenEntry | undefined {
8383
return this.entries.get(cacheKey(address, username));
8484
}
85+
86+
/**
87+
* Delete all expired entries from the cache.
88+
*/
89+
deleteExpiredEntries(): void {
90+
this.entries.forEach((entry, key, entries) => {
91+
if (!entry.isValid()) {
92+
entries.delete(key);
93+
}
94+
});
95+
}
8596
}
8697

8798
/**

test/unit/cmap/auth/mongodb_oidc/token_entry_cache.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,25 @@ describe('TokenEntryCache', function () {
6464
});
6565
});
6666

67+
describe('#deleteExpiredEntries', function () {
68+
const cache = new TokenEntryCache();
69+
70+
const nonExpiredResult = {
71+
accessToken: 'test',
72+
expiresInSeconds: 600
73+
};
74+
75+
before(function () {
76+
cache.addEntry(tokenResult, serverResult, 'localhost', 'user');
77+
cache.addEntry(nonExpiredResult, serverResult, 'localhost', 'user2');
78+
cache.deleteExpiredEntries();
79+
});
80+
81+
it('deletes all expired tokens from the cache', function () {
82+
expect(cache.entries.size).to.equal(1);
83+
});
84+
});
85+
6786
describe('#deleteEntry', function () {
6887
const cache = new TokenEntryCache();
6988

0 commit comments

Comments
 (0)