This repository has been archived by the owner on May 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 567
/
batchoperation.js
417 lines (383 loc) · 12.8 KB
/
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
417
//
// 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 azureCommon = require('azure-common');
var utils = azureCommon.util;
var Logger = azureCommon.Logger;
var DEFAULT_OPERATION_MEMORY_USAGE = azureCommon.Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
var DEFAULT_GLOBAL_CONCURRENCY = 5; //Default http connection limitation for nodejs
var SystemTotalMemory = os.totalmem();
var nodeVersion = utils.getNodeVersion();
var enableReuseSocket = nodeVersion.major >= 0 && nodeVersion.minor >= 10;
/**
* Concurrent execute batch operation 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 operation and callback has finished.
* 2. BatchOperation guarantee the user callback is fired one by one.
* 3. The next user callback can't be fired util the current one complete.
*/
function BatchOperation(name, options) {
if (!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._currentOperationId = this.callbackInorder ? 1 : -1;
this.concurrency = DEFAULT_GLOBAL_CONCURRENCY;
//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 = [];
this._emitter = null;
this._enableComplete = false;
this._ended = false;
this._error = null;
this._paused = false;
}
/**
* 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) {
if (concurrency) {
this.concurrency = concurrency;
http.globalAgent.maxSockets = this.concurrency;
https.globalAgent.maxSockets = this.concurrency;
}
};
/**
* Is the workload heavy and It can 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;
if(enableReuseSocket) {
sharedRequest = 5;
}
return this._activeOperation >= sharedRequest * this.concurrency ||
(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;
};
/**
* Add a operation into batch operation
*/
BatchOperation.prototype.addOperation = function(operation) {
this._operations.push(operation);
operation.status = OperationState.QUEUED;
operation.operationId = this._getActiveOperationId();
this._queuedOperation++;
this.logger.debug(util.format('Add operation %d into batch operation %s.', operation.operationId, this.name));
//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() {
if (this._paused) {
this._paused = false;
this._fireOperationUserCallback();
}
};
/**
* Add event listener
*/
BatchOperation.prototype.on = function(event, listener) {
if(!this._emitter) this._emitter = new EventEmitter();
if(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);
if(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) {
self.logger.debug(util.format('Operation %d failed. Error %s', operation.operationId, error));
//Abort the batch operation if one of them failed
self.abort(error);
} else {
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 pasued and Operation %d wait for firing callback', operation.operationId));
} else if (self.callbackInorder) {
if(self._currentOperationId === operation.operationId) {
self._fireOperationUserCallback(operation);
} else if (self._currentOperationId > operation.operationId) {
throw new Error('Debug error: current callback operation id can\'t larger than oepration id');
} else {
operation.status = OperationState.CALLBACK;
self.logger.debug(util.format('Operation %d wait for firing callback %s', operation.operationId, self._currentOperationId));
}
} else {
self._fireOperationUserCallback(operation);
}
self._tryEmitDrainEvent();
operation = null;
self = null;
};
};
/**
* Abort all the operation
*/
BatchOperation.prototype.abort = function (abortError) {
if (abortError) {
//Can't really abort all operations now.
this._error = abortError;
}
};
/**
* Fire user's call back
*/
BatchOperation.prototype._fireOperationUserCallback = function (operation) {
var index = -1;
if (operation) {
index = this._operations.indexOf(operation);
} else if (this.callbackInorder) {
index = this._getCurrentOperationIndex();
}
if(index != -1 && !this._paused) {
operation = this._operations[index];
if(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();
}
this._operations.splice(index, 1);
this._activeOperation--;
operation.status = OperationState.COMPLETE;
index = operation = null;
if(this._operations.length === 0) {
// Emit end event with callbackInorder
this._tryEmitEndEvent();
}
if(this.callbackInorder) {
this._currentOperationId++;
}
this._fireOperationUserCallback();
} else {
this._tryEmitDrainEvent();
}
};
/**
* 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;
if(this._emitter) {
this.logger.debug(util.format('Batch operation %s emit the end event', this.name));
var retValue = null;
this._emitter.emit('end', this._error, retValue);
}
return true;
}
return false;
};
/**
* Try to emit the drain event
*/
BatchOperation.prototype._tryEmitDrainEvent = function () {
if(!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._getCurrentOperationIndex = function () {
var operation = null;
for(var i = 0, len = this._operations.length; i < len; i++) {
operation = this._operations[i];
if (this.callbackInorder) {
//Sequence mode
if(operation.operationId == this._currentOperationId) {
if (operation.status === OperationState.CALLBACK) {
return i;
} else if (operation.status === OperationState.COMPLETE) {
this._currentOperationId ++;
return this._getCurrentOperationIndex();
} else {
break;
}
}
} else {
//Random mode
if (operation.status === OperationState.CALLBACK) {
return i;
}
}
}
return -1;
};
/**
* Get an operation id
*/
BatchOperation.prototype._getActiveOperationId = function() {
return ++this._totalOperation;
};
/**
* Rest operation in sdk
*/
function RestOperation(serviceClient, operation) {
this.status = OperationState.Inited;
this.operationId = -1;
this._userCallback = arguments[arguments.length - 1];
this._callbackArguments = null;
var sliceEnd = arguments.length;
if(utils.objectIsFunction(this._userCallback)) {
sliceEnd--;
} else {
this._userCallback = null;
}
var operationArguments = Array.prototype.slice.call(arguments).slice(2, sliceEnd);
sliceEnd = null;
this.run = function(cb) {
var func = serviceClient[operation];
if(!func) {
throw new Error(util.format('Unknown operation %s in serviceclient', operation));
} else {
if(!cb) cb = this._userCallback;
operationArguments.push(cb);
this.status = OperationState.RUNNING;
func.apply(serviceClient, operationArguments);
operationArguments = serviceClient = operation = null;
}
};
this._fireUserCallback = function () {
if(this._userCallback) {
this._userCallback.apply(null, this._callbackArguments);
}
this._userCallback = this._callbackArguments = null;
};
}
BatchOperation.RestOperation = RestOperation;
/**
* Common operation wrapper
*/
function CommonOperation(operationFunc, callback) {
this.status = OperationState.Inited;
this.operationId = -1;
this._callbackArguments = null;
var sliceStart = 2;
if(utils.objectIsFunction(callback)) {
this._userCallback = callback;
} else {
this._userCallback = null;
sliceStart = 1;
}
var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
this.run = function(cb) {
if(!cb) cb = this._userCallback;
operationArguments.push(cb);
this.status = OperationState.RUNNING;
operationFunc.apply(null, operationArguments);
operationArguments = operationFunc = null;
};
this._fireUserCallback = function () {
if(this._userCallback) {
this._userCallback.apply(null, this._callbackArguments);
}
this._userCallback = this._callbackArguments = null;
};
}
BatchOperation.CommonOperation = CommonOperation;
/**
* 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();
};
module.exports = BatchOperation;