Skip to content

Commit 516acfc

Browse files
committed
Skip caching a notification configuration that changed during its lookup
The change stream handler only refreshes cached buckets. When a bucket's configuration changed while its lookup was in flight, the handler skipped it, and the lookup then cached what it read before the change: a stale configuration, or since BB-908 a stale absence of one, kept until the bucket changes again or is evicted. Track the lookups in flight per bucket, have the handler flag those of the bucket that changed, and return their result without caching it, so that the next entry reads it again. Also read the configuration from the primary, whatever the configured read preference: the change stream reports majority-committed changes, so a lookup started after a change was handled could otherwise still read the previous configuration from a lagging secondary, and cache it. Issue: BB-939
1 parent 83567b4 commit 516acfc

2 files changed

Lines changed: 138 additions & 7 deletions

File tree

‎extensions/notification/configManager/MongoConfigManager.js‎

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const { ZenkoMetrics } = require('@scality/arsenal').metrics;
55
const LRUCache = require('@scality/arsenal').algorithms.cache.LRUCache;
66
const { errors } = require('@scality/arsenal');
77

8-
const MongoClient = require('mongodb').MongoClient;
8+
const { MongoClient, ReadPreference } = require('mongodb');
99

1010
const ChangeStream = require('../../../lib/wrappers/ChangeStream');
1111
const { constructConnectionString, getMongoVersion } = require('../../utils/MongoUtils');
@@ -84,6 +84,7 @@ class MongoConfigManager extends BaseConfigManager {
8484
this._logger = params.logger;
8585
this._mongoConfig = params.mongoConfig;
8686
this._cachedConfigs = new LRUCache(params.maxCachedConfigs);
87+
this._pendingLookups = new Map();
8788
this._bucketMetastore = params.bucketMetastore;
8889
this._mongoClient = null;
8990
this._metastore = null;
@@ -142,6 +143,11 @@ class MongoConfigManager extends BaseConfigManager {
142143
* @returns {undefined}
143144
*/
144145
_handleChangeStreamChangeEvent(change) {
146+
// any change event can change the configuration. we don't know if it was an
147+
// actual change or a noop from just the event and an empty cache.
148+
for (const lookup of this._pendingLookups.get(change.documentKey._id) ?? []) {
149+
lookup.changed = true;
150+
}
145151
// invalidating cached notification configs
146152
const cachedConfig = this._cachedConfigs.get(change.documentKey._id);
147153
const bucketNotificationConfiguration = change.fullDocument
@@ -271,23 +277,35 @@ class MongoConfigManager extends BaseConfigManager {
271277
notificationConfiguration: cachedConfig,
272278
};
273279
}
280+
const lookup = { changed: false };
281+
this._addPendingLookup(bucket, lookup);
274282
try {
275283
// retreiving bucket metadata from the metastore
276-
const bucketMetadata = await this._metastore.findOne({ _id: bucket });
284+
// from the primary: the change stream reports majority-committed
285+
// changes, which a lagging secondary could still miss
286+
const bucketMetadata = await this._metastore.findOne(
287+
{ _id: bucket },
288+
{ readPreference: ReadPreference.PRIMARY },
289+
);
277290
const notificationConfiguration = bucketMetadata?.value?.notificationConfiguration;
278291
const delay = (Date.now() - startTime) / 1000;
279292
onConfigManagerConfigGet(false, delay);
280293
// when disabled after being enabled bucket notification configuration is set to an empty object
281-
if (!notificationConfiguration || !Object.keys(notificationConfiguration).length) {
294+
const hasConfig = notificationConfiguration && Object.keys(notificationConfiguration).length > 0;
295+
if (lookup.changed) {
296+
this._logger.debug('not caching configuration read while the bucket changed', {
297+
method: 'MongoConfigManager.getConfig',
298+
bucket,
299+
});
300+
} else {
282301
// caching the absence of configuration too, so that the
283302
// entries of buckets without one do not each cost a lookup
284-
this._cachedConfigs.add(bucket, NO_CONFIG);
303+
this._cachedConfigs.add(bucket, hasConfig ? notificationConfiguration : NO_CONFIG);
285304
onConfigManagerCacheUpdate('add', this._cachedConfigs.count());
305+
}
306+
if (!hasConfig) {
286307
return undefined;
287308
}
288-
// caching the bucket configuration
289-
this._cachedConfigs.add(bucket, notificationConfiguration);
290-
onConfigManagerCacheUpdate('add', this._cachedConfigs.count());
291309
return {
292310
bucket,
293311
notificationConfiguration,
@@ -299,6 +317,25 @@ class MongoConfigManager extends BaseConfigManager {
299317
error: err.message,
300318
});
301319
throw errors.InternalError.customizeDescription(err.message);
320+
} finally {
321+
this._removePendingLookup(bucket, lookup);
322+
}
323+
}
324+
325+
_addPendingLookup(bucket, lookup) {
326+
const lookups = this._pendingLookups.get(bucket);
327+
if (lookups) {
328+
lookups.add(lookup);
329+
} else {
330+
this._pendingLookups.set(bucket, new Set([lookup]));
331+
}
332+
}
333+
334+
_removePendingLookup(bucket, lookup) {
335+
const lookups = this._pendingLookups.get(bucket);
336+
lookups.delete(lookup);
337+
if (lookups.size === 0) {
338+
this._pendingLookups.delete(bucket);
302339
}
303340
}
304341

‎tests/unit/notification/configManager/MongoConfigManager.spec.js‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,14 @@ describe('MongoConfigManager ::', () => {
354354
assert.deepEqual(manager._cachedConfigs.get('example-bucket-1'), notificationConfiguration);
355355
});
356356

357+
it('should read the configuration from the primary', async () => {
358+
const manager = new MongoConfigManager(params);
359+
const findOne = sinon.stub().resolves({ value: { notificationConfiguration } });
360+
manager._metastore = { findOne };
361+
await manager.getConfig('example-bucket-1');
362+
assert(findOne.calledOnceWithExactly({ _id: 'example-bucket-1' }, { readPreference: 'primary' }));
363+
});
364+
357365
it('should throw when mongo findOne fails', done => {
358366
const manager = new MongoConfigManager(params);
359367
manager._metastore = {
@@ -427,6 +435,92 @@ describe('MongoConfigManager ::', () => {
427435
});
428436
});
429437

438+
describe('getConfig of buckets changed during the lookup ::', () => {
439+
const updateEvent = (bucket, config) => ({
440+
_id: 'resumeToken',
441+
operationType: 'update',
442+
documentKey: { _id: bucket },
443+
fullDocument: {
444+
_id: bucket,
445+
value: { notificationConfiguration: config },
446+
},
447+
});
448+
449+
it('should return but not cache a configuration that changed during its lookup', async () => {
450+
const manager = new MongoConfigManager(params);
451+
const findOne = sinon.stub().callsFake(async () => {
452+
manager._handleChangeStreamChangeEvent(
453+
updateEvent('example-bucket-1', notificationConfigurationVariant),
454+
);
455+
return { value: { notificationConfiguration } };
456+
});
457+
manager._metastore = { findOne };
458+
assert.deepStrictEqual(await manager.getConfig('example-bucket-1'), {
459+
bucket: 'example-bucket-1',
460+
notificationConfiguration,
461+
});
462+
assert.strictEqual(manager._cachedConfigs.get('example-bucket-1'), undefined);
463+
await manager.getConfig('example-bucket-1');
464+
assert.strictEqual(findOne.callCount, 2);
465+
});
466+
467+
it('should not cache a missing configuration when one got enabled during its lookup', async () => {
468+
const manager = new MongoConfigManager(params);
469+
const findOne = sinon.stub();
470+
findOne.onFirstCall().callsFake(async () => {
471+
manager._handleChangeStreamChangeEvent(updateEvent('example-bucket-1', notificationConfiguration));
472+
return { value: {} };
473+
});
474+
findOne.onSecondCall().resolves({ value: { notificationConfiguration } });
475+
manager._metastore = { findOne };
476+
assert.strictEqual(await manager.getConfig('example-bucket-1'), undefined);
477+
assert.strictEqual(manager._cachedConfigs.get('example-bucket-1'), undefined);
478+
assert.deepStrictEqual(await manager.getConfig('example-bucket-1'), {
479+
bucket: 'example-bucket-1',
480+
notificationConfiguration,
481+
});
482+
});
483+
484+
it('should cache a configuration when another bucket changed during its lookup', async () => {
485+
const manager = new MongoConfigManager(params);
486+
manager._metastore = {
487+
findOne: async () => {
488+
manager._handleChangeStreamChangeEvent(
489+
updateEvent('example-bucket-2', notificationConfigurationVariant),
490+
);
491+
return { value: { notificationConfiguration } };
492+
},
493+
};
494+
await manager.getConfig('example-bucket-1');
495+
assert.deepStrictEqual(manager._cachedConfigs.get('example-bucket-1'), notificationConfiguration);
496+
});
497+
498+
it('should cache a lookup started after the change', async () => {
499+
const manager = new MongoConfigManager(params);
500+
let second;
501+
const findOne = sinon.stub();
502+
findOne.onFirstCall().callsFake(async () => {
503+
manager._handleChangeStreamChangeEvent(
504+
updateEvent('example-bucket-1', notificationConfigurationVariant),
505+
);
506+
second = manager.getConfig('example-bucket-1');
507+
return { value: { notificationConfiguration } };
508+
});
509+
findOne.onSecondCall().resolves({ value: { notificationConfiguration: notificationConfigurationVariant } });
510+
manager._metastore = { findOne };
511+
await manager.getConfig('example-bucket-1');
512+
await second;
513+
assert.deepStrictEqual(manager._cachedConfigs.get('example-bucket-1'), notificationConfigurationVariant);
514+
});
515+
516+
it('should forget the lookup when it fails', async () => {
517+
const manager = new MongoConfigManager(params);
518+
manager._metastore = { findOne: sinon.stub().rejects(new Error('read failed')) };
519+
await assert.rejects(manager.getConfig('example-bucket-1'));
520+
assert.strictEqual(manager._pendingLookups.size, 0);
521+
});
522+
});
523+
430524
describe('setConfig ::', () => {
431525
it('should always return false', async () => {
432526
const manager = new MongoConfigManager(params);

0 commit comments

Comments
 (0)