Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions extensions/notification/configManager/MongoConfigManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { ZenkoMetrics } = require('@scality/arsenal').metrics;
const LRUCache = require('@scality/arsenal').algorithms.cache.LRUCache;
const { errors } = require('@scality/arsenal');

const MongoClient = require('mongodb').MongoClient;
const { MongoClient, ReadPreference } = require('mongodb');

const ChangeStream = require('../../../lib/wrappers/ChangeStream');
const { constructConnectionString, getMongoVersion } = require('../../utils/MongoUtils');
Expand Down Expand Up @@ -84,6 +84,7 @@ class MongoConfigManager extends BaseConfigManager {
this._logger = params.logger;
this._mongoConfig = params.mongoConfig;
this._cachedConfigs = new LRUCache(params.maxCachedConfigs);
this._pendingLookups = new Map();
this._bucketMetastore = params.bucketMetastore;
this._mongoClient = null;
this._metastore = null;
Expand Down Expand Up @@ -142,6 +143,11 @@ class MongoConfigManager extends BaseConfigManager {
* @returns {undefined}
*/
_handleChangeStreamChangeEvent(change) {
// any change event can change the configuration. we don't know if it was an
// actual change or a noop from just the event and an empty cache.
for (const lookup of this._pendingLookups.get(change.documentKey._id) ?? []) {
Comment thread
delthas marked this conversation as resolved.
Resolved
lookup.changed = true;
}
// invalidating cached notification configs
const cachedConfig = this._cachedConfigs.get(change.documentKey._id);
const bucketNotificationConfiguration = change.fullDocument
Expand Down Expand Up @@ -271,23 +277,35 @@ class MongoConfigManager extends BaseConfigManager {
notificationConfiguration: cachedConfig,
};
}
const lookup = { changed: false };
this._addPendingLookup(bucket, lookup);
try {
// retreiving bucket metadata from the metastore
const bucketMetadata = await this._metastore.findOne({ _id: bucket });
// from the primary: the change stream reports majority-committed
// changes, which a lagging secondary could still miss
const bucketMetadata = await this._metastore.findOne(
{ _id: bucket },
{ readPreference: ReadPreference.PRIMARY },
);
const notificationConfiguration = bucketMetadata?.value?.notificationConfiguration;
const delay = (Date.now() - startTime) / 1000;
onConfigManagerConfigGet(false, delay);
// when disabled after being enabled bucket notification configuration is set to an empty object
if (!notificationConfiguration || !Object.keys(notificationConfiguration).length) {
const hasConfig = notificationConfiguration && Object.keys(notificationConfiguration).length > 0;
if (lookup.changed) {
this._logger.debug('not caching configuration read while the bucket changed', {
method: 'MongoConfigManager.getConfig',
bucket,
});
} else {
// caching the absence of configuration too, so that the
// entries of buckets without one do not each cost a lookup
this._cachedConfigs.add(bucket, NO_CONFIG);
this._cachedConfigs.add(bucket, hasConfig ? notificationConfiguration : NO_CONFIG);
onConfigManagerCacheUpdate('add', this._cachedConfigs.count());
}
if (!hasConfig) {
return undefined;
}
// caching the bucket configuration
this._cachedConfigs.add(bucket, notificationConfiguration);
onConfigManagerCacheUpdate('add', this._cachedConfigs.count());
return {
bucket,
notificationConfiguration,
Expand All @@ -299,6 +317,25 @@ class MongoConfigManager extends BaseConfigManager {
error: err.message,
});
throw errors.InternalError.customizeDescription(err.message);
} finally {
this._removePendingLookup(bucket, lookup);
}
}

_addPendingLookup(bucket, lookup) {
const lookups = this._pendingLookups.get(bucket);
if (lookups) {
lookups.add(lookup);
} else {
this._pendingLookups.set(bucket, new Set([lookup]));
}
}

_removePendingLookup(bucket, lookup) {
const lookups = this._pendingLookups.get(bucket);
lookups.delete(lookup);
if (lookups.size === 0) {
this._pendingLookups.delete(bucket);
}
}

Expand Down
94 changes: 94 additions & 0 deletions tests/unit/notification/configManager/MongoConfigManager.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,14 @@ describe('MongoConfigManager ::', () => {
assert.deepEqual(manager._cachedConfigs.get('example-bucket-1'), notificationConfiguration);
});

it('should read the configuration from the primary', async () => {
const manager = new MongoConfigManager(params);
const findOne = sinon.stub().resolves({ value: { notificationConfiguration } });
manager._metastore = { findOne };
await manager.getConfig('example-bucket-1');
assert(findOne.calledOnceWithExactly({ _id: 'example-bucket-1' }, { readPreference: 'primary' }));
});

it('should throw when mongo findOne fails', done => {
const manager = new MongoConfigManager(params);
manager._metastore = {
Expand Down Expand Up @@ -427,6 +435,92 @@ describe('MongoConfigManager ::', () => {
});
});

describe('getConfig of buckets changed during the lookup ::', () => {
Comment thread
delthas marked this conversation as resolved.
Resolved
const updateEvent = (bucket, config) => ({
_id: 'resumeToken',
operationType: 'update',
documentKey: { _id: bucket },
fullDocument: {
_id: bucket,
value: { notificationConfiguration: config },
},
});

it('should return but not cache a configuration that changed during its lookup', async () => {
const manager = new MongoConfigManager(params);
const findOne = sinon.stub().callsFake(async () => {
manager._handleChangeStreamChangeEvent(
updateEvent('example-bucket-1', notificationConfigurationVariant),
);
return { value: { notificationConfiguration } };
});
manager._metastore = { findOne };
assert.deepStrictEqual(await manager.getConfig('example-bucket-1'), {
bucket: 'example-bucket-1',
notificationConfiguration,
});
assert.strictEqual(manager._cachedConfigs.get('example-bucket-1'), undefined);
await manager.getConfig('example-bucket-1');
assert.strictEqual(findOne.callCount, 2);
});

it('should not cache a missing configuration when one got enabled during its lookup', async () => {
const manager = new MongoConfigManager(params);
const findOne = sinon.stub();
findOne.onFirstCall().callsFake(async () => {
manager._handleChangeStreamChangeEvent(updateEvent('example-bucket-1', notificationConfiguration));
return { value: {} };
});
findOne.onSecondCall().resolves({ value: { notificationConfiguration } });
manager._metastore = { findOne };
assert.strictEqual(await manager.getConfig('example-bucket-1'), undefined);
assert.strictEqual(manager._cachedConfigs.get('example-bucket-1'), undefined);
assert.deepStrictEqual(await manager.getConfig('example-bucket-1'), {
bucket: 'example-bucket-1',
notificationConfiguration,
});
});

it('should cache a configuration when another bucket changed during its lookup', async () => {
const manager = new MongoConfigManager(params);
manager._metastore = {
findOne: async () => {
manager._handleChangeStreamChangeEvent(
updateEvent('example-bucket-2', notificationConfigurationVariant),
);
return { value: { notificationConfiguration } };
},
};
await manager.getConfig('example-bucket-1');
assert.deepStrictEqual(manager._cachedConfigs.get('example-bucket-1'), notificationConfiguration);
});

it('should cache a lookup started after the change', async () => {
const manager = new MongoConfigManager(params);
let second;
const findOne = sinon.stub();
findOne.onFirstCall().callsFake(async () => {
manager._handleChangeStreamChangeEvent(
updateEvent('example-bucket-1', notificationConfigurationVariant),
);
second = manager.getConfig('example-bucket-1');
return { value: { notificationConfiguration } };
});
findOne.onSecondCall().resolves({ value: { notificationConfiguration: notificationConfigurationVariant } });
manager._metastore = { findOne };
await manager.getConfig('example-bucket-1');
await second;
assert.deepStrictEqual(manager._cachedConfigs.get('example-bucket-1'), notificationConfigurationVariant);
});

it('should forget the lookup when it fails', async () => {
const manager = new MongoConfigManager(params);
manager._metastore = { findOne: sinon.stub().rejects(new Error('read failed')) };
await assert.rejects(manager.getConfig('example-bucket-1'));
assert.strictEqual(manager._pendingLookups.size, 0);
});
});

describe('setConfig ::', () => {
it('should always return false', async () => {
const manager = new MongoConfigManager(params);
Expand Down
Loading