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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
|
// **********************************************************************
//
// Copyright (c) 2003-2018 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
const Ice = require("../Ice/ModuleRegistry").Ice;
Ice._ModuleRegistry.require(module,
[
"../Ice/ArrayUtil",
"../Ice/AsyncResultBase",
"../Ice/ConnectionI",
"../Ice/Debug",
"../Ice/HashMap",
"../Ice/Promise",
"../Ice/EndpointTypes",
"../Ice/LocalException",
"../Ice/Exception",
"../Ice/ACM"
]);
const ArrayUtil = Ice.ArrayUtil;
const AsyncResultBase = Ice.AsyncResultBase;
const ConnectionI = Ice.ConnectionI;
const ConnectionReaper = Ice.ConnectionReaper;
const Debug = Ice.Debug;
const HashMap = Ice.HashMap;
const EndpointSelectionType = Ice.EndpointSelectionType;
const FactoryACMMonitor = Ice.FactoryACMMonitor;
//
// Only for use by Instance.
//
class OutgoingConnectionFactory
{
constructor(communicator, instance)
{
this._communicator = communicator;
this._instance = instance;
this._destroyed = false;
this._monitor = new FactoryACMMonitor(this._instance, this._instance.clientACM());
this._connectionsByEndpoint = new ConnectionListMap(); // map<EndpointI, Array<Ice.ConnectionI>>
this._pending = new HashMap(HashMap.compareEquals); // map<EndpointI, Array<ConnectCallback>>
this._pendingConnectCount = 0;
this._waitPromise = null;
}
destroy()
{
if(this._destroyed)
{
return;
}
this._connectionsByEndpoint.forEach(connection => connection.destroy(ConnectionI.CommunicatorDestroyed));
this._destroyed = true;
this._communicator = null;
this.checkFinished();
}
waitUntilFinished()
{
this._waitPromise = new Ice.Promise();
this.checkFinished();
return this._waitPromise;
}
//
// Returns a promise, success callback receives the connection
//
create(endpts, hasMore, selType)
{
Debug.assert(endpts.length > 0);
//
// Apply the overrides.
//
const endpoints = this.applyOverrides(endpts);
//
// Try to find a connection to one of the given endpoints.
//
try
{
const connection = this.findConnectionByEndpoint(endpoints);
if(connection !== null)
{
return Ice.Promise.resolve(connection);
}
}
catch(ex)
{
return Ice.Promise.reject(ex);
}
return new ConnectCallback(this, endpoints, hasMore, selType).start();
}
setRouterInfo(routerInfo)
{
return Ice.Promise.try(() =>
{
if(this._destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
return routerInfo.getClientEndpoints();
}
).then(
endpoints =>
{
//
// Search for connections to the router's client proxy
// endpoints, and update the object adapter for such
// connections, so that callbacks from the router can be
// received over such connections.
//
const adapter = routerInfo.getAdapter();
const defaultsAndOverrides = this._instance.defaultsAndOverrides();
endpoints.forEach(endpoint =>
{
//
// Modify endpoints with overrides.
//
if(defaultsAndOverrides.overrideTimeout)
{
endpoint = endpoint.changeTimeout(defaultsAndOverrides.overrideTimeoutValue);
}
//
// The Connection object does not take the compression flag of
// endpoints into account, but instead gets the information
// about whether messages should be compressed or not from
// other sources. In order to allow connection sharing for
// endpoints that differ in the value of the compression flag
// only, we always set the compression flag to false here in
// this connection factory.
//
endpoint = endpoint.changeCompress(false);
this._connectionsByEndpoint.forEach(connection =>
{
if(connection.endpoint().equals(endpoint))
{
connection.setAdapter(adapter);
}
});
});
});
}
removeAdapter(adapter)
{
if(this._destroyed)
{
return;
}
this._connectionsByEndpoint.forEach(connection =>
{
if(connection.getAdapter() === adapter)
{
connection.setAdapter(null);
}
});
}
flushAsyncBatchRequests()
{
const promise = new AsyncResultBase(this._communicator, "flushBatchRequests", null, null, null);
if(this._destroyed)
{
promise.resolve();
return promise;
}
Ice.Promise.all(
this._connectionsByEndpoint.map(
connection =>
{
if(connection.isActiveOrHolding())
{
return connection.flushBatchRequests().catch(
ex =>
{
if(ex instanceof Ice.LocalException)
{
// Ignore
}
else
{
throw ex;
}
});
}
})).then(promise.resolve, promise.reject);
return promise;
}
applyOverrides(endpts)
{
const defaultsAndOverrides = this._instance.defaultsAndOverrides();
return endpts.map(endpoint =>
{
//
// Modify endpoints with overrides.
//
return defaultsAndOverrides.overrideTimeout ?
endpoint.changeTimeout(defaultsAndOverrides.overrideTimeoutValue) : endpoint;
});
}
findConnectionByEndpoint(endpoints)
{
if(this._destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
const defaultsAndOverrides = this._instance.defaultsAndOverrides();
Debug.assert(endpoints.length > 0);
for(let i = 0; i < endpoints.length; ++i)
{
const endpoint = endpoints[i];
if(this._pending.has(endpoint))
{
continue;
}
const connectionList = this._connectionsByEndpoint.get(endpoint);
if(connectionList === undefined)
{
continue;
}
for(let j = 0; j < connectionList.length; ++j)
{
if(connectionList[j].isActiveOrHolding()) // Don't return destroyed or un-validated connections
{
return connectionList[j];
}
}
}
return null;
}
incPendingConnectCount()
{
//
// Keep track of the number of pending connects. The outgoing connection factory
// waitUntilFinished() method waits for all the pending connects to terminate before
// to return. This ensures that the communicator client thread pool isn't destroyed
// too soon and will still be available to execute the ice_exception() callbacks for
// the asynchronous requests waiting on a connection to be established.
//
if(this._destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
++this._pendingConnectCount;
}
decPendingConnectCount()
{
--this._pendingConnectCount;
Debug.assert(this._pendingConnectCount >= 0);
if(this._destroyed && this._pendingConnectCount === 0)
{
this.checkFinished();
}
}
getConnection(endpoints, cb)
{
if(this._destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
//
// Reap closed connections
//
const cons = this._monitor.swapReapedConnections();
if(cons !== null)
{
cons.forEach(c =>
{
this._connectionsByEndpoint.removeConnection(c.endpoint(), c);
this._connectionsByEndpoint.removeConnection(c.endpoint().changeCompress(true), c);
});
}
//
// Try to get the connection.
//
while(true)
{
if(this._destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
//
// Search for a matching connection. If we find one, we're done.
//
const connection = this.findConnectionByEndpoint(endpoints);
if(connection !== null)
{
return connection;
}
if(this.addToPending(cb, endpoints))
{
//
// A connection is already pending.
//
return null;
}
else
{
//
// No connection is currently pending to one of our endpoints, so we
// get out of this loop and start the connection establishment to one of the
// given endpoints.
//
break;
}
}
//
// At this point, we're responsible for establishing the connection to one of
// the given endpoints. If it's a non-blocking connect, calling nextEndpoint
// will start the connection establishment. Otherwise, we return null to get
// the caller to establish the connection.
//
cb.nextEndpoint();
return null;
}
createConnection(transceiver, endpoint)
{
Debug.assert(this._pending.has(endpoint) && transceiver !== null);
//
// Create and add the connection to the connection map. Adding the connection to the map
// is necessary to support the interruption of the connection initialization and validation
// in case the communicator is destroyed.
//
let connection = null;
try
{
if(this._destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
connection = new ConnectionI(this._communicator, this._instance, this._monitor, transceiver,
endpoint.changeCompress(false), false, null);
}
catch(ex)
{
if(ex instanceof Ice.LocalException)
{
try
{
transceiver.close();
}
catch(exc)
{
// Ignore
}
}
throw ex;
}
this._connectionsByEndpoint.set(connection.endpoint(), connection);
this._connectionsByEndpoint.set(connection.endpoint().changeCompress(true), connection);
return connection;
}
finishGetConnection(endpoints, endpoint, connection, cb)
{
// cb is-a ConnectCallback
const connectionCallbacks = [];
if(cb !== null)
{
connectionCallbacks.push(cb);
}
let callbacks = [];
endpoints.forEach(endpt =>
{
let cbs = this._pending.get(endpt);
if(cbs !== undefined)
{
this._pending.delete(endpt);
cbs.forEach(cc =>
{
if(cc.hasEndpoint(endpoint))
{
if(connectionCallbacks.indexOf(cc) === -1)
{
connectionCallbacks.push(cc);
}
}
else
{
if(callbacks.indexOf(cc) === -1)
{
callbacks.push(cc);
}
}
});
}
});
connectionCallbacks.forEach(cc =>
{
cc.removeFromPending();
let idx = callbacks.indexOf(cc);
if(idx !== -1)
{
callbacks.splice(idx, 1);
}
});
callbacks.forEach(cc => cc.removeFromPending());
callbacks.forEach(cc => cc.getConnection());
connectionCallbacks.forEach(cc => cc.setConnection(connection));
this.checkFinished();
}
finishGetConnectionEx(endpoints, ex, cb)
{
// cb is-a ConnectCallback
const failedCallbacks = [];
if(cb !== null)
{
failedCallbacks.push(cb);
}
const callbacks = [];
endpoints.forEach(endpt =>
{
const cbs = this._pending.get(endpt);
if(cbs !== undefined)
{
this._pending.delete(endpt);
cbs.forEach(cc =>
{
if(cc.removeEndpoints(endpoints))
{
if(failedCallbacks.indexOf(cc) === -1)
{
failedCallbacks.push(cc);
}
}
else
{
if(callbacks.indexOf(cc) === -1)
{
callbacks.push(cc);
}
}
});
}
});
callbacks.forEach(cc =>
{
Debug.assert(failedCallbacks.indexOf(cc) === -1);
cc.removeFromPending();
});
this.checkFinished();
callbacks.forEach(cc => cc.getConnection());
failedCallbacks.forEach(cc => cc.setException(ex));
}
addToPending(cb, endpoints)
{
// cb is-a ConnectCallback
//
// Add the callback to each pending list.
//
let found = false;
if(cb !== null)
{
endpoints.forEach(p =>
{
const cbs = this._pending.get(p);
if(cbs !== undefined)
{
found = true;
if(cbs.indexOf(cb) === -1)
{
cbs.push(cb); // Add the callback to each pending endpoint.
}
}
});
}
if(found)
{
return true;
}
//
// If there's no pending connection for the given endpoints, we're
// responsible for its establishment. We add empty pending lists,
// other callbacks to the same endpoints will be queued.
//
endpoints.forEach(p =>
{
if(!this._pending.has(p))
{
this._pending.set(p, []);
}
});
return false;
}
removeFromPending(cb, endpoints)
{
// cb is-a ConnectCallback
endpoints.forEach(p =>
{
const cbs = this._pending.get(p);
if(cbs !== undefined)
{
const idx = cbs.indexOf(cb);
if(idx !== -1)
{
cbs.splice(idx, 1);
}
}
});
}
handleConnectionException(ex, hasMore)
{
const traceLevels = this._instance.traceLevels();
if(traceLevels.network >= 2)
{
const s = [];
s.push("connection to endpoint failed");
if(ex instanceof Ice.CommunicatorDestroyedException)
{
s.push("\n");
}
else
{
if(hasMore)
{
s.push(", trying next endpoint\n");
}
else
{
s.push(" and no more endpoints to try\n");
}
}
s.push(ex.toString());
this._instance.initializationData().logger.trace(traceLevels.networkCat, s.join(""));
}
}
handleException(ex, hasMore)
{
const traceLevels = this._instance.traceLevels();
if(traceLevels.network >= 2)
{
const s = [];
s.push("couldn't resolve endpoint host");
if(ex instanceof Ice.CommunicatorDestroyedException)
{
s.push("\n");
}
else
{
if(hasMore)
{
s.push(", trying next endpoint\n");
}
else
{
s.push(" and no more endpoints to try\n");
}
}
s.push(ex.toString());
this._instance.initializationData().logger.trace(traceLevels.networkCat, s.join(""));
}
}
checkFinished()
{
//
// Can't continue until the factory is destroyed and there are no pending connections.
//
if(!this._waitPromise || !this._destroyed || this._pending.size > 0 || this._pendingConnectCount > 0)
{
return;
}
Ice.Promise.all(
this._connectionsByEndpoint.map(
connection => connection.waitUntilFinished().catch(ex => Debug.assert(false)))
).then(
() =>
{
const cons = this._monitor.swapReapedConnections();
if(cons !== null)
{
const arr = [];
this._connectionsByEndpoint.forEach(connection =>
{
if(arr.indexOf(connection) === -1)
{
arr.push(connection);
}
});
Debug.assert(cons.length === arr.length);
this._connectionsByEndpoint.clear();
}
else
{
Debug.assert(this._connectionsByEndpoint.size === 0);
}
Debug.assert(this._waitPromise !== null);
this._waitPromise.resolve();
this._monitor.destroy();
});
}
}
Ice.OutgoingConnectionFactory = OutgoingConnectionFactory;
module.exports.Ice = Ice;
//
// Value is a Vector<Ice.ConnectionI>
//
class ConnectionListMap extends HashMap
{
constructor(h)
{
super(h || HashMap.compareEquals);
}
set(key, value)
{
let list = this.get(key);
if(list === undefined)
{
list = [];
super.set(key, list);
}
Debug.assert(value instanceof ConnectionI);
list.push(value);
return undefined;
}
removeConnection(key, conn)
{
const list = this.get(key);
Debug.assert(list !== null);
const idx = list.indexOf(conn);
Debug.assert(idx !== -1);
list.splice(idx, 1);
if(list.length === 0)
{
this.delete(key);
}
}
map(fn)
{
const arr = [];
this.forEach(c => arr.push(fn(c)));
return arr;
}
forEach(fn)
{
for(let connections of this.values())
{
connections.forEach(fn);
}
}
}
class ConnectCallback
{
constructor(f, endpoints, more, selType)
{
this._factory = f;
this._endpoints = endpoints;
this._hasMore = more;
this._selType = selType;
this._promise = new Ice.Promise();
this._index = 0;
this._current = null;
}
//
// Methods from ConnectionI_StartCallback
//
connectionStartCompleted(connection)
{
connection.activate();
this._factory.finishGetConnection(this._endpoints, this._current, connection, this);
}
connectionStartFailed(connection, ex)
{
Debug.assert(this._current !== null);
if(this.connectionStartFailedImpl(ex))
{
this.nextEndpoint();
}
}
setConnection(connection)
{
//
// Callback from the factory: the connection to one of the callback
// connectors has been established.
//
this._promise.resolve(connection);
this._factory.decPendingConnectCount(); // Must be called last.
}
setException(ex)
{
//
// Callback from the factory: connection establishment failed.
//
this._promise.reject(ex);
this._factory.decPendingConnectCount(); // Must be called last.
}
hasEndpoint(endpoint)
{
return this.findEndpoint(endpoint) !== -1;
}
findEndpoint(endpoint)
{
return this._endpoints.findIndex(value => endpoint.equals(value));
}
removeEndpoints(endpoints)
{
endpoints.forEach(endpoint =>
{
let idx = this.findEndpoint(endpoint);
if(idx !== -1)
{
this._endpoints.splice(idx, 1);
}
});
this._index = 0;
return this._endpoints.length === 0;
}
removeFromPending()
{
this._factory.removeFromPending(this, this._endpoints);
}
start()
{
try
{
//
// Notify the factory that there's an async connect pending. This is necessary
// to prevent the outgoing connection factory to be destroyed before all the
// pending asynchronous connects are finished.
//
this._factory.incPendingConnectCount();
}
catch(ex)
{
this._promise.reject(ex);
return;
}
this.getConnection();
return this._promise;
}
getConnection()
{
try
{
//
// Ask the factory to get a connection.
//
const connection = this._factory.getConnection(this._endpoints, this);
if(connection === null)
{
//
// A null return value from getConnection indicates that the connection
// is being established and that everthing has been done to ensure that
// the callback will be notified when the connection establishment is
// done.
//
return;
}
this._promise.resolve(connection);
this._factory.decPendingConnectCount(); // Must be called last.
}
catch(ex)
{
this._promise.reject(ex);
this._factory.decPendingConnectCount(); // Must be called last.
}
}
nextEndpoint()
{
const start = (connection) =>
{
connection.start().then(
() =>
{
this.connectionStartCompleted(connection);
},
ex =>
{
this.connectionStartFailed(connection, ex);
});
};
while(true)
{
const traceLevels = this._factory._instance.traceLevels();
try
{
Debug.assert(this._index < this._endpoints.length);
this._current = this._endpoints[this._index++];
if(traceLevels.network >= 2)
{
let s = [];
s.push("trying to establish ");
s.push(this._current.protocol());
s.push(" connection to ");
s.push(this._current.toConnectorString());
this._factory._instance.initializationData().logger.trace(traceLevels.networkCat, s.join(""));
}
start(this._factory.createConnection(this._current.connect(), this._current));
}
catch(ex)
{
if(traceLevels.network >= 2)
{
let s = [];
s.push("failed to establish ");
s.push(this._current.protocol());
s.push(" connection to ");
s.push(this._current.toString());
s.push("\n");
s.push(ex.toString());
this._factory._instance.initializationData().logger.trace(traceLevels.networkCat, s.join(""));
}
if(this.connectionStartFailedImpl(ex))
{
continue;
}
}
break;
}
}
connectionStartFailedImpl(ex)
{
if(ex instanceof Ice.LocalException)
{
this._factory.handleConnectionException(ex, this._hasMore || this._index < this._endpoints.length);
if(ex instanceof Ice.CommunicatorDestroyedException) // No need to continue.
{
this._factory.finishGetConnectionEx(this._endpoints, ex, this);
}
else if(this._index < this._endpoints.length) // Try the next endpoint.
{
return true;
}
else
{
this._factory.finishGetConnectionEx(this._endpoints, ex, this);
}
}
else
{
this._factory.finishGetConnectionEx(this._endpoints, ex, this);
}
return false;
}
}
|