Skip to content

Commit bcf2784

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

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

src/cmap/auth/mongodb_oidc/callback_workflow.ts

+2
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

+12
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export class TokenEntry {
2929
* 5 minutes from the expiration time.
3030
*/
3131
isValid() {
32+
console.log(this.expiration);
3233
return this.expiration - Date.now() > EXPIRATION_BUFFER;
3334
}
3435
}
@@ -82,6 +83,17 @@ export class TokenEntryCache {
8283
getEntry(address: string, username = ''): TokenEntry | undefined {
8384
return this.entries.get(cacheKey(address, username));
8485
}
86+
87+
/**
88+
* Delete all expired entries from the cache.
89+
*/
90+
deleteExpiredEntries(): void {
91+
this.entries.forEach((entry, key, entries) => {
92+
if (!entry.isValid()) {
93+
entries.delete(key);
94+
}
95+
});
96+
}
8597
}
8698

8799
/**

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

+19
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)