Code coverage report for lib/services/client/read.js

Statements: 93.28% (111 / 119)      Branches: 79.63% (43 / 54)      Functions: 100% (24 / 24)      Lines: 93.28% (111 / 119)     

All files » lib/services/client/ » read.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330                                              1   1                           1 26 20       20 6 6                             1 11 7             7 7           4                     1 26 26   26 11 11   15 15     26 15 15   11                             1 10           29 21 21 21 21         1 76 76 67   9         10 10       10 1 1 76       9       10                         1 11 10 10     11     1 18     1 3 3     3   3 1     3         1 3       3     3 1   2     2 1     2 2     2         1 3       3     3     3     3 1     3 2 2       3                       1 26 26     26 9 3 6 3   3     17                   1 1 1 1     1 1     1 1           1     1 1     1 8     8       8     1 1 1 1
/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-lwm2m-lib
 *
 * iotagent-lwm2m-lib is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-lwm2m-lib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-lwm2m-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
 
'use strict';
 
var async = require('async'),
    apply = async.apply,
    objectRegistry = require('./objectRegistry'),
    errors = require('../../errors'),
    logger = require('logops'),
    _ = require('underscore'),
    observers = {};
 
/**
 * Extract Object type and id from the request URI, returning it using the callback.
 *
 * @param {Object} req          Arriving COAP Request to be handled.
 * @param {Object} res          Outgoing COAP Response.
 */
function extractUriInfo(req, res, callback) {
    if (req.urlObj.pathname.match(/\/\d+\/\d+\/\d+/)) {
        var resourceIndex = req.urlObj.pathname.lastIndexOf('/'),
            resourceId = req.urlObj.pathname.substring(resourceIndex + 1),
            objectUri = req.urlObj.pathname.substring(0, resourceIndex);
 
        callback(null, objectUri, resourceId);
    } else Eif (req.urlObj.pathname.match(/\/\d+(\/\d+)?/)) {
        callback(null, req.urlObj.pathname, null);
    } else {
        callback(new errors.WrongObjectUri(req.urlObj.pathname));
    }
}
 
/**
 * Invoke the user handler for this operation, with all the information from the query parameters as its arguments.
 * This method handling gives the client an opportunity to change or overwrite the values before returning them to
 * the client. The handler must call the callback with the overwritten value it wants to return. If the callback is
 * called without parameters, the original value is returned instead.
 *
 * @param {Object} queryParams      Object containing all the query parameters.
 * @param {Function} handler        User handler to be invoked.
 */
function applyHandler(resourceId, handler, storedObject, callback) {
    if (storedObject.attributes[resourceId]) {
        handler(
            storedObject.objectType,
            storedObject.objectId,
            resourceId,
            storedObject.attributes[resourceId],
 
            function handleReadOverwrite(error, result) {
                Eif (result) {
                    callback(error, result);
                } else {
                    callback(error, storedObject.attributes[resourceId]);
                }
            });
    } else {
        callback(new errors.ResourceNotFound(storedObject.objectType, storedObject.objectId, resourceId));
    }
}
 
/**
 * Generates the end of request handler that will generate the final response to the COAP Client.
 *
 * @param {Object} req          Arriving COAP Request to be handled.
 * @param {Object} res          Outgoing COAP Response.
 * @returns {Function}          Request handler, receiving an optional error and the read operation result.
 */
function endRead(req, res) {
    return function (error, result) {
        var body;
 
        if (error) {
            res.code = error.code;
            body = '';
        } else {
            res.code = '2.05';
            body = result.toString();
        }
 
        if (_.some(req.options, _.matches({name: 'Observe'}))) {
            res.setOption('Observe', 1);
            res.write(body);
        } else {
            res.end(body);
        }
    };
}
 
/**
 * Constructs the resource observer. The observer listens in the object registry bus for attribute modifications,
 * sending a new information update to the server each time the selected attribute changes its value.
 *
 * @param {Object} stream           Stream where the new data will be written to the server.
 * @param {Number} resourceId       Resource to read from.
 * @param {Object} storedObject     Object instance to observe.
 * @returns {{uri: (object.objectUri|*|string), stream: *, observation: number}}
 * @constructor
 */
function ResourceObserver(stream, resourceId, storedObject) {
    var data = {
        id: storedObject.objectUri + '/' + resourceId,
        uri: storedObject.objectUri,
        stream: stream,
        observation: 1,
        listener: function newModification(method, id, value) {
            if (method === 'setResource' && resourceId === id.toString()) {
                stream.setOption('Observe', data.observation);
                stream.write(value.toString());
                data.observation++;
                data.lastObservation = Date.now();
            }
        }
    };
 
    function getLastMeasure() {
        objectRegistry.get(storedObject.objectUri, function (error, obj) {
            if (error) {
                logger.error('Error retrieving the last resource value');
            } else {
                data.listener('setResource', resourceId, obj.attributes[resourceId]);
            }
        });
    }
 
    objectRegistry.getAttributes(storedObject.objectUri + '/' + resourceId, function(error, attributes) {
        Iif (error) {
            logger.error('Couldn\'t find attributes for the [%s] resource URI. Falling back to value changed');
        }
 
        if (attributes) {
            Eif (attributes.pmax) {
                data.scheduler = setInterval(function handleMaxPeriod() {
                    getLastMeasure(storedObject.objectUri, resourceId);
                }, attributes.pmax);
            }
        } else {
            objectRegistry.bus.on(storedObject.objectUri, data.listener);
        }
    });
 
    return data;
}
 
/**
 * If the Read request comes with the observation option, apart from resolving the information request, a subscription
 * has to be created, so every time the selected resource changes in value (or in a timely basis, depending on the
 * configuration), the server is updated on the new value.
 *
 * @param {Object} req              Arriving COAP Request to be handled.
 * @param {Object} res              Outgoing COAP Response.
 * @param {Number} resourceId       ID of the resource to be observed.
 * @param {Object} storedObject     Object instance to be read.
 */
function createObservers(req, res, resourceId, storedObject, callback) {
    if (_.some(req.options, _.matches({name: 'Observe'}))) {
        var observer = new ResourceObserver(res, resourceId, storedObject);
        observers[observer.id] = observer;
    }
 
    callback(null, storedObject);
}
 
function addAttribute(previous, value) {
    return previous + ';' + value[0] + '=' + value[1];
}
 
function discoverResourceAttributes(objectUri, resourceId, callback) {
    objectRegistry.getAttributes(objectUri + '/' + resourceId, function (error, attributes) {
        Iif (error) {
            callback(error);
        } else {
            var payload = '<' + objectUri + '/' + resourceId + '>';
 
            if (attributes) {
                payload = _.pairs(attributes).reduce(addAttribute, payload);
            }
 
            callback(null, payload);
        }
    });
}
 
function discoverObjectResources(objectUri, callback) {
    async.series([
        apply(objectRegistry.get, objectUri),
        apply(objectRegistry.getAttributes, objectUri)
    ], function handleGetObject(error, results) {
        var obj = results[0],
            attributes = results[1];
 
        if (error) {
            callback(error);
        } else {
            var payload = '<' + objectUri + '>',
                resources = _.keys(obj.attributes);
 
            if (attributes) {
                payload += _.pairs(attributes).reduce(addAttribute, '');
            }
 
            for (var i = 0; i < resources.length; i++) {
                payload += ',<' + objectUri + '/' + resources[i] + '>';
            }
 
            callback(null, payload);
        }
    });
}
 
function discoverObjectTypeInstances(objectTypeUri, callback) {
    async.series([
        objectRegistry.list,
        apply(objectRegistry.getAttributes, objectTypeUri)
    ], function handleListResult(error, results) {
        var objList = results[0],
            attributes = results[1];
 
        Iif (error) {
            callback(error);
        } else {
            var payload = '<' + objectTypeUri + '>',
                objectType = objectTypeUri.substring(1);
 
            if (attributes) {
                payload += _.pairs(attributes).reduce(addAttribute, '');
            }
 
            for (var i = 0; i < objList.length; i++) {
                Eif (objList[i].objectType === objectType) {
                    payload += ',<' + objList[i].objectUri + '>';
                }
            }
 
            callback(null, payload);
        }
    });
}
 
/**
 * Handle the read operation.
 *
 * @param {Object} req          Arriving COAP Request to be handled.
 * @param {Object} res          Outgoing COAP Response.
 * @param {Function} handler    User handler to be executed if everything goes ok.
 */
function handleRead(req, res, handler) {
    extractUriInfo(req, res, function (error, objectUri, resourceId) {
        Iif (error) {
            endRead(req, res)(error);
        } else {
            if (_.some(req.options, _.matches({name: 'Accept', value: 'application/link-format'}))) {
                if (resourceId) {
                    discoverResourceAttributes(objectUri, resourceId, endRead(req, res));
                } else if (objectUri.match(/\/\d+\/\d+/)) {
                    discoverObjectResources(objectUri, endRead(req, res));
                } else {
                    discoverObjectTypeInstances(objectUri, endRead(req, res));
                }
            } else {
                async.waterfall([
                    apply(objectRegistry.get, objectUri),
                    apply(createObservers, req, res, resourceId),
                    apply(applyHandler, resourceId, handler)
                ], endRead(req, res));
            }
        }
    });
}
 
function cancelObservation(objUri, resourceId, callback) {
    Eif (observers[objUri + '/' + resourceId]) {
        Eif (observers[objUri + '/' + resourceId].stream) {
            observers[objUri + '/' + resourceId].stream.end();
        }
 
        Eif (observers[objUri + '/' + resourceId]) {
            clearInterval(observers[objUri + '/' + resourceId].scheduler);
        }
 
        objectRegistry.bus.removeListener(objUri, observers[objUri + '/' + resourceId].listener);
        delete observers[objUri + '/' + resourceId];
    } else {
        logger.error('Tried to remove an unexistant observation on obj URI [%s] and resourceId [%s]',
            objUri, resourceId);
    }
 
    callback(null);
}
 
function listObservers(callback) {
    callback(null, _.values(observers));
}
 
function cancelAllObservers(callback) {
    var observers = _.values(observers),
        cancellations = [];
 
    for (var i = 0; i < observers.length; i++) {
        cancellations.push(apply(cancelObservation, observers[i].objUri, observers[i].resourceId));
    }
 
    async.series(cancellations, callback);
}
 
exports.handle = handleRead;
exports.cancel = cancelObservation;
exports.list = listObservers;
exports.cancelAll = cancelAllObservers;