Skip to content

Commit

Permalink
Add in-memory cache assertions.
Browse files Browse the repository at this point in the history
  • Loading branch information
dlongley committed Nov 16, 2024
1 parent a303905 commit e8e54d7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const TEXT_ENCODER = new TextEncoder();

const COLLECTION_NAME = 'tokenized-cache-entry';

// in-memory entries cache
let ENTRY_CACHE;
// in-memory entries cache; exported for testing purposes only
export let ENTRY_CACHE;

bedrock.events.on('bedrock.init', async () => {
_createEntryCache();
Expand Down
26 changes: 26 additions & 0 deletions test/mocha/10-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ describe('Cache', function() {
});

it('should replace an existing cache entry', async () => {
// clear cache
cache.ENTRY_CACHE.cache.reset();

const id = crypto.randomUUID();
const record1 = await cache.upsert({
id,
Expand All @@ -30,8 +33,11 @@ describe('Cache', function() {
// first fetch should hit database, second in-memory cache
const record1a = await cache.get({id});
record1.should.eql(record1a);
cache.ENTRY_CACHE.cache.itemCount.should.equal(1);
const record1b = await cache.get({id});
record1a.should.eql(record1b);
// should have reused cache
cache.ENTRY_CACHE.cache.itemCount.should.equal(1);

const record2 = await cache.upsert({
id,
Expand All @@ -40,7 +46,10 @@ describe('Cache', function() {
});
// first fetch should hit database, second in-memory cache
const record2a = await cache.get({id});
cache.ENTRY_CACHE.cache.itemCount.should.equal(1);
const record2b = await cache.get({id});
// should have reused cache
cache.ENTRY_CACHE.cache.itemCount.should.equal(1);
record1.should.not.eql(record2);
record2.should.eql(record2a);
record2b.should.eql(record2a);
Expand Down Expand Up @@ -69,7 +78,21 @@ describe('Cache', function() {
});

it('should return not found for an expired entry', async () => {
// clear cache
cache.ENTRY_CACHE.cache.reset();

// add entry with long TTL
const id = crypto.randomUUID();
await cache.upsert({
id,
value: {},
ttl: 30000
});
await cache.get({id});
// confirm cache population
cache.ENTRY_CACHE.cache.itemCount.should.equal(1);

// overwrite with expired entry
await cache.upsert({
id,
value: {},
Expand All @@ -83,6 +106,9 @@ describe('Cache', function() {
err = e;
}
err.name.should.equal('NotFoundError');

// cache entry should have been deleted
cache.ENTRY_CACHE.cache.itemCount.should.equal(0);
});
});

Expand Down

0 comments on commit e8e54d7

Please sign in to comment.