Code coverage report for lib\common\streams\batchoperation.js

Statements: 91.41% (181 / 198)      Branches: 72.94% (62 / 85)      Functions: 95.83% (23 / 24)      Lines: 92.82% (181 / 195)      Ignored: none     

All files » lib/common/streams/ » batchoperation.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 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                                1 1 1 1 1   1 1 1   1 1   1 1 1 1                     1 48       48 48 48 48 48 48 48   48 48 48 48 48     48     48     48     48           1                 1         1 48 48 48 48             1         619 619     619               1                 1 81           1 302 302 302 302 302   302 302           1 48 48 48           1 15           1 15 15 15             1   96     96             1 302 302   302     302     302             1 302 302 302 302 1 1 1   301 301     302 302 240 240 62 38 38 38             24     302 302 302             1 379 379 254     379   302 302     302       302 302 302 302   302 278     302 77 15     62               1 110 48 48 48 48   62           1 317 317 64 64   253               1 379 379 317 317   293 293 292   1         24 23       63               1 256           1 46 46 46     46 46 46 46       46   46 46 46     46 46 46 46 46       46 46 46         1         1 256 256 256 256 256 256         256 256 256 256 256 256 256     256 256 256   256       1   1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var util = require('util');
var http = require('http');
var https = require('https');
var EventEmitter = require('events').EventEmitter;
var os = require('os');
 
var azureutil = require('../util/util');
var Logger = require('../diagnostics/logger');
var Constants = require('../util/constants');
 
var DEFAULT_OPERATION_MEMORY_USAGE = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
var DEFAULT_GLOBAL_CONCURRENCY = 5; //Default http connection limitation for nodejs
 
var SystemTotalMemory = os.totalmem();
var CriticalFreeMemory = 0.1 * SystemTotalMemory;
var nodeVersion = azureutil.getNodeVersion();
var enableReuseSocket = nodeVersion.major >= 0 && nodeVersion.minor >= 10;
 
/**
* Concurrently execute batch operations and call operation callback randomly or in sequence.
* Random mode is for uploading.
*   1. Fire user callback when the operation is done.
* Sequence mode is for downloading.
*   1. Fire user callback when the operation is done and all previous operations and callback has finished.
*   2. BatchOperation guarantees the user callback is fired one by one.
*   3. The next user callback can't be fired until the current one is completed.
*/
function BatchOperation(name, options) {
  Iif (!options) {
    options = {};
  }
 
  this.name = name;
  this.logger = options.logger || new Logger(Logger.LogLevels.INFO);
  this.operationMemoryUsage = options.operationMemoryUsage || DEFAULT_OPERATION_MEMORY_USAGE;
  this.callbackInOrder = options.callbackInOrder === true;
  this.callInOrder = options.callInOrder === true;
  this._currentOperationId = this.callbackInOrder ? 1 : -1;
  this.concurrency = DEFAULT_GLOBAL_CONCURRENCY;
 
  this._emitter = new EventEmitter();
  this._enableComplete = false;
  this._ended = false;
  this._error = null;
  this._paused = false;
 
  //Total operations count(queued and active and connected)
  this._totalOperation = 0;
 
  //Action operations count(The operations which are connecting to remote or executing callback or queued for executing)
  this._activeOperation = 0;
 
  //Queued operations count(The operations which are connecting to remote or queued for executing)
  this._queuedOperation = 0;
 
  //finished operation should be removed from this array
  this._operations = [];
}
 
/**
* Operation state
*/
var OperationState = {
  INITED : 'inited',
  QUEUED : 'queued',
  RUNNING : 'running',
  COMPLETE : 'complete',
  CALLBACK : 'callback',
  ERROR : 'error'
};
 
BatchOperation.OperationState = OperationState;
 
/**
* Set batch operation concurrency
*/
BatchOperation.prototype.setConcurrency = function(concurrency) {
  Eif (concurrency) {
    this.concurrency = concurrency;
    http.globalAgent.maxSockets = this.concurrency;
    https.globalAgent.maxSockets = this.concurrency;
  }
};
 
/**
* Is the workload heavy and It can be used to determine whether we could queue operations
*/
BatchOperation.prototype.IsWorkloadHeavy = function() {
  //Only support one batch operation for now.
  //In order to work with the multiple batch operation, we can use global operation track objects
  //BatchOperation acquire a bunch of operation ids from global and allocated ids to RestOperation
  //RestOperation start to run in order of id
  var sharedRequest = 1;
  Iif(enableReuseSocket && !this.callInOrder) {
    sharedRequest = 5;
  }
  return this._activeOperation >= sharedRequest * this.concurrency ||
    this._isLowMemory() ||
    (this._activeOperation >= this.concurrency && this._getApproximateMemoryUsage() > 0.5 * SystemTotalMemory);
};
 
/**
* get the approximate memory usage for batch operation
*/
BatchOperation.prototype._getApproximateMemoryUsage = function() {
  var currentUsage = process.memoryUsage().rss;
  var futureUsage = this._queuedOperation * this.operationMemoryUsage;
  return currentUsage + futureUsage;
};
 
/**
* get the approximate free memory
*/
BatchOperation.prototype._isLowMemory = function() {
  return os.freemem() < CriticalFreeMemory;
};
 
/**
* Add a operation into batch operation
*/
BatchOperation.prototype.addOperation = function(operation) {
  this._operations.push(operation);
  operation.status = OperationState.QUEUED;
  operation.operationId = ++this._totalOperation;
  this._queuedOperation++;
  this.logger.debug(util.format('Add operation %d into batch operation %s. Active: %s; Queued: %s', operation.operationId, this.name, this._activeOperation, this._queuedOperation));
  //Immediately start the idle operation if workload isn't heavy
  this._runOperation(operation);
  return this.IsWorkloadHeavy();
};
 
/**
* Enable batch operation complete when there is no operation to run.
*/
BatchOperation.prototype.enableComplete = function() {
  this._enableComplete = true;
  this.logger.debug(util.format('Enable batch operation %s complete', this.name));
  this._tryEmitEndEvent();
};
 
/**
* Stop firing user call back
*/
BatchOperation.prototype.pause = function () {
  this._paused = true;
};
 
/**
* Start firing user call back
*/
BatchOperation.prototype.resume = function () {
  Eif (this._paused) {
    this._paused = false;
    this._fireOperationUserCallback();
  }
};
 
/**
* Add event listener
*/
BatchOperation.prototype.on = function(event, listener) {
  // only emit end if the batch has completed all operations
  Iif(this._ended && event === 'end') {
    listener();
  } else {
    this._emitter.on(event, listener);
  }
};
 
/**
* Run operation
*/
BatchOperation.prototype._runOperation = function (operation) {
  this.logger.debug(util.format('Operation %d start to run', operation.operationId));
  var cb = this.getBatchOperationCallback(operation);
 
  Iif(this._error) {
    cb(this._error);//Directly call the callback with previous error.
  } else {
    operation.run(cb);
  }
 
  this._activeOperation++;
};
 
/**
* Return an general operation call back.
* This callback is used to update the internal status and fire user's callback when operation is complete.
*/
BatchOperation.prototype.getBatchOperationCallback = function (operation) {
  var self = this;
  return function (error) {
    self._queuedOperation--;
    if (error) {
      operation.status = OperationState.ERROR;
      self.logger.debug(util.format('Operation %d failed. Error %s', operation.operationId, error));
      self._error = error;
    } else {
      operation.status = OperationState.CALLBACK;
      self.logger.debug(util.format('Operation %d succeed', operation.operationId));
    }
 
    operation._callbackArguments = arguments;
    if (self._paused) {
      operation.status = OperationState.CALLBACK;
      self.logger.debug(util.format('Batch operation paused and Operation %d wait for firing callback', operation.operationId));
    } else if (self.callbackInOrder) {
      operation.status = OperationState.CALLBACK;
      Eif (self._currentOperationId === operation.operationId) {
        self._fireOperationUserCallback(operation);
      } else if (self._currentOperationId > operation.operationId) {
        throw new Error('Debug error: current callback operation id cannot be larger than operation id');
      } else {
        self.logger.debug(util.format('Operation %d is waiting for firing callback %s', operation.operationId, self._currentOperationId));
      }
    } else {
      self._fireOperationUserCallback(operation);
    }
 
    self._tryEmitDrainEvent();
    operation = null;
    self = null;
  };
};
 
/**
* Fire user's call back
*/
BatchOperation.prototype._fireOperationUserCallback = function (operation) {
  var index = this._getCallbackOperationIndex();
  if (!operation && index != -1) {
    operation = this._operations[index];
  }
 
  if (operation && !this._paused) {
    // fire the callback, if exists
    Eif (operation._userCallback) {
      this.logger.debug(util.format('Fire user call back for operation %d', operation.operationId));
      // make sure UserCallback is a sync operation in sequence mode.
      // both async and sync operations are available for random mode.
      operation._fireUserCallback();
    }
    
    // remove the operation from the array and decrement the counter
    this._operations.splice(index, 1);
    this._activeOperation--;
    operation.status = OperationState.COMPLETE;
    index = operation = null;
 
    if (this.callbackInOrder) {
      this._currentOperationId++;
    }
 
    this._fireOperationUserCallback();
  } else if (this._paused) {
    this._tryEmitDrainEvent();
  } else {
    // check if batch has ended and if so emit end event
    this._tryEmitEndEvent();
  }
};
 
/**
* Try to emit the BatchOperation end event
* End event means all the operation and callback already finished.
*/
BatchOperation.prototype._tryEmitEndEvent = function () {
  if(this._enableComplete && this._activeOperation === 0 && this._operations.length === 0) {
    this._ended = true;
    this.logger.debug(util.format('Batch operation %s emits the end event', this.name));
    this._emitter.emit('end', this._error, null);
    return true;
  }
  return false;
};
 
/**
* Try to emit the drain event
*/
BatchOperation.prototype._tryEmitDrainEvent = function () {
  Iif (!this._emitter) return false;
  if(!this.IsWorkloadHeavy() || this._activeOperation < this.concurrency) {
    this._emitter.emit('drain');
    return true;
  }
  return false;
};
 
/**
* Get the current active operation index.
* Only the active operation could call user's callback in sequence model.
* The other finished but not active operations should wait for wake up.
*/
BatchOperation.prototype._getCallbackOperationIndex = function () {
  var operation = null;
  for (var i = 0; i < this._operations.length; i++) {
    operation = this._operations[i];
    if (this.callbackInOrder) {
      //Sequence mode
      Eif (operation.operationId == this._currentOperationId) {
        if (operation.status === OperationState.CALLBACK) {
          return i;
        } else {
          return -1;
        }
      }
    } else {
      //Random mode
      if (operation.status === OperationState.CALLBACK) {
        return i;
      }
    }
  }
  return -1;
};
 
/**
* Do nothing and directly call the callback.
* In random mode, the user callback will be called immediately
* In sequence mode, the user callback will be called after the previous callback has been called
*/
BatchOperation.noOperation = function (cb) {
  cb();
};
 
/**
* Rest operation in sdk
*/
function RestOperation(serviceClient, operation) {
  this.status = OperationState.Inited;
  this.operationId = -1;
  this._callbackArguments = null;
 
  // setup callback and args
  this._userCallback = arguments[arguments.length - 1];
  var sliceEnd = arguments.length;
  Eif(azureutil.objectIsFunction(this._userCallback)) {
    sliceEnd--;
  } else {
    this._userCallback = null;
  }
  var operationArguments = Array.prototype.slice.call(arguments).slice(2, sliceEnd);
 
  this.run = function(cb) {
    var func = serviceClient[operation];
    Iif(!func) {
      throw new Error(util.format('Unknown operation %s in serviceclient', operation));
    } else {
      Iif(!cb) cb = this._userCallback;
      operationArguments.push(cb);
      this.status = OperationState.RUNNING;
      func.apply(serviceClient, operationArguments);
      operationArguments = operation = null;
    }
  };
 
  this._fireUserCallback = function () {
    Eif(this._userCallback) {
      this._userCallback.apply(null, this._callbackArguments);
    }
  };
}
 
BatchOperation.RestOperation = RestOperation;
 
/**
* Common operation wrapper
*/
function CommonOperation(operationFunc, callback) {
  this.status = OperationState.Inited;
  this.operationId = -1;
  this._callbackArguments = null;
  var sliceStart = 2;
  Eif (azureutil.objectIsFunction(callback)) {
    this._userCallback = callback;
  } else {
    this._userCallback = null;
    sliceStart = 1;
  }
  var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
  this.run = function (cb) {
    Iif (!cb) cb = this._userCallback;
    operationArguments.push(cb);
    this.status = OperationState.RUNNING;
    operationFunc.apply(null, operationArguments);
    operationArguments = operationFunc = null;
  };
  
  this._fireUserCallback = function () {
    Eif (this._userCallback) {
      this._userCallback.apply(null, this._callbackArguments);
    }
    this._userCallback = this._callbackArguments = null;
  };
}
 
BatchOperation.CommonOperation = CommonOperation;
 
module.exports = BatchOperation;