Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache Mongo-DB calls (in-memory and/or Redis) #926

Draft
wants to merge 29 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
4e6f9f1
Cache Mongo-DB calls.
jason-fox Oct 26, 2020
7872370
Linting - move functions.
jason-fox Oct 26, 2020
c2a7ea0
Merge branch 'master' into feature/cache
jason-fox Nov 2, 2020
9471f42
Make Caching configurable.
jason-fox Nov 2, 2020
7a8edc8
Add documentation
jason-fox Nov 2, 2020
d0fe4f8
Amend documentation.
jason-fox Nov 2, 2020
5d08c0e
Tidying up code and tests.
jason-fox Nov 2, 2020
6b6dba7
Merge branch 'master' into feature/cache
jason-fox Nov 16, 2020
3c1190c
Merge commit 'master' into feature/cache
jason-fox Nov 18, 2020
60d7dca
Complete linting using ESLint.
jason-fox Nov 18, 2020
56c8023
Merge branch 'master' into feature/cache
jason-fox Nov 27, 2020
90d1318
Merge branch 'master' into feature/cache
jason-fox Dec 4, 2020
acad317
Fixing merge
jason-fox Dec 4, 2020
4b7a08a
Adding Redis Cache
jason-fox Dec 7, 2020
b0daf0a
Adding Start-up test for Redis and Memcache
jason-fox Dec 7, 2020
5eaef79
Updating Docs
jason-fox Dec 7, 2020
94bc29e
Merge branch 'master' into feature/cache
jason-fox Dec 10, 2020
76dcd15
Remove debug
jason-fox Dec 10, 2020
7d88f72
Merge branch 'master' into feature/cache
jason-fox Dec 15, 2020
bb0c277
Merge branch 'master' into feature/cache
jason-fox Jan 21, 2021
55e017b
Merge branch 'master' into feature/cache
jason-fox Feb 11, 2021
a0b1dd8
Merge branch 'master' into feature/cache
jason-fox Feb 12, 2021
880f164
Merge branch 'master' into feature/cache
jason-fox Mar 2, 2021
cfdd819
Merge branch 'master' into feature/cache
jason-fox Mar 16, 2021
d39a90b
Merge branch 'master' into feature/cache
jason-fox Apr 13, 2021
e98c02e
Set cache rather than don't cache
jason-fox Apr 13, 2021
7753fec
Delete file.
jason-fox Jun 24, 2021
f3d6622
Merge branch 'master' into feature/cache
jason-fox Jun 24, 2021
12f9bcb
Merge branch 'master' into feature/cache
jason-fox Sep 17, 2021
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
136 changes: 87 additions & 49 deletions lib/services/devices/deviceRegistryMongoDB.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,45 @@
* please contact with::[email protected]
*/

var logger = require('logops'),
dbService = require('../../model/dbConn'),
config = require('../../commonConfig'),
fillService = require('./../common/domain').fillService,
alarmsInt = require('../common/alarmManagement').intercept,
errors = require('../../errors'),
constants = require('../../constants'),
Device = require('../../model/Device'),
async = require('async'),
context = {
op: 'IoTAgentNGSI.MongoDBDeviceRegister'
};
const logger = require('logops');
const dbService = require('../../model/dbConn');
const config = require('../../commonConfig');
const fillService = require('./../common/domain').fillService;
const alarmsInt = require('../common/alarmManagement').intercept;
const errors = require('../../errors');
const constants = require('../../constants');
const Device = require('../../model/Device');
const async = require('async');
const cacheManager = require('cache-manager');
const memoryCache = cacheManager.caching({store: 'memory', max: 1000, ttl: 10/*seconds*/});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Magic numbers. MUST be config.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In addition, I think the whole possibilty of not using cache (e.g. something like cache: true|false in configuration) should be provided.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed 9471f42 and subsequent pushes.

let context = {
op: 'IoTAgentNGSI.MongoDBDeviceRegister'
};

const attributeList = [
'id',
'type',
'name',
'service',
'subservice',
'lazy',
'commands',
'staticAttributes',
'active',
'registrationId',
'internalId',
'internalAttributes',
'resource',
'apikey',
'protocol',
'endpoint',
'transport',
'polling',
'timestamp',
'autoprovision',
'explicitAttrs',
'expressionLanguage'
];

/**
* Generates a handler for the save device operations. The handler will take the customary error and the saved device
Expand All @@ -52,20 +79,24 @@ function saveDeviceHandler(callback) {
};
}

/**
* Empties the memory cache
*/
function clearCache(){
memoryCache.reset();
}

/**
* Create a new register for a device. The device object should contain the id, type and registrationId
*
* @param {Object} newDevice Device object to be stored
*/
function storeDevice(newDevice, callback) {
var deviceObj = new Device.model(),
attributeList = ['id', 'type', 'name', 'service', 'subservice', 'lazy', 'commands', 'staticAttributes',
'active', 'registrationId', 'internalId', 'internalAttributes', 'resource', 'apikey', 'protocol',
'endpoint', 'transport', 'polling', 'timestamp', 'autoprovision', 'explicitAttrs', 'expressionLanguage'];
const deviceObj = new Device.model();

for (var i = 0; i < attributeList.length; i++) {
deviceObj[attributeList[i]] = newDevice[attributeList[i]];
}
attributeList.forEach((key) => {
deviceObj[key] = newDevice[key];
});

// Ensure protocol is in newDevice
if ( !newDevice.protocol && config.getConfig().iotManager && config.getConfig().iotManager.protocol) {
Expand Down Expand Up @@ -99,7 +130,7 @@ function storeDevice(newDevice, callback) {
* @param {String} subservice Subservice inside the service for the removed device.
*/
function removeDevice(id, service, subservice, callback) {
var condition = {
const condition = {
id: id,
service: service,
subservice: subservice
Expand All @@ -114,7 +145,7 @@ function removeDevice(id, service, subservice, callback) {
callback(new errors.InternalDbError(error));
} else {
logger.debug(context, 'Device [%s] successfully removed.', id);

clearCache();
callback(null);
}
});
Expand All @@ -130,8 +161,8 @@ function removeDevice(id, service, subservice, callback) {
* @param {Number} offset Number of entries to skip for pagination.
*/
function listDevices(type, service, subservice, limit, offset, callback) {
var condition = {},
query;
const condition = {};
let query;

if (type) {
condition.type = type;
Expand Down Expand Up @@ -174,32 +205,36 @@ function listDevices(type, service, subservice, limit, offset, callback) {
* @param {String} subservice Division inside the service (optional).
*/
function getDeviceById(id, service, subservice, callback) {
var query,
queryParams = {
id: id,
service: service,
subservice: subservice
};
let query;
const queryParams = {
id: id,
service: service,
subservice: subservice
};
context = fillService(context, queryParams);
logger.debug(context, 'Looking for device with id [%s].', id);

query = Device.model.findOne(queryParams);
query.select({__v: 0});
memoryCache.wrap(JSON.stringify(queryParams), function (cacheCallback) {
query = Device.model.findOne(queryParams);
query.select({__v: 0});

query.exec(function handleGet(error, data) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
query.exec(function handleGet(error, data) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);

callback(new errors.InternalDbError(error));
} else if (data) {
context = fillService(context, data);
logger.debug(context, 'Device data found: %j', data);
callback(null, data);
} else {
logger.debug(context, 'Device [%s] not found.', id);
cacheCallback(new errors.InternalDbError(error));
} else if (data) {
context = fillService(context, data);
logger.debug(context, 'Device data found: %j', data);
cacheCallback(null, data);
} else {
logger.debug(context, 'Device [%s] not found.', id);

callback(new errors.DeviceNotFound(id));
}
cacheCallback(new errors.DeviceNotFound(id));
}
});
}, (error, data) => {
callback(error, data);
});
}

Expand All @@ -222,7 +257,7 @@ function getDevice(id, service, subservice, callback) {
}

function getByName(name, service, servicepath, callback) {
var query;
let query;
context = fillService(context, { service: service, subservice: servicepath});
logger.debug(context, 'Looking for device with name [%s].', name);

Expand Down Expand Up @@ -250,8 +285,9 @@ function getByName(name, service, servicepath, callback) {
}

/**
* Updates the given device into the database. Only the following attributes: lazy, active and internalId will be
* updated.
* Updates the given device into the database. Only the following attributes:
* lazy, active and internalId, commanda, endpoint, name, type, explicitAttrs
* will be updated.
*
* @param {Object} device Device object with the new values to write.
*/
Expand All @@ -260,6 +296,7 @@ function update(device, callback) {
if (error) {
callback(error);
} else {
clearCache();
data.lazy = device.lazy;
data.active = device.active;
data.internalId = device.internalId;
Expand All @@ -269,7 +306,6 @@ function update(device, callback) {
data.name = device.name;
data.type = device.type;
data.explicitAttrs = device.explicitAttrs;

data.save(saveDeviceHandler(callback));
}
});
Expand All @@ -291,8 +327,8 @@ function itemToObject(i) {
}

function getDevicesByAttribute(name, value, service, subservice, callback) {
var query,
filter = {};
let query;
const filter = {};

if (service) {
filter.service = service;
Expand Down Expand Up @@ -324,6 +360,7 @@ function getDevicesByAttribute(name, value, service, subservice, callback) {
});
}


exports.getDevicesByAttribute = alarmsInt(constants.MONGO_ALARM, getDevicesByAttribute);
exports.store = alarmsInt(constants.MONGO_ALARM, storeDevice);
exports.update = alarmsInt(constants.MONGO_ALARM, update);
Expand All @@ -333,3 +370,4 @@ exports.get = alarmsInt(constants.MONGO_ALARM, getDevice);
exports.getSilently = getDevice;
exports.getByName = alarmsInt(constants.MONGO_ALARM, getByName);
exports.clear = alarmsInt(constants.MONGO_ALARM, clear);
exports.clearCache = clearCache;
Loading