This repository has been archived by the owner on May 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
peer.js
840 lines (697 loc) · 23.9 KB
/
peer.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
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var assert = require('assert');
var inherits = require('util').inherits;
var inspect = require('util').inspect;
var EventEmitter = require('./lib/event_emitter');
var stat = require('./stat-tags.js');
var net = require('net');
var TChannelConnection = require('./connection');
var HostPort = require('./host-port.js');
var errors = require('./errors');
var Request = require('./request');
var PreferOutgoing = require('./peer_score_strategies.js').PreferOutgoing;
var NoPreference = require('./peer_score_strategies.js').NoPreference;
var PreferIncoming = require('./peer_score_strategies.js').PreferIncoming;
var Range = require('./range');
var PeerDrain = require('./drain.js').PeerDrain;
var ObjectPool = require('./lib/object_pool');
var DEFAULT_REPORT_INTERVAL = 1000;
var INITIAL_CONN_ATTEMPT_DELAY = 5000;
var CONN_ATTEMPT_DELAY_MULTIPLER = 2;
var MAX_CONN_ATTEMPT_DELAY = 30 * 1000;
/*eslint max-statements: [2, 40]*/
function TChannelPeer(channel, hostPort, options) {
assert(hostPort !== '0.0.0.0:0', 'Cannot create ephemeral peer');
options = options || {};
EventEmitter.call(this);
this.stateChangedEvent = this.defineEvent('stateChanged');
this.allocConnectionEvent = this.defineEvent('allocConnection');
this.removeConnectionEvent = this.defineEvent('removeConnection');
this.deltaOutConnectionEvent = this.defineEvent('deltaOutConnection');
this.channel = channel;
this.socketInitTimeout = channel.initTimeout;
this.logger = this.channel.logger;
this.timers = this.channel.timers;
this.random = this.channel.random;
this.hostPort = hostPort;
this.connections = [];
this.pendingIdentified = 0;
this.heapElements = [];
this.scoreStrategy = null;
this.draining = null;
this.boundOnIdentified = onIdentified;
this.boundOnConnectionError = onConnectionError;
this.boundOnConnectionClose = onConnectionClose;
this.boundOnPendingChange = onPendingChange;
this.scoreRange = null;
// Timestamp when next conn attempt is allowed
this.nextConnAttemptTime = 0;
// How long to delay conn attempt by on failure (ms)
this.nextConnAttemptDelay = 0;
// Whether we are doing a connection attempt
this.hasConnectionAttempt = false;
this.waitForIdentifiedListeners = [];
this.reportInterval = options.reportInterval || DEFAULT_REPORT_INTERVAL;
if (this.reportInterval > 0 && this.channel.emitConnectionMetrics) {
this.reportTimer = this.timers.setTimeout(
onReport, this.reportInterval
);
}
this.connectionAttemptDelay = this.channel.connectionAttemptDelay ||
INITIAL_CONN_ATTEMPT_DELAY;
this.maxConnectionAttemptDelay = this.channel.maxConnectionAttemptDelay ||
MAX_CONN_ATTEMPT_DELAY;
this.setPreferConnectionDirection(options.preferConnectionDirection || 'any');
var self = this;
function onIdentified(_, conn) {
self.onIdentified(conn);
}
function onConnectionError(err, conn) {
self.onConnectionError(err, conn);
}
function onConnectionClose(_, conn) {
self.onConnectionClose(conn);
}
function onPendingChange(pending, conn) {
self.onPendingChange(conn, pending);
}
function onReport() {
if (!self.hostPort) {
return;
}
var count = self.countConnections('out');
if (self.channel.emitConnectionMetrics) {
self.channel.emitFastStat(
'tchannel.connections.active',
'gauge',
count,
new stat.ConnectionsActiveTags(
self.channel.hostPort,
self.hostPort
)
);
}
self.reportTimer = self.timers.setTimeout(
onReport, self.reportInterval
);
}
}
inherits(TChannelPeer, EventEmitter);
TChannelPeer.prototype.DRAIN_GOAL_NOOP = PeerDrain.GOAL_NOOP;
TChannelPeer.prototype.DRAIN_GOAL_CLOSE_DRAINED = PeerDrain.GOAL_CLOSE_DRAINED;
TChannelPeer.prototype.DRAIN_GOAL_CLOSE_PEER = PeerDrain.GOAL_CLOSE_PEER;
TChannelPeer.prototype.toString =
function toString() {
var self = this;
return 'TChannelPeer(' + self.hostPort + ')';
};
TChannelPeer.prototype.inspect =
function inspectPeer() {
var self = this;
return 'TChannelPeer(' + inspect(self.extendLogInfo({})) + ')';
};
TChannelPeer.prototype.extendLogInfo =
function extendLogInfo(info) {
var self = this;
info.hostPort = self.hostPort;
info.peerDraining = !!self.draining;
info.scoreRange = self.scoreRange;
if (self.draining) {
self.draining.extendLogInfo(info);
}
return info;
};
TChannelPeer.prototype.drain =
function drain(options, callback) {
var self = this;
assert(!self.draining, 'cannot double drain a peer');
self.draining = new PeerDrain(self, options, callback);
self.draining.start();
};
TChannelPeer.prototype.clearDrain =
function clearDrain(reason) {
var self = this;
if (self.draining) {
self.draining.stop(reason);
self.draining = null;
}
};
TChannelPeer.prototype.setMaxTombstoneTTL =
function setMaxTombstoneTTL(ttl) {
var self = this;
for (var i = 0; i < self.connections.length; i++) {
var conn = self.connections[i];
conn.ops.setMaxTombstoneTTL(ttl);
}
};
TChannelPeer.prototype.setPreferConnectionDirection = function setPreferConnectionDirection(direction) {
var self = this;
if (self.preferConnectionDirection === direction) {
return;
}
self.preferConnectionDirection = direction;
if (self.preferConnectionDirection === 'out') {
self.setScoreStrategy(PreferOutgoing);
} else if (self.preferConnectionDirection === 'in') {
self.setScoreStrategy(PreferIncoming);
} else {
self.setScoreStrategy(NoPreference);
}
self.invalidateScore('setPreferConnectionDirection');
};
TChannelPeer.prototype.setScoreStrategy = function setScoreStrategy(ScoreStrategy) {
var self = this;
self.scoreStrategy = new ScoreStrategy(self);
};
TChannelPeer.prototype.invalidateScore = function invalidateScore(reason) {
var self = this;
self.scoreRange = self.computeScoreRange();
if (!self.heapElements.length) {
return;
}
var info = self.channel.peerScoredEvent ? {
peer: self,
reason: reason || 'unknown',
score: 0,
oldScores: [],
scores: []
} : null;
var range = self.scoreRange;
for (var i = 0; i < self.heapElements.length; i++) {
var el = self.heapElements[i];
if (info) {
info.oldScores.push(el.range);
info.scores.push(range);
}
el.rescore();
}
if (info) {
self.channel.peerScoredEvent.emit(self, info);
}
};
TChannelPeer.prototype.isConnected = function isConnected(direction, identified) {
var self = this;
if (identified === undefined) {
identified = true;
}
for (var i = 0; i < self.connections.length; i++) {
var conn = self.connections[i];
if (direction && conn.direction !== direction) {
continue;
} else if (conn.closing) {
continue;
} else if (conn.remoteName !== null || !identified) {
return true;
}
}
return false;
};
TChannelPeer.prototype.closeDrainedConnections =
function closeDrainedConnections(callback) {
var self = this;
var counter = 1;
var conns = self.connections.slice(0);
for (var i = 0; i < conns.length; i++) {
var conn = conns[i];
if (conn.draining) {
counter++;
conn.close(onClose);
}
}
onClose();
function onClose() {
if (--counter <= 0) {
if (counter < 0) {
self.logger.error('closed more peer sockets than expected', {
counter: counter
});
}
callback(null);
}
}
};
TChannelPeer.prototype.close =
function close(callback) {
var self = this;
if (self.reportTimer) {
self.timers.clearTimeout(self.reportTimer);
self.reportTimer = null;
}
var conns = self.connections.slice(0);
var counter = conns.length;
if (counter) {
for (var i = 0; i < conns.length; i++) {
conns[i].close(onClose);
}
} else {
callback(null);
}
function onClose() {
if (--counter <= 0) {
if (counter < 0) {
self.logger.error('closed more peer sockets than expected', {
counter: counter
});
}
callback(null);
}
}
};
TChannelPeer.prototype.getInConnection = function getInConnection(preferIdentified) {
var self = this;
var candidate = null;
for (var i = 0; i < self.connections.length; i++) {
var conn = self.connections[i];
if (conn.closing) {
continue;
}
if (!preferIdentified) {
return conn; // user doesn't care, take first incoming
}
if (conn.remoteName) {
return conn; // user wanted an identified channel, and we found one
}
if (!candidate) {
candidate = conn; // we'll fallback to returning this if we can't find an identified one
}
}
return candidate;
};
TChannelPeer.prototype.getIdentifiedInConnection = function getIdentifiedInConnection() {
var self = this;
return self.getInConnection(true);
};
TChannelPeer.prototype.getOutConnection = function getOutConnection(preferIdentified) {
var self = this;
var candidate = null;
for (var i = self.connections.length - 1; i >= 0; i--) {
var conn = self.connections[i];
if (conn.closing) {
continue;
}
if (!preferIdentified) {
return conn; // user doesn't care, take last outgoing
}
if (conn.remoteName) {
return conn; // user wanted an identified channel, and we found one
}
if (!candidate) {
candidate = conn; // we'll fallback to returning this if we can't find an identified one
}
}
return candidate;
};
TChannelPeer.prototype.getIdentifiedOutConnection = function getIdentifiedOutConnection() {
var self = this;
return self.getOutConnection(true);
};
TChannelPeer.prototype.countConnections = function countConnections(direction) {
var self = this;
if (!direction) {
return self.connections.length;
}
var count = 0;
for (var i = 0; i < self.connections.length; i++) {
var conn = self.connections[i];
if (conn.direction === direction) {
count++;
}
}
return count;
};
// ensures that a connection exists
TChannelPeer.prototype.connect =
function connect(outOnly) {
var self = this;
var conn = null;
if (self.preferConnectionDirection === 'in' && !outOnly) {
conn = self.getIdentifiedInConnection();
} else {
conn = self.getIdentifiedOutConnection();
}
if (!conn || (outOnly && conn.direction !== 'out')) {
var socket = self.makeOutSocket();
conn = self.makeOutConnection(socket);
self.addConnection(conn);
}
return conn;
};
// ensures that an outbound connection exists
TChannelPeer.prototype.connectTo = function connectTo() {
var self = this;
return self.connect(true);
};
TChannelPeer.prototype.tryConnect = function tryConnect() {
var self = this;
var connectTime = Date.now();
if (connectTime < self.nextConnAttemptTime ||
self.hasConnectionAttempt
) {
return;
}
self.hasConnectionAttempt = true;
var conn = this.getOutConnection();
if (!conn || conn.direction !== 'out') {
conn = this.connectTo();
}
this.waitForIdentified(conn, onIdentified);
function onIdentified(err) {
self.hasConnectionAttempt = false;
if (!err) {
self.nextConnAttemptDelay = 0;
self.nextConnAttemptTime = 0;
return;
}
if (self.nextConnAttemptDelay === 0) {
self.nextConnAttemptDelay = self.connectionAttemptDelay;
} else {
self.nextConnAttemptDelay *= CONN_ATTEMPT_DELAY_MULTIPLER;
// Add some amount of fuzz, +-100ms
self.nextConnAttemptDelay += Math.floor(100 * (Math.random() - 0.5));
self.nextConnAttemptDelay = Math.min(
self.nextConnAttemptDelay, self.maxConnectionAttemptDelay
);
}
var afterConnect = Date.now();
if (self.nextConnAttemptTime < afterConnect) {
// When in the past set next attempt to now + delay
self.nextConnAttemptTime = afterConnect + self.nextConnAttemptDelay;
} else {
// When in the future; leave it alone.
}
}
};
TChannelPeer.prototype.waitForIdentified =
function waitForIdentified(conn, callback) {
var self = this;
if (typeof conn === 'function' && !callback) {
callback = conn;
conn = self.connect();
}
if (conn.closing) {
callback(conn.closeError);
} else if (conn.remoteName) {
callback(null);
} else {
return self._waitForIdentified(conn, callback);
}
return -1;
};
TChannelPeer.prototype._waitForIdentified =
function _waitForIdentified(conn, callback) {
var self = this;
var called = false;
// Setup an ident descriptor so we can stop waiting for identified later
var slot = self.getIdentDescriptorSlot();
var descriptor = WaitForIdentifiedDescriptor.alloc();
descriptor.reset(
onConnectionClose,
onConnectionError,
onIdentified,
conn
);
self.waitForIdentifiedListeners[slot] = descriptor;
self.pendingIdentified++;
conn.errorEvent.on(onConnectionError);
conn.closeEvent.on(onConnectionClose);
conn.identifiedEvent.on(onIdentified);
self.invalidateScore('waitForIdentified');
return slot;
function onConnectionError(err) {
finish(err);
}
function onConnectionClose(err) {
finish(err);
}
function onIdentified() {
finish(null);
}
function finish(err) {
// Multiple events can trigger which causes double callback hilarity.
if (called) {
return;
}
called = true;
self.stopWaitingForIdentified(slot);
callback(err);
}
};
TChannelPeer.prototype.stopWaitingForIdentified =
function stopWaitingForIdentified(slot) {
assert(typeof slot === 'number', 'stopWaitingForIdentified arg1 should be number');
if (slot === -1) {
// when connection was already identified, `waitForIdentified` will
// return -1
return;
}
var descriptor = this.waitForIdentifiedListeners[slot];
this.waitForIdentifiedListeners[slot] = null;
if (!descriptor || !descriptor.conn) {
return;
}
var conn = descriptor.conn;
conn.errorEvent.removeListener(descriptor.error);
conn.closeEvent.removeListener(descriptor.close);
conn.identifiedEvent.removeListener(descriptor.ident);
this.pendingIdentified = 0;
this.invalidateScore('waitForIdentified > finish');
descriptor.free();
};
TChannelPeer.prototype.getIdentDescriptorSlot =
function getIdentDescriptorSlot() {
var i;
for (i = 0; i < this.waitForIdentifiedListeners.length; i++) {
if (this.waitForIdentifiedListeners[i] === null) {
return i;
}
}
return this.waitForIdentifiedListeners.length;
};
TChannelPeer.prototype.request = function peerRequest(options) {
var self = this;
options.timeout = options.timeout || Request.defaultTimeout;
return self.connect().request(options);
};
TChannelPeer.prototype.addConnection = function addConnection(conn) {
var self = this;
// TODO: first approx alert for self.connections.length > 2
// TODO: second approx support pruning
if (conn.direction === 'out') {
self.connections.push(conn);
self.deltaOutConnectionEvent.emit(self, 1);
} else {
self.connections.unshift(conn);
}
conn.errorEvent.on(self.boundOnConnectionError);
conn.closeEvent.on(self.boundOnConnectionClose);
conn.ops.pendingChangeEvent.on(self.boundOnPendingChange);
self._maybeInvalidateScore('addConnection');
if (!conn.remoteName) {
// TODO: could optimize if handler had a way of saying "would a new
// identified connection change your Tier?"
conn.identifiedEvent.on(self.boundOnIdentified);
}
if (!conn.draining) {
if (conn.channel.draining) {
conn.drain(conn.channel.drainReason, null);
} else if (self.draining) {
self.draining.drainConnection(conn);
}
}
return conn;
};
TChannelPeer.prototype.onIdentified =
function onIdentified(conn) {
var self = this;
conn.identifiedEvent.removeListener(self.boundOnIdentified);
self._maybeInvalidateScore('addConnection > onIdentified');
};
TChannelPeer.prototype.onConnectionError =
function onConnectionError(err, conn) {
var self = this;
self.removeConnectionFrom(err, conn);
};
TChannelPeer.prototype.onConnectionClose =
function onConnectionClose(conn) {
var self = this;
self.removeConnectionFrom(null, conn);
};
TChannelPeer.prototype.onPendingChange =
function onPendingChange() {
var self = this;
// TODO: it would be possible to a faster partial-recomputation based only
// on the change of pending for the this one connection. Note arguments are
// (conn, pending)
self._maybeInvalidateScore('pendingChange');
};
TChannelPeer.prototype.removeConnectionFrom =
function removeConnectionFrom(err, conn) {
var self = this;
conn.closeEvent.removeListener(self.boundOnConnectionClose);
conn.errorEvent.removeListener(self.boundOnConnectionError);
conn.identifiedEvent.removeListener(self.boundOnIdentified);
conn.ops.pendingChangeEvent.removeListener(self.boundOnPendingChange);
if (err) {
var loggerInfo = conn.extendLogInfo({
error: err
});
var codeName = errors.classify(err);
if (codeName === 'Timeout' ||
codeName === 'NetworkError') {
self.logger.warn('Got a connection error', loggerInfo);
} else {
self.logger.error('Got an unexpected connection error', loggerInfo);
}
}
self.removeConnection(conn);
};
TChannelPeer.prototype.removeConnection = function removeConnection(conn) {
var self = this;
var ret = null;
var isRemoved = false;
var index = self.connections ? self.connections.indexOf(conn) : -1;
if (index !== -1) {
ret = self.connections.splice(index, 1)[0];
isRemoved = conn.direction === 'out';
}
self._maybeInvalidateScore('removeConnection');
self.removeConnectionEvent.emit(self, conn);
if (isRemoved) {
self.deltaOutConnectionEvent.emit(self, -1);
}
return ret;
};
TChannelPeer.prototype.makeOutSocket = function makeOutSocket() {
var self = this;
var reason = HostPort.validateHostPort(self.hostPort, false);
if (reason) {
assert(false, reason);
}
var parts = self.hostPort.split(':');
var host = parts[0];
var port = parseInt(parts[1], 10);
var socket = net.createConnection({
host: host,
port: port
});
return socket;
};
TChannelPeer.prototype.makeOutConnection = function makeOutConnection(socket) {
var self = this;
var chan = self.channel.topChannel || self.channel;
var conn = new TChannelConnection(
chan, socket, 'out', self.hostPort, this.socketInitTimeout
);
self.allocConnectionEvent.emit(self, conn);
return conn;
};
// Returns a range from 0 to 1, where it is preferable to use
// a peer with a higher score over one with a lower score.
// This range is divided among an infinite set of subranges corresponding
// to peers with the same number of pending requests.
// So, the range (1/2, 1] is reserved for peers with 0 pending connections.
// The range (1/4, 1/2] is reserved for peers with 1 pending connections.
// The range (1/8, 1/4] is reserved for peers with 2 pending connections.
// Ad nauseam.
// Within each equivalence class, each peer receives a uniform random
// value.
//
// The previous score was a weighted random variable:
// random() ** (1 + pending)
// This had the attribute that a less loaded peer was merely more likely to
// be chosen over a more loaded peer.
// We observed with the introduction of a heap, that a less favored peer
// would have its score less frequently re-evaluated.
// An emergent behavior was that scores would, over time, be squeezed
// toward zero and the least favored peer would remain the least favored
// for ever increasing durations.
//
// This remains true with this algorithm, within each equivalence class.
TChannelPeer.prototype.pendingWeightedRange = function pendingWeightedRange() {
var self = this;
var pending = self.countPending();
var max = Math.pow(0.5, pending);
var min = max / 2;
return new Range(min, max);
};
TChannelPeer.prototype.countPending = function countPending() {
var self = this;
var pending = self.pendingIdentified;
for (var index = 0; index < self.connections.length; index++) {
var connPending = self.connections[index].ops.getPending();
pending += connPending.out;
pending += connPending.errors;
}
return pending;
};
// TODO: on connection #getScore impacting event
// - on identified
// Called on connection change event
TChannelPeer.prototype._maybeInvalidateScore =
function _maybeInvalidateScore(reason) {
var self = this;
if (self.scoreStrategy.getTier() !== self.scoreStrategy.lastTier) {
self.invalidateScore(reason);
}
};
TChannelPeer.prototype.getScoreRange = function getScoreRange() {
var self = this;
return self.scoreRange;
};
TChannelPeer.prototype.computeScoreRange = function computeScoreRange() {
var self = this;
var range = self.scoreStrategy.getScoreRange();
range.multiply(self.pendingWeightedRange());
return range;
};
TChannelPeer.prototype.getScore = function getScore() {
// This is INLINED into peer_heap.js#115
var self = this;
var diff = self.scoreRange.hi - self.scoreRange.lo;
var rand = self.random();
if (rand === 0) {
rand = 1;
}
return self.scoreRange.lo + diff * rand;
};
module.exports = TChannelPeer;
function WaitForIdentifiedDescriptor(close, error, ident, conn) {
this.close = null;
this.error = null;
this.ident = null;
this.conn = null;
}
WaitForIdentifiedDescriptor.prototype.reset =
function reset(close, error, ident, conn) {
this.close = close;
this.error = error;
this.ident = ident;
this.conn = conn;
};
WaitForIdentifiedDescriptor.prototype.clear =
function clear() {
this.close = null;
this.error = null;
this.ident = null;
this.conn = null;
};
ObjectPool.setup({Type: WaitForIdentifiedDescriptor, maxSize: 100});