All files / lib swsAPIStats.js

78.33% Statements 206/263
54.27% Branches 89/164
77.78% Functions 14/18
81.01% Lines 192/237

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508              1x 1x 1x 1x 1x 1x 1x 1x 1x                   1x     1x       1x       1x       1x       1x     1x 1x 1x     1x     1x       1x       1x                                                     1x 1x     1x     1x 1x         1x 1x         1x 14x 14x 14x       14x       1x     1x 1x   1x 1x 1x     1x 1x 1x   1x 1x   1x 1x   1x   1x   1x     1x   14x     14x     14x 14x     14x     14x 4x 4x 4x       14x   14x 14x 98x 98x   20x 20x   20x 20x 20x 20x 20x 20x 20x     20x     20x 20x     20x     20x     20x   20x               1x   20x     20x                 20x 20x 20x 25x 25x           1x   25x 25x   25x 25x   25x 25x     25x 550x 130x         25x 138x 1x         25x 25x       1x 43x 43x           43x       1x 22x 22x 22x       1x   25x 350x 500x           1x                           1x   2x   2x     2x 2x       2x 2x 2x 2x     2x 1x 1x 1x     1x 14x 4x 4x                     2x   1x   1x   1x 1x 1x       1x 1x 1x     1x                           1x   1x   1x   1x   1x   1x 1x   1x 1x           1x   1x 1x   1x                   1x   1x   1x   1x   1x   1x   1x   1x 1x               1x     1x       1x       1x     1x 1x 1x 1x           1x   1x 1x     1x             1x         1x     1x     1x       1x       1x 1x 1x 1x     1x   1x 1x 1x       1x  
/**
 * Created by sv2 on 2/18/17.
 * API Statistics
 */
 
'use strict';
 
const util = require('util');
const { pathToRegexp } = require('path-to-regexp');
const debug = require('debug')('sws:apistats');
const promClient = require("prom-client");
const swsSettings = require('./swssettings');
const swsMetrics = require('./swsmetrics');
const swsUtil = require('./swsUtil');
const swsReqResStats = require('./swsReqResStats');
const swsBucketStats = require('./swsBucketStats');
 
 
// API Statistics
// Stores Definition of API based on Swagger Spec
// Stores API Statistics, for both Swagger spec-based API, as well as for detected Express APIs (route.path)
// Stores Detailed Stats for each API request
function swsAPIStats() {
 
    // Options
    this.options = null;
 
    // API Base path per swagger spec
    this.basePath = '/';
 
    // Array of possible API path matches, populated based on Swagger spec
    // Contains regex to match URI to Swagger path
    this.apiMatchIndex = {};
 
    // API definition - entry per API request from swagger spec
    // Stores attributes of known Swagger APIs - description, summary, tags, parameters
    this.apidefs = {};
 
    // API statistics - entry per API request from swagger
    // Paths not covered by swagger will be added on demand as used
    this.apistats = {};
 
    // Detailed API stats
    // TODO Consider: individual timelines (?), parameters (query/path?)
    this.apidetails = {};
 
    // Buckets for histograms, with default bucket values
    this.durationBuckets = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
    this.requestSizeBuckets = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
    this.responseSizeBuckets = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
 
    // Prometheus metrics in prom-client
    this.promClientMetrics = {};
}
 
swsAPIStats.prototype.getAPIDefs = function() {
    return this.apidefs;
};
 
swsAPIStats.prototype.getAPIStats = function() {
    return this.apistats;
};
 
swsAPIStats.prototype.getAPIOperationStats = function(path,method) {
 
    if( (typeof path === 'undefined') || !path || (path==='')) return {};
    if( (typeof method === 'undefined') || !method || (method==='')) return {};
 
    var res = {};
    res[path] = {};
    res[path][method] = {};
 
    // api op defs
    if( (path in this.apidefs) && (method in this.apidefs[path])) {
        res[path][method].defs = this.apidefs[path][method];
    }
 
    // api op stats
    if( (path in this.apistats) && (method in this.apistats[path])) {
        res[path][method].stats = this.apistats[path][method];
    }
 
    // api op details
    if( (path in this.apidetails) && (method in this.apidetails[path])) {
        res[path][method].details = this.apidetails[path][method];
    }
 
    return res;
};
 
swsAPIStats.prototype.initBasePath = function(swaggerSpec,swsOptions) {
    Iif(('basePath' in swsOptions) && (swsOptions.basePath!=='')){
        this.basePath = swsOptions.basePath;
    }else{
        Iif( swaggerSpec.openapi && swaggerSpec.openapi.startsWith('3') ){
            this.basePath = '/';
        }else{
            this.basePath = swaggerSpec.basePath ? swaggerSpec.basePath : '/';
            Iif (this.basePath.charAt(0) !== '/') {
                this.basePath = '/' + this.basePath;
            }
        }
    }
    Eif (this.basePath.charAt(this.basePath.length - 1) !== '/') {
        this.basePath = this.basePath + '/';
    }
};
 
// Get full swagger Path
swsAPIStats.prototype.getFullPath = function (path) {
    var fullPath = this.basePath;
    Eif (path.charAt(0) === '/') {
        fullPath += path.substring(1);
    }else{
        fullPath += path;
    }
    return fullPath;
};
 
 
swsAPIStats.prototype.initialize = function(swsOptions) {
 
    // TODO remove
    Iif(!swsOptions) return;
    this.options = swsOptions;
 
    this.durationBuckets = swsSettings.durationBuckets;
    this.requestSizeBuckets = swsSettings.requestSizeBuckets;
    this.responseSizeBuckets = swsSettings.responseSizeBuckets;
 
    // Update buckets to reflect passed options
    swsMetrics.apiMetricsDefs.api_request_duration_milliseconds.buckets = this.durationBuckets;
    swsMetrics.apiMetricsDefs.api_request_size_bytes.buckets = this.requestSizeBuckets;
    swsMetrics.apiMetricsDefs.api_response_size_bytes.buckets = this.responseSizeBuckets;
 
    swsMetrics.clearPrometheusMetrics(this.promClientMetrics);
    this.promClientMetrics = swsMetrics.getPrometheusMetrics(swsSettings.metricsPrefix,swsMetrics.apiMetricsDefs);
 
    Iif(!('swaggerSpec' in swsOptions)) return;
    Iif(swsOptions.swaggerSpec === null) return;
 
    var swaggerSpec = swsOptions.swaggerSpec;
 
    this.initBasePath(swaggerSpec,swsOptions);
 
    Iif(!swaggerSpec.paths) return;
 
    // Enumerate all paths entries
    for(var path in swaggerSpec.paths ){
 
        var pathDef = swaggerSpec.paths[path];
 
        // Create full path
        var fullPath = this.getFullPath(path);
 
        // by default, regex is null
        var keys = [];
        var re = null;
 
        // Convert to express path
        var fullExpressPath = fullPath;
 
        // Create regex if we have path parameters
        if( fullExpressPath.indexOf('{') !== -1 ) {
            fullExpressPath = fullExpressPath.replace(/\{/g, ':');
            fullExpressPath = fullExpressPath.replace(/\}/g, '');
            re = pathToRegexp(fullExpressPath, keys);
        }
 
        // Add to API Match Index, leveraging express style matching
        this.apiMatchIndex[fullPath] = { re: re, keys: keys, expressPath: fullExpressPath, methods: {}};
 
        var operations = ['get','put','post','delete','options','head','patch'];
        for(var i=0;i<operations.length;i++){
            var op = operations[i];
            if(op in pathDef){
 
                var opDef = pathDef[op];
                var opMethod = op.toUpperCase();
 
                var apiOpDef = {};   // API Operation definition
                apiOpDef.swagger = true; // by definition
                apiOpDef.deprecated = ('deprecated' in opDef) ? opDef.deprecated : false;
                Eif( 'description' in opDef ) apiOpDef.description = opDef.description;
                Eif( 'operationId' in opDef ) apiOpDef.operationId = opDef.operationId;
                Eif( 'summary' in opDef ) apiOpDef.summary = opDef.summary;
                Eif( 'tags' in opDef ) apiOpDef.tags = opDef.tags;
 
                // Store in match index
                this.apiMatchIndex[fullPath].methods[opMethod] = apiOpDef;
 
                // Store in API Operation definitions. Stored separately so only definition can be retrieved
                if(!(fullPath in this.apidefs) ) this.apidefs[fullPath] = {};
                this.apidefs[fullPath][opMethod] = apiOpDef;
 
                // Create Stats for this API Operation; stats stored separately so only stats can be retrieved
                this.getAPIOpStats(fullPath,opMethod);
 
                // Create entry in apidetails
                this.getApiOpDetails(fullPath,opMethod);
 
                // Process parameters for this op
                this.processParameters(swaggerSpec, pathDef, opDef, fullPath, opMethod);
 
                debug('SWS:Initialize API:added %s %s (%s)', op, fullPath, fullExpressPath);
            }
        }
    }
};
 
// Process parameterss for given operation
// Take into account parameters defined as common for path (from pathDef)
swsAPIStats.prototype.processParameters = function(swaggerSpec, pathDef, opDef, fullPath, opMethod ) {
 
    var apidetailsEntry = this.getApiOpDetails(fullPath,opMethod);
 
    // Params from path
    Iif(('parameters' in pathDef) && (pathDef.parameters instanceof Array)) {
        var pathParams = pathDef.parameters;
        for(var j=0;j<pathParams.length;j++){
            var param = pathParams[j];
            this.processSingleParameter(apidetailsEntry,param);
        }
    }
 
    // Params from Op, overriding parameters from path
    Eif(('parameters' in opDef) && (opDef.parameters instanceof Array)){
        var opParams = opDef.parameters;
        for(var k=0;k<opParams.length;k++){
            var param = opParams[k];
            this.processSingleParameter(apidetailsEntry,param);
        }
    }
 
};
 
swsAPIStats.prototype.processSingleParameter = function(apidetailsEntry,param) {
 
    if( !('parameters' in apidetailsEntry) ) apidetailsEntry.parameters = {};
    var params = apidetailsEntry.parameters;
 
    var pname = "name" in param ? param.name : null;
    Iif( pname === null ) return;
 
    Eif(!(pname in params)) params[pname] = { name: pname };
    var paramEntry = params[pname];
 
    // Process all supported parameter properties
    for( var supportedProp in swsUtil.swsParameterProperties ){
        if(supportedProp in param){
            paramEntry[supportedProp] = param[supportedProp];
        }
    }
 
    // Process all vendor extensions
    for( var paramProp in param ){
        if( paramProp.startsWith('x-') ){
            paramEntry[paramProp] = param[paramProp];
        }
    }
 
    // Add standard stats
    paramEntry.hits = 0;
    paramEntry.misses = 0;
};
 
// Get or create API Operation Details
swsAPIStats.prototype.getApiOpDetails = function(path,method) {
    if(!(path in this.apidetails) ) this.apidetails[path] = {};
    if(!(method in this.apidetails[path]) ) this.apidetails[path][method] = {
        duration: new swsBucketStats(this.durationBuckets),       // Request duration histogram
        req_size: new swsBucketStats(this.requestSizeBuckets),    // Request size histogram
        res_size: new swsBucketStats(this.responseSizeBuckets),   // Response size histogram
        code: {'200':{count:0}}                                 // Counts by response code
    };
    return this.apidetails[path][method];
};
 
// Get or create API Operation Stats
swsAPIStats.prototype.getAPIOpStats = function( path, method ) {
    if( !(path in this.apistats)) this.apistats[path] = {};
    if( !(method in this.apistats[path])) this.apistats[path][method] = new swsReqResStats(this.options.apdexThreshold);
    return this.apistats[path][method];
};
 
// Update and stats per tick
swsAPIStats.prototype.tick = function (ts,totalElapsedSec) {
    // Update Rates in apistats
    for( var path in this.apistats ) {
        for( var method in this.apistats[path] ) {
            this.apistats[path][method].updateRates(totalElapsedSec);
        }
    }
};
 
// Extract path parameter values based on successful path match results
swsAPIStats.prototype.extractPathParams = function (matchResult,keys) {
    var pathParams = {};
    for(var i=0;i<keys.length;i++){
        if('name' in keys[i] ) {
            var vidx = i + 1; // first element in match result is URI
            if( vidx < matchResult.length ) {
                pathParams[keys[i].name] = swsUtil.swsStringValue(matchResult[vidx]);
            }
        }
    }
    return pathParams;
};
 
// Try to match request to API to known API definition
swsAPIStats.prototype.matchRequest = function (req) {
 
    var url = req.sws.originalUrl;
 
    req.sws.match = false;  // No match by default
 
    // Strip query string parameters
    var qidx = url.indexOf('?');
    Iif(qidx!=-1) {
        url = url.substring(0,qidx);
    }
 
    var matchEntry = null;
    var apiPath = null;
    var apiPathParams = null;
    var apiInfo = null;
 
    // First check if we can find exact match in apiMatchIndex
    if( url in this.apiMatchIndex ){
        matchEntry = this.apiMatchIndex[url];
        apiPath = url;
        debug('SWS:MATCH: %s exact match', url);
    }else{
        // if not, search by regex matching
        for(var swPath in this.apiMatchIndex) {
            if( this.apiMatchIndex[swPath].re !== null) {
                var matchResult = this.apiMatchIndex[swPath].re.exec(url);
                Iif (matchResult && (matchResult instanceof Array)) {
                    matchEntry = this.apiMatchIndex[swPath];
                    apiPath = swPath;
                    apiPathParams = this.extractPathParams(matchResult, this.apiMatchIndex[swPath].keys);
                    debug('SWS:MATCH: %s matched to %s', url, swPath);
                    break; // Done
                }
            }
        }
    }
 
    if( matchEntry ) {
 
        Eif (req.method in matchEntry.methods) {
 
            apiInfo = matchEntry.methods[req.method];
 
            req.sws.match = true;       // Match is found
            req.sws.api_path = apiPath;
            req.sws.swagger = true;
 
            // When matched, attach only subset of information to request,
            // so we don't overload reqresinfo with repeated description, etc
            Eif ('deprecated' in apiInfo) req.sws.deprecated = apiInfo.deprecated;
            Eif ('operationId' in apiInfo) req.sws.operationId = apiInfo.operationId;
            Eif ('tags' in apiInfo) req.sws.tags = apiInfo.tags;
 
            // Store path parameters from match result
            Iif (apiPathParams) req.sws.path_params = apiPathParams;
 
        }
    }
 
 
};
 
 
// Count Api Operation Parameters Statistics
// Only count hits and misses
// Hit: parameter present
// Miss: mandatory parameter is missing
// Only supported path and query parameters
swsAPIStats.prototype.countParametersStats = function (path, method, req, res) {
 
    Iif(!('swagger' in req.sws) || !req.sws.swagger ) return; // Only counting for swagger-defined API Ops
 
    var apiOpDetails = this.getApiOpDetails(path, method);
 
    Iif( !('parameters' in apiOpDetails) ) return; // Only counting if parameters spec is there
 
    for( var pname in apiOpDetails.parameters ){
 
        var param = apiOpDetails.parameters[pname];
        var isRrequired = 'required' in param ? param.required : false;
 
        Eif( 'in' in param ){
            switch(param.in){
                case "path":
                    // Path param is always there, or request will not be matched
                    param.hits++;
                    break;
                case "query":
                    Iif( ('query' in req.sws) && (pname in req.sws.query) ){
                        param.hits++;
                    }else Eif(isRrequired){
                        param.misses++;
                    }
                    break;
            }
        }
    }
 
};
 
 
// Get Api Operation Parameter Values per specification
// Only supported path and query parameters
swsAPIStats.prototype.getApiOpParameterValues = function (path, method, req, res) {
 
    Iif(!('swagger' in req.sws) || !req.sws.swagger ) return null; // Only for swagger-defined API Ops
 
    var apiOpDetails = this.getApiOpDetails(path, method);
 
    Iif( !('parameters' in apiOpDetails) ) return null; // Only if parameters spec is there
 
    var paramValues = {};
 
    for( var pname in apiOpDetails.parameters ){
 
        var param = apiOpDetails.parameters[pname];
 
        Eif( 'in' in param ){
            switch(param.in){
                case "path":
                    if(('path_params' in req.sws) && (pname in req.sws.path_params)) {
                        paramValues[pname] = swsUtil.swsStringValue(req.sws.path_params[pname]);
                    }
                    break;
 
                case "query":
                    Iif(('query' in req.sws) && (pname in req.sws.query)) {
                        paramValues[pname] = swsUtil.swsStringValue(req.sws.query[pname]);
                    }
                    break;
            }
        }
    }
    return paramValues;
};
 
// Count request
swsAPIStats.prototype.countRequest = function (req, res) {
 
    // Count request if it was matched to API Operation
    Eif(('match' in req.sws) && req.sws.match ){
        var apiOpStats = this.getAPIOpStats(req.sws.api_path,req.method);
        apiOpStats.countRequest(req.sws.req_clength);
        this.countParametersStats(req.sws.api_path,req.method, req, res );
    }
 
};
 
// Count finished response
swsAPIStats.prototype.countResponse = function (res) {
 
    var req = res._swsReq;
    var codeclass = swsUtil.getStatusCodeClass(res.statusCode);
 
    // Only intersted in updating stats here
    var apiOpStats = this.getAPIOpStats(req.sws.api_path,req.method);
 
    // If request was not matched to API operation,
    // do both count request and count response here,
    // as only at this time we know path so can map request / response to API entry
    // This allows supporting API statistics on non-swagger express route APIs, like /path/:param
    // as express router would attach route.path to request
    Iif(!('match' in req.sws) || !req.sws.match) {
        apiOpStats.countRequest(req.sws.req_clength);
    }
 
    // In all cases, count response here
    apiOpStats.countResponse(res.statusCode,codeclass,req.sws.duration,req.sws.res_clength);
 
    // Count metrics
    var apiOpDetails = this.getApiOpDetails(req.sws.api_path,req.method);
 
    // Metrics by response code
    Iif( !('code' in apiOpDetails) ) {
        apiOpDetails.code = {};
    }
 
    Iif(!(res.statusCode in apiOpDetails.code)){
        apiOpDetails.code[res.statusCode] = { count:0 };
    }
 
    apiOpDetails.code[res.statusCode].count++;
    apiOpDetails.duration.countValue(req.sws.duration);
    apiOpDetails.req_size.countValue(req.sws.req_clength);
    apiOpDetails.res_size.countValue(req.sws.res_clength);
 
    // update Prometheus metrics
    this.promClientMetrics.api_request_total.labels(req.method,req.sws.api_path,res.statusCode).inc();
 
    this.promClientMetrics.api_request_duration_milliseconds.labels(req.method,req.sws.api_path,res.statusCode).observe(req.sws.duration);
    this.promClientMetrics.api_request_size_bytes.labels(req.method,req.sws.api_path,res.statusCode).observe(req.sws.req_clength);
    this.promClientMetrics.api_response_size_bytes.labels(req.method,req.sws.api_path,res.statusCode).observe(req.sws.res_clength);
 
};
 
module.exports = swsAPIStats;