File: PeerNeighborManager.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (1725 lines) | stat: -rw-r--r-- 68,595 bytes parent folder | download
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Net;
    using System.Runtime;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using System.ServiceModel.Diagnostics;
    using System.ServiceModel.Dispatcher;
    using System.Threading;

    // Neighbor Manager is responsible for managing a set of neighbors for a node.
    class PeerNeighborManager
    {
        public event EventHandler<PeerNeighborCloseEventArgs> NeighborClosed;
        public event EventHandler<PeerNeighborCloseEventArgs> NeighborClosing;
        public event EventHandler NeighborConnected;
        public event EventHandler NeighborOpened;
        public event EventHandler Offline;
        public event EventHandler Online;

        // Delegate to determine if neighbor manager is closing or closed
        delegate bool ClosedCallback();

        enum State
        {
            Created,
            Opened,
            ShuttingDown,
            Shutdown,
            Closed,
        }

        PeerNodeConfig config;

        //
        // Contains the neighbors in connected state
        // We maintain a connectedNeighborList in addition to neighborList for two reasons:
        // (a) Several operations are on connected neighbors 
        // (b) To correctly handle online/offline conditions
        //
        List<IPeerNeighbor> connectedNeighborList;

        bool isOnline;
        PeerIPHelper ipHelper;
        List<PeerNeighbor> neighborList;    // contains all the neighbors known to neighbor manager
        ManualResetEvent shutdownEvent;
        State state;
        object thisLock;
        PeerNodeTraceRecord traceRecord;
        PeerService service;
        Binding serviceBinding;
        IPeerNodeMessageHandling messageHandler;

        public PeerNeighborManager(PeerIPHelper ipHelper, PeerNodeConfig config)
            :
            this(ipHelper, config, null) { }
        public PeerNeighborManager(PeerIPHelper ipHelper, PeerNodeConfig config, IPeerNodeMessageHandling messageHandler)
        {
            Fx.Assert(ipHelper != null, "Non-null ipHelper is expected");
            Fx.Assert(config != null, "Non-null Config is expected");

            this.neighborList = new List<PeerNeighbor>();
            this.connectedNeighborList = new List<IPeerNeighbor>();
            this.ipHelper = ipHelper;
            this.messageHandler = messageHandler;
            this.config = config;
            this.thisLock = new object();
            this.traceRecord = new PeerNodeTraceRecord(config.NodeId);
            this.state = State.Created;
        }

        // Returns the count of connected neighbors
        public int ConnectedNeighborCount
        {
            get
            {
                return this.connectedNeighborList.Count;
            }
        }

        public int NonClosingNeighborCount
        {
            get
            {
                int count = 0;
                foreach (PeerNeighbor neighbor in this.connectedNeighborList)
                {
                    if (!neighbor.IsClosing) count++;
                }
                return count;
            }
        }

        // Returns true if Neighbor Manager is online 
        // (i.e., has one or more connected neighbors)
        public bool IsOnline
        {
            get
            {
                return this.isOnline;
            }
        }

        // Returns the count of connected neighbors
        public int NeighborCount
        {
            get
            {
                return this.neighborList.Count;
            }
        }

        object ThisLock
        {
            get
            {
                return this.thisLock;
            }
        }

        // Ungracefully shutdown the neighbor manager
        void Abort(PeerNeighbor[] neighbors)
        {
            foreach (PeerNeighbor neighbor in neighbors)
                neighbor.Abort(PeerCloseReason.LeavingMesh, PeerCloseInitiator.LocalNode);
        }

        public IAsyncResult BeginOpenNeighbor(PeerNodeAddress remoteAddress, TimeSpan timeout, AsyncCallback callback, object asyncState)
        {
            ThrowIfNotOpen();

            // It's okay if neighbor manager is shutdown and closed after the above check 
            // because the new neighbor is only added to neighborList in NeighborOpened 
            // handler if the neighbor manager is still open.

            // Sort the IP addresses
            ReadOnlyCollection<IPAddress> sortedAddresses = this.ipHelper.SortAddresses(remoteAddress.IPAddresses);
            PeerNodeAddress address = new PeerNodeAddress(remoteAddress.EndpointAddress, sortedAddresses);
            return BeginOpenNeighborInternal(address, timeout, callback, asyncState);
        }

        internal IAsyncResult BeginOpenNeighborInternal(PeerNodeAddress remoteAddress, TimeSpan timeout, AsyncCallback callback, object asyncState)
        {
            PeerNeighbor neighbor = new PeerNeighbor(this.config, this.messageHandler);
            RegisterForNeighborEvents(neighbor);

            return new NeighborOpenAsyncResult(neighbor, remoteAddress, this.serviceBinding, this.service,
                new ClosedCallback(Closed), timeout, callback, asyncState);
        }

        // Cleanup after shutdown
        void Cleanup(bool graceful)
        {
            lock (ThisLock)
            {
                // In case of g----ful shutdown, we wait for neighbor list to become empty. connectedNeighborList should become
                // empty as well.
                if (graceful)
                {
                    Fx.Assert(this.neighborList.Count == 0, "neighbor count should be 0");
                    Fx.Assert(this.connectedNeighborList.Count == 0, "Connected neighbor count should be 0");

                    // shutdownEvent is only relevant for a g----ful close. And should be closed by the thread
                    // performing g----ful close
                    if (this.shutdownEvent != null)
                        this.shutdownEvent.Close();
                }
                this.state = State.Shutdown;
            }
        }

        // To clear the neighbor lists in case of unexpected exceptions during shutdown
        void ClearNeighborList()
        {
            lock (ThisLock)
            {
                this.neighborList.Clear();
                this.connectedNeighborList.Clear();
            }
        }

        // Close the neighbor manager. It should be called after Shutdown(). 
        // Can also be called before Open.
        public void Close()
        {
            lock (ThisLock)
            {
                this.state = State.Closed;
            }
        }

        // Returns true if neighbor manager is closing or closed
        bool Closed()
        {
            return this.state != State.Opened;
        }

        //
        // Close the specified neighbor. Ok to call multiple times, but NeighborClosing 
        // and NeighborClosed events are fired just once.
        // If the closeReason specified is InvalidNeighbor, it will be closed ungracefully
        //
        public void CloseNeighbor(IPeerNeighbor neighbor, PeerCloseReason closeReason,
            PeerCloseInitiator closeInitiator)
        {
            CloseNeighbor(neighbor, closeReason, closeInitiator, null);
        }

        public void CloseNeighbor(IPeerNeighbor neighbor, PeerCloseReason closeReason,
            PeerCloseInitiator closeInitiator, Exception closeException)
        {
            PeerNeighbor nbr = (PeerNeighbor)neighbor;

            lock (ThisLock)
            {
                if (!(this.state != State.Created))
                {
                    throw Fx.AssertAndThrow("Neighbor Manager is not expected to be in Created state");
                }

                // Check that the neighbor is known to neighbor manager
                if (!this.neighborList.Contains(nbr))
                    return;
            }

            // initiate closing of the neighbor
            if (closeReason != PeerCloseReason.InvalidNeighbor)
            {
                if (!nbr.IsClosing)
                    InvokeAsyncNeighborClose(nbr, closeReason, closeInitiator, closeException, null);
            }
            else    // Call abort even if neighbor is already closing
            {
                nbr.Abort(closeReason, closeInitiator);
            }
        }

        public IPeerNeighbor EndOpenNeighbor(IAsyncResult result)
        {
            return NeighborOpenAsyncResult.End(result);
        }

        static void FireEvent(EventHandler handler, PeerNeighborManager manager)
        {
            if (handler != null)
                handler(manager, EventArgs.Empty);
        }

        static void FireEvent(EventHandler handler, PeerNeighbor neighbor)
        {
            if (handler != null)
                handler(neighbor, EventArgs.Empty);
        }

        static void FireEvent(EventHandler<PeerNeighborCloseEventArgs> handler,
            PeerNeighbor neighbor, PeerCloseReason closeReason,
            PeerCloseInitiator closeInitiator, Exception closeException)
        {
            if (handler != null)
            {
                PeerNeighborCloseEventArgs args = new PeerNeighborCloseEventArgs(
                    closeReason, closeInitiator, closeException);
                handler(neighbor, args);
            }
        }

        // Find a duplicate neighbor matching the nodeId
        public IPeerNeighbor FindDuplicateNeighbor(ulong nodeId)
        {
            return FindDuplicateNeighbor(nodeId, null);
        }

        // Find a duplicate neighbor (excluding skipNeighbor) matching the nodeID.
        public IPeerNeighbor FindDuplicateNeighbor(ulong nodeId, IPeerNeighbor skipNeighbor)
        {
            PeerNeighbor duplicateNeighbor = null;

            if (nodeId != PeerTransportConstants.InvalidNodeId)
            {
                lock (ThisLock)
                {
                    foreach (PeerNeighbor neighbor in this.neighborList)
                    {
                        // We restrict search to neighbors that are not yet closing.
                        if (neighbor != (PeerNeighbor)skipNeighbor && neighbor.NodeId == nodeId &&
                            !neighbor.IsClosing &&
                            neighbor.State < PeerNeighborState.Disconnecting)
                        {
                            duplicateNeighbor = neighbor;
                            break;
                        }
                    }
                }
            }
            return duplicateNeighbor;
        }

        public bool PingNeighbor(IPeerNeighbor peer)
        {
            bool result = true;
            Message message = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, PeerStrings.PingAction);
            try
            {
                peer.Ping(message);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e)) throw;
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                peer.Abort(PeerCloseReason.InternalFailure, PeerCloseInitiator.LocalNode);
                result = false;
            }
            return result;

        }

        public void PingNeighbors()
        {
            List<IPeerNeighbor> neighbors = GetConnectedNeighbors();
            foreach (IPeerNeighbor neighbor in neighbors)
            {
                PingNeighbor(neighbor);
            }
        }

        // Find a duplicate neighbor matching the address
        public IPeerNeighbor FindDuplicateNeighbor(PeerNodeAddress address)
        {
            return FindDuplicateNeighbor(address, null);
        }

        // Find a duplicate neighbor (excluding skipNeighbor) matching the address.
        public IPeerNeighbor FindDuplicateNeighbor(PeerNodeAddress address, IPeerNeighbor skipNeighbor)
        {
            PeerNeighbor duplicateNeighbor = null;

            lock (ThisLock)
            {
                foreach (PeerNeighbor neighbor in this.neighborList)
                {
                    // We restrict search to neighbors that are not yet closing.
                    if (neighbor != (PeerNeighbor)skipNeighbor &&
                        neighbor.ListenAddress != null &&
                        neighbor.ListenAddress.ServicePath == address.ServicePath &&
                        !neighbor.IsClosing &&
                        neighbor.State < PeerNeighborState.Disconnecting)
                    {
                        duplicateNeighbor = neighbor;
                        break;
                    }
                }
            }
            return duplicateNeighbor;
        }

        // Returns a copy of the list of connected neighbors.
        public List<IPeerNeighbor> GetConnectedNeighbors()
        {
            lock (ThisLock)
            {
                return new List<IPeerNeighbor>(this.connectedNeighborList);
            }
        }

        // Used to retrieve a neighbor given the proxy.
        // Maps the proxy from the incoming message's service context to a neighbor instance.
        public IPeerNeighbor GetNeighborFromProxy(IPeerProxy proxy)
        {
            PeerNeighbor neighbor = null;

            lock (ThisLock)
            {
                if (state == State.Opened)
                {
                    // Find the neighbor containing the specified proxy.
                    foreach (PeerNeighbor nbr in this.neighborList)
                    {
                        if (nbr.Proxy == proxy)
                        {
                            neighbor = nbr;
                            break;
                        }
                    }
                }
            }

            return neighbor;
        }

        // Calls neighbor.BeginClose or EndClose and catches appropriate exceptions for any cleanup.
        // We use a single method for both BeginClose and EndClose processing since exception handling
        // is very similar in both cases.
        void InvokeAsyncNeighborClose(PeerNeighbor neighbor, PeerCloseReason closeReason,
            PeerCloseInitiator closeInitiator, Exception closeException, IAsyncResult endResult)
        {
            // initiate invoking BeginClose or EndClose
            try
            {
                if (endResult == null)
                {
                    IAsyncResult beginResult = neighbor.BeginClose(closeReason, closeInitiator,
                                        closeException, Fx.ThunkCallback(new AsyncCallback(OnNeighborClosedCallback)), neighbor);
                    if (beginResult.CompletedSynchronously)
                        neighbor.EndClose(beginResult);
                }
                else
                {
                    neighbor.EndClose(endResult);
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e)) throw;
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);

                neighbor.TraceEventHelper(TraceEventType.Warning, TraceCode.PeerNeighborCloseFailed, SR.GetString(SR.TraceCodePeerNeighborCloseFailed), e);
                // May get InvalidOperationException or ObjectDisposedException due to simultaneous close from both sides (and autoclose is enabled)
                if (e is InvalidOperationException || e is CommunicationException || e is TimeoutException)
                {
                    neighbor.Abort();
                }
                else
                {
                    throw;
                }
            }
        }

        //
        // Handler for processing neighbor closed event.
        //
        // We should allow this event to be processed even if the neighbor manager is shutting
        // down because neighbor manager will be waiting on the shutdown event which is set in 
        // this handler once the last neighbor's close event is processed.
        //
        void OnNeighborClosed(object source, EventArgs args)
        {
            RemoveNeighbor((PeerNeighbor)source);
        }

        // Callback that is invoked when BeginClose completes.
        void OnNeighborClosedCallback(IAsyncResult result)
        {
            if (!result.CompletedSynchronously)
            {
                // Call neighbor.EndClose -- PeerCloseReason and PeerCloseInitiator are dummy values
                InvokeAsyncNeighborClose((PeerNeighbor)result.AsyncState, PeerCloseReason.None,
                    PeerCloseInitiator.LocalNode, null, result);
            }
        }

        // Handles neighbor disconnecting or disconnected events
        void OnNeighborClosing(object source, EventArgs args)
        {
            //
            // Remove the neighbor from connected list. But closed and offline events are
            // fired upon processing closed event. If, due to thread scheduling issues,
            // closed handler executes before this handler, it will have already done the
            // work and Remove() below is a NOP.
            //
            lock (ThisLock)
            {
                this.connectedNeighborList.Remove((IPeerNeighbor)source);
            }
        }

        // handler to process neighbor connected event
        void OnNeighborConnected(object source, EventArgs args)
        {
            PeerNeighbor neighbor = (PeerNeighbor)source;
            bool fireConnected = false;
            bool fireOnline = false;

            // we may get this event after the neighbor has been closed. So, we check to see if
            // the neighbor exists in the neighbor list before processing the event.
            lock (ThisLock)
            {
                if (this.neighborList.Contains(neighbor))
                {
                    fireConnected = true;

                    // Add the neighbor to connected list and determine if online should be fired
                    this.connectedNeighborList.Add(neighbor);
                    if (!this.isOnline)
                    {
                        // Fire online event
                        this.isOnline = true;
                        fireOnline = true;
                    }
                }
            }

            if (fireConnected)
            {
                FireEvent(NeighborConnected, neighbor);
            }
            else
                neighbor.TraceEventHelper(TraceEventType.Warning, TraceCode.PeerNeighborNotFound, SR.GetString(SR.TraceCodePeerNeighborNotFound));

            if (fireOnline)
            {
                if (DiagnosticUtility.ShouldTraceInformation)
                {
                    TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerNeighborManagerOnline,
                        SR.GetString(SR.TraceCodePeerNeighborManagerOnline), this.traceRecord, this, null);
                }
                FireEvent(Online, this);
            }
        }

        // handler to process neighbor opened event
        void OnNeighborOpened(object source, EventArgs args)
        {
            PeerNeighbor neighbor = (PeerNeighbor)source;
            bool accept = false;

            lock (ThisLock)
            {
                // Add the neighbor to neighborList if neighbor manager is still open
                if (this.state == State.Opened)
                {
                    // StateManager assures that neighbor Opened and Closed events are 
                    // serialized. So, we should never have to process a closed event handler 
                    // before opened is complete.
                    if (!(neighbor.State == PeerNeighborState.Opened))
                    {
                        throw Fx.AssertAndThrow("Neighbor expected to be in Opened state");
                    }
                    this.neighborList.Add(neighbor);
                    accept = true;
                }
            }
            if (accept)
            {
                FireEvent(NeighborOpened, neighbor);
            }
            else                // close the neighbor ungracefully
            {
                neighbor.Abort();
                neighbor.TraceEventHelper(TraceEventType.Warning, TraceCode.PeerNeighborNotAccepted, SR.GetString(SR.TraceCodePeerNeighborNotAccepted));
            }
        }

        // Opens the neighbor manager. When this method returns the neighbor manager is ready 
        // to accept incoming neighbor requests and to establish outgoing neighbors.
        public void Open(Binding serviceBinding, PeerService service)
        {
            Fx.Assert(serviceBinding != null, "serviceBinding must not be null");
            Fx.Assert(service != null, "service must not be null");

            lock (ThisLock)
            {
                this.service = service;
                this.serviceBinding = serviceBinding;
                if (!(this.state == State.Created))
                {
                    throw Fx.AssertAndThrow("Neighbor Manager is expected to be in Created state");
                }
                this.state = State.Opened;
            }
        }

        // Process an inbound channel 
        public bool ProcessIncomingChannel(IClientChannel channel)
        {
            bool accepted = false;
            IPeerProxy proxy = (IPeerProxy)channel;

            Fx.Assert(GetNeighborFromProxy(proxy) == null, "Channel should not map to an existing neighbor");
            if (this.state == State.Opened)
            {
                // It is okay if neighbor manager is closed after the above check because the 
                // new neighbor is only added to neighborList in neighbor Opened handler if the 
                // neighbor manager is still open.
                PeerNeighbor neighbor = new PeerNeighbor(this.config, this.messageHandler);
                RegisterForNeighborEvents(neighbor);
                neighbor.Open(proxy);
                accepted = true;
            }
            else
            {
                if (DiagnosticUtility.ShouldTraceWarning)
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.PeerNeighborNotAccepted,
                        SR.GetString(SR.TraceCodePeerNeighborNotAccepted), this.traceRecord, this, null);
                }
            }

            return accepted;
        }

        void RegisterForNeighborEvents(PeerNeighbor neighbor)
        {
            neighbor.Opened += OnNeighborOpened;
            neighbor.Connected += OnNeighborConnected;
            neighbor.Closed += OnNeighborClosed;

            // We want the neighbor to call Closing handlers directly, so we delegate
            neighbor.Closing += this.NeighborClosing;

            // Disconnecting and Disconnected are treated the same way
            neighbor.Disconnecting += OnNeighborClosing;
            neighbor.Disconnected += OnNeighborClosing;
        }

        // Remove neighbor from the list and fire relevant events
        void RemoveNeighbor(PeerNeighbor neighbor)
        {
            bool fireClosed = false;
            bool fireOffline = false;

            lock (ThisLock)
            {
                if (this.neighborList.Contains(neighbor))
                {
                    fireClosed = true;

                    // Remove neighbor from our lists and determine if offline should be fired.
                    this.neighborList.Remove(neighbor);
                    this.connectedNeighborList.Remove(neighbor);
                    if (this.isOnline && this.connectedNeighborList.Count == 0)
                    {
                        this.isOnline = false;
                        fireOffline = true;
                    }
                    // If in the process of shutting down neighbor manager, signal completion 
                    // upon closing of the last remaining neighbor
                    if (this.neighborList.Count == 0 && this.shutdownEvent != null)
                    {
                        this.shutdownEvent.Set();
                    }
                }
            }

            // Fire events
            if (fireClosed)
            {
                FireEvent(NeighborClosed, neighbor, neighbor.CloseReason,
                        neighbor.CloseInitiator, neighbor.CloseException);
            }
            else
            {
                if (DiagnosticUtility.ShouldTraceWarning)
                {
                    neighbor.TraceEventHelper(TraceEventType.Warning, TraceCode.PeerNeighborNotFound, SR.GetString(SR.TraceCodePeerNeighborNotFound));
                }
            }
            if (fireOffline)
            {
                if (DiagnosticUtility.ShouldTraceInformation)
                {
                    TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerNeighborManagerOffline,
                        SR.GetString(SR.TraceCodePeerNeighborManagerOffline), this.traceRecord, this, null);
                }
                FireEvent(Offline, this);
            }
        }

        //
        // Shutdown the neighbor manager. Shutdown should be called prior to Close(). It stops
        // processing inbound neighbor sessions and closes all the neighbors. Outbound neighbor
        // sessions are also disabled as a result of setting the state to ShuttingDown
        // (and then Shutdown).
        //
        public void Shutdown(bool graceful, TimeSpan timeout)
        {
            PeerNeighbor[] neighbors = null;
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            try
            {
                lock (ThisLock)
                {
                    if (this.state == State.Shutdown || this.state == State.Closed)
                        return;
                    this.state = State.ShuttingDown;

                    // Create a copy of neighbor list in order to close neighbors outside lock.
                    neighbors = this.neighborList.ToArray();

                    // In case of g----ful shutdown, if there are any neighbors to close, create an event 
                    // to wait until they are closed
                    if (graceful && neighbors.Length > 0)
                        this.shutdownEvent = new ManualResetEvent(false);
                }

                // Close each neighbor. Do this outside the lock due to Closing and Closed event handlers being invoked
                if (graceful)
                    Shutdown(neighbors, timeoutHelper.RemainingTime());
                else
                    Abort(neighbors);
            }
            catch (Exception e)
            {
                // Purge neighbor list in case of unexpected exceptions
                if (Fx.IsFatal(e)) throw;
                try
                {
                    ClearNeighborList();
                }
                catch (Exception ee)
                {
                    if (Fx.IsFatal(ee)) throw;
                    DiagnosticUtility.TraceHandledException(ee, TraceEventType.Information);
                }
                throw;
            }
            finally
            {
                Cleanup(graceful);
            }
        }

        // G----ful shutdown
        void Shutdown(PeerNeighbor[] neighbors, TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            foreach (PeerNeighbor neighbor in neighbors)
                CloseNeighbor(neighbor, PeerCloseReason.LeavingMesh, PeerCloseInitiator.LocalNode, null);

            // Wait for all the neighbors to close (the event object is set when the last 
            // neighbor is closed). Specify a timeout for wait event handle in case event.Set
            // fails for some reason (it doesn't throw exception). Bail out of the loop when 
            // the neighbor count reaches 0. This ensures that Shutdown() doesn't hang.
            if (neighbors.Length > 0)
            {
                if (!TimeoutHelper.WaitOne(this.shutdownEvent, timeoutHelper.RemainingTime()))
                {
                    Abort(neighbors);   // abort neighbors that haven't been closed yet
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException());
                }
            }
        }

        void ThrowIfNotOpen()
        {
            if (!(this.state != State.Created))
            {
                throw Fx.AssertAndThrow("Neighbor manager not expected to be in Created state");
            }
            if (Closed())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.ToString()));
            }
        }

        class PeerNeighbor : IPeerNeighbor, IInputSessionShutdown
        {
            public event EventHandler Closed;
            public event EventHandler<PeerNeighborCloseEventArgs> Closing;
            public event EventHandler Connected;
            public event EventHandler Disconnected;
            public event EventHandler Disconnecting;
            public event EventHandler Opened;

            ChannelFactory<IPeerProxy> channelFactory;

            // Used after closing the neighbor to find details of the close reason and who 
            // initiated closing.
            Exception closeException;
            PeerCloseInitiator closeInitiator;
            PeerCloseReason closeReason;

            PeerNodeConfig config;
            IPAddress connectIPAddress;         // relevant for initiator neighbor. Indicates the IP address used for connection
            ExtensionCollection<IPeerNeighbor> extensions;
            bool initiator;
            bool isClosing;                     // If true, the neighbor is being closed or already closed
            PeerNodeAddress listenAddress;      // The address that the remote endpoint is listening on
            ulong nodeId;                       // The nodeID of the remote endpoint
            IPeerProxy proxy;                   // Proxy channel to talk to the remote endpoint
            IClientChannel proxyChannel;        // To access inner Channel from proxy w/o casting
            PeerNeighborState state;            // Current state of the neighbor
            object thisLock = new object();
            IPeerNodeMessageHandling messageHandler;
            UtilityExtension utility;

            // Dictates if attempt to set neighbor state should throw exception on failure.
            enum SetStateBehavior
            {
                ThrowException,
                TrySet,
            }

            public PeerNeighbor(PeerNodeConfig config,
                                IPeerNodeMessageHandling messageHandler)
            {
                this.closeReason = PeerCloseReason.None;
                this.closeInitiator = PeerCloseInitiator.LocalNode;
                this.config = config;
                this.state = PeerNeighborState.Created;
                this.extensions = new ExtensionCollection<IPeerNeighbor>(this, thisLock);
                this.messageHandler = messageHandler;
            }

            public IPAddress ConnectIPAddress
            {
                get
                {
                    return this.connectIPAddress;
                }
                set
                {
                    this.connectIPAddress = value;
                }
            }

            // To retrieve reason for closing the neighbor
            public PeerCloseReason CloseReason
            {
                get
                {
                    return this.closeReason;
                }
            }

            // Indicates if close was initiated by local or remote node
            public PeerCloseInitiator CloseInitiator
            {
                get
                {
                    return this.closeInitiator;
                }
            }

            // If an exception during processing caused the neighbor to be closed
            public Exception CloseException
            {
                get
                {
                    return this.closeException;
                }
            }

            public IExtensionCollection<IPeerNeighbor> Extensions
            {
                get
                {
                    return extensions;
                }
            }

            // Returns true if the neighbor is currently closing or already closed
            public bool IsClosing
            {
                get
                {
                    return isClosing;
                }
            }

            // Returns true if neighbor is in connected, synchronizing, or synchronized states
            public bool IsConnected
            {
                get
                {
                    return PeerNeighborStateHelper.IsConnected(this.state);
                }
            }

            // NOTE: If the property is accessed before the neighbor transitions to connected 
            // state, the returned listen address may be null for the accepting neighbor.
            public PeerNodeAddress ListenAddress
            {
                get
                {
                    // Return a copy since the scope ID is settable
                    PeerNodeAddress address = this.listenAddress;
                    if (address != null)
                        return new PeerNodeAddress(address.EndpointAddress, PeerIPHelper.CloneAddresses(address.IPAddresses, true));
                    else
                        return address;
                }
                set
                {

                    lock (ThisLock)
                    {
                        if (!(!this.initiator))
                        {
                            throw Fx.AssertAndThrow("Cannot be set for initiator neighbors");
                        }
                        ThrowIfClosed();

                        if (value != null)
                        {
                            this.listenAddress = value;
                        }
                    }
                }
            }

            // Returns true if the neighbor is an initiator
            public bool IsInitiator
            {
                get
                {
                    return this.initiator;
                }
            }

            // Returns the node ID of the neighbor. If this property is accessed before the 
            // neighbor transitions to connected state, the returned node ID may be 0.
            public ulong NodeId
            {
                get
                {
                    return this.nodeId;
                }

                set
                {
                    lock (ThisLock)
                    {
                        ThrowIfClosed();
                        this.nodeId = value;
                    }
                }
            }

            // Returns the proxy for the neighbor (i.e., the channel that SFx maintains to the
            // remote node associated with this neighbor instance).
            public IPeerProxy Proxy
            {
                get
                {
                    return this.proxy;
                }
                set
                {
                    this.proxy = value;
                    this.proxyChannel = (IClientChannel)this.proxy;
                    RegisterForChannelEvents();
                }
            }

            // The only states that are settable are connecting, connected, synchronizing, 
            // synchronized, disconnecting, and disconnected.
            public PeerNeighborState State
            {
                get
                {
                    return this.state;
                }

                set
                {
                    if (!(PeerNeighborStateHelper.IsSettable(value)))
                    {
                        throw Fx.AssertAndThrow("A valid settable state is expected");
                    }
                    SetState(value, SetStateBehavior.ThrowException);
                }
            }

            object ThisLock
            {
                get
                {
                    return this.thisLock;
                }
            }

            // NOTE: Closing handlers not invoked when a neighbor is aborted; but Closed handlers are.
            public void Abort(PeerCloseReason reason, PeerCloseInitiator closeInit)
            {
                lock (ThisLock)
                {
                    // Set close reason etc. if they are not already set.
                    if (!this.isClosing)
                    {
                        this.isClosing = true;
                        this.closeReason = reason;
                        this.closeInitiator = closeInit;
                    }
                }
                Abort();
            }

            public void Abort()
            {
                if (this.channelFactory != null)
                    this.channelFactory.Abort();
                else
                    this.proxyChannel.Abort();
            }

            // Close a neighbor gracefully
            public IAsyncResult BeginClose(PeerCloseReason reason,
                PeerCloseInitiator closeInit, Exception exception,
                AsyncCallback callback, object asyncState)
            {
                bool callClosing = false;

                lock (ThisLock)
                {
                    // Set close reason etc. if they are not already set.
                    if (!this.isClosing)
                    {
                        callClosing = true;
                        this.isClosing = true;
                        this.closeReason = reason;
                        this.closeInitiator = closeInit;
                        this.closeException = exception;
                    }
                }

                // Initiate close, if another thread has not already done so....
                // NOTE: NeighborClosing handlers should not throw any catchable exceptions.
                if (callClosing)
                {
                    EventHandler<PeerNeighborCloseEventArgs> handler = this.Closing;
                    if (handler != null)
                    {
                        try
                        {
                            PeerNeighborCloseEventArgs args = new PeerNeighborCloseEventArgs(
                                reason, closeInitiator, exception);
                            handler(this, args);
                        }
                        catch (Exception e)
                        {
                            if (Fx.IsFatal(e)) throw;
                            Abort();
                            throw;
                        }
                    }
                }

                if (this.channelFactory != null)
                    return this.channelFactory.BeginClose(callback, asyncState);
                else
                    return this.proxyChannel.BeginClose(callback, asyncState);
            }

            // Begin opening of a neighbor channel to 'to'. instanceContext is where the remote 
            // endpoint should send messages to (it will be a reference to PeerNeighborManager).
            public IAsyncResult BeginOpen(PeerNodeAddress remoteAddress, Binding binding,
                PeerService service, ClosedCallback closedCallback, TimeSpan timeout,
                AsyncCallback callback, object asyncState)
            {
                this.initiator = true;
                this.listenAddress = remoteAddress;
                OpenAsyncResult result = new OpenAsyncResult(this, remoteAddress, binding, service,
                    closedCallback, timeout, callback, state);
                return result;
            }

            // Called by OpenAsyncResult
            public IAsyncResult BeginOpenProxy(EndpointAddress remoteAddress, Binding binding,
                InstanceContext instanceContext, TimeSpan timeout, AsyncCallback callback, object state)
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                if (this.channelFactory != null)
                    Abort();    // to close previously created factory, if any

                EndpointAddressBuilder meshEprBuilder = new EndpointAddressBuilder(remoteAddress);
                meshEprBuilder.Uri = config.GetMeshUri();
                this.channelFactory = new DuplexChannelFactory<IPeerProxy>(instanceContext, binding, meshEprBuilder.ToEndpointAddress());
                this.channelFactory.Endpoint.Behaviors.Add(new ClientViaBehavior(remoteAddress.Uri));
                this.channelFactory.Endpoint.Behaviors.Add(new PeerNeighborBehavior(this));
                this.channelFactory.Endpoint.Contract.Behaviors.Add(new PeerOperationSelectorBehavior(this.messageHandler));
                this.config.SecurityManager.ApplyClientSecurity(channelFactory);
                this.channelFactory.Open(timeoutHelper.RemainingTime());
                this.Proxy = this.channelFactory.CreateChannel();

                IAsyncResult result = this.proxyChannel.BeginOpen(timeoutHelper.RemainingTime(), callback, state);
                if (result.CompletedSynchronously)
                    this.proxyChannel.EndOpen(result);

                return result;
            }

            public IAsyncResult BeginSend(Message message,
                AsyncCallback callback, object asyncState)
            {
                return this.proxy.BeginSend(message, callback, asyncState);
            }

            public IAsyncResult BeginSend(Message message,
                TimeSpan timeout, AsyncCallback callback, object asyncState)
            {
                return this.proxy.BeginSend(message, timeout, callback, asyncState);
            }

            public void Send(Message message)
            {
                this.proxy.Send(message);
            }

            // Called to Abort channelFactory in case BeginOpenProxy or EndOpenProxy throw
            public void CleanupProxy()
            {
                this.channelFactory.Abort();
            }

            public void EndClose(IAsyncResult result)
            {
                if (this.channelFactory != null)
                    this.channelFactory.EndClose(result);
                else
                    this.proxyChannel.EndClose(result);
            }

            public void EndOpen(IAsyncResult result)
            {
                OpenAsyncResult.End(result);
            }

            // Called by OpenAsyncResult
            public void EndOpenProxy(IAsyncResult result)
            {
                if (!result.CompletedSynchronously)
                    this.proxyChannel.EndOpen(result);
            }

            public void EndSend(IAsyncResult result)
            {
                this.proxy.EndSend(result);
            }


            public Message RequestSecurityToken(Message request)
            {
                return this.proxy.ProcessRequestSecurityToken(request);
            }

            public void Ping(Message request)
            {
                this.proxy.Ping(request);
            }

            // Service channel closed event handler.
            void OnChannelClosed(object source, EventArgs args)
            {
                if (this.state < PeerNeighborState.Closed)
                    OnChannelClosedOrFaulted(PeerCloseReason.Closed);

                // If the other side closed the channel, abort the factory (if one exists)
                if (this.closeInitiator != PeerCloseInitiator.LocalNode && this.channelFactory != null)
                    this.channelFactory.Abort();
            }

            // Does heavy-lifting of processing closed/faulted events
            void OnChannelClosedOrFaulted(PeerCloseReason reason)
            {
                PeerNeighborState oldState;

                lock (ThisLock)
                {
                    // We don't call SetState here because it should not be called inside lock,
                    // and to avoid race conditions, we need to set the state before the lock 
                    // can be released.
                    oldState = this.state;
                    this.state = PeerNeighborState.Closed;

                    // Set close reason etc. if they are not already set (as a result of local 
                    // node initiating Close)
                    if (!this.isClosing)
                    {
                        this.isClosing = true;
                        this.closeReason = reason;
                        this.closeInitiator = PeerCloseInitiator.RemoteNode;
                    }
                    TraceClosedEvent(oldState);
                }

                // Update traces and counters and notify interested parties
                OnStateChanged(PeerNeighborState.Closed);
            }

            // Service channel faulted event handler.
            void OnChannelFaulted(object source, EventArgs args)
            {
                try
                {
                    OnChannelClosedOrFaulted(PeerCloseReason.Faulted);
                }
                finally
                {
                    Abort();
                }
            }

            // Service channel opened event handler.
            void OnChannelOpened(object source, EventArgs args)
            {
                // TrySetState is not used because it asserts for a settable state
                // and is meant for use by upper layers. Only PeerNeighbor can set
                // the state to Opened. So, it calls SetState directly.
                SetState(PeerNeighborState.Opened, SetStateBehavior.TrySet);
            }

            //
            // Invokes the appropriate state changed event handler.
            // WARNING: This method should not be called within lock.
            //
            void OnStateChanged(PeerNeighborState newState)
            {
                EventHandler handler = null;
                switch (newState)
                {
                    case PeerNeighborState.Opened:
                        handler = this.Opened;
                        break;
                    case PeerNeighborState.Closed:
                        handler = this.Closed;
                        break;
                    case PeerNeighborState.Connected:
                        handler = this.Connected;
                        break;
                    case PeerNeighborState.Disconnecting:
                        handler = this.Disconnecting;
                        break;
                    case PeerNeighborState.Disconnected:
                        handler = this.Disconnected;
                        break;
                }
                if (handler != null)
                    handler(this, EventArgs.Empty);
            }

            // Open an accepting (incoming) neighbor. callbackInstance is where msgs meant for
            // remote endpoint should be sent.
            public void Open(IPeerProxy callbackInstance)
            {
                this.initiator = false;
                this.Proxy = callbackInstance;
            }

            // Register for channel events
            void RegisterForChannelEvents()
            {
                this.state = PeerNeighborState.Created;     // reset state if the previous proxy failed
                this.proxyChannel.Opened += OnChannelOpened;
                this.proxyChannel.Closed += OnChannelClosed;
                this.proxyChannel.Faulted += OnChannelFaulted;
            }

            // WARNING: This method should not be called within the lock -- it may invoke state 
            // changed event handlers
            bool SetState(PeerNeighborState newState, SetStateBehavior behavior)
            {
                bool stateChanged = false;
                PeerNeighborState oldState;

                // Attempt to set the state
                lock (ThisLock)
                {
                    oldState = this.State;
                    if (behavior == SetStateBehavior.ThrowException)
                        ThrowIfInvalidState(newState);
                    if (newState > this.state)
                    {
                        this.state = newState;
                        stateChanged = true;
                        if (DiagnosticUtility.ShouldTraceInformation)
                        {
                            TraceEventHelper(TraceEventType.Information, TraceCode.PeerNeighborStateChanged, SR.GetString(SR.TraceCodePeerNeighborStateChanged), null, null, newState, oldState);
                        }
                    }
                    else
                    {
                        if (DiagnosticUtility.ShouldTraceInformation)
                        {
                            TraceEventHelper(TraceEventType.Information, TraceCode.PeerNeighborStateChangeFailed, SR.GetString(SR.TraceCodePeerNeighborStateChangeFailed), null, null, oldState, newState);
                        }
                    }
                }

                if (stateChanged)
                {
                    // Pass state change notification on to interested subscribers.
                    OnStateChanged(newState);
                }

                return stateChanged;
            }

            // Attempts to set to specified state.
            // Returns true if succeed and false otherwise.
            public bool TrySetState(PeerNeighborState newState)
            {
                if (!(PeerNeighborStateHelper.IsSettable(newState)))
                {
                    throw Fx.AssertAndThrow("A valid settable state is expected");
                }
                return SetState(newState, SetStateBehavior.TrySet);
            }

            public void ThrowIfClosed()
            {
                if (this.state == PeerNeighborState.Closed)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(
                        this.ToString()));
                }
            }

            // Throws if the new state being set on the neighbor is invalid compared to the 
            // current state (such as setting state to connecting when it is already in
            // disconnected state). Also throws if neighbor is already closed.
            // NOTE: This method should be called within the lock.
            void ThrowIfInvalidState(PeerNeighborState newState)
            {
                if (this.state == PeerNeighborState.Closed)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(
                        this.ToString()));
                }
                if (this.state >= newState)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                        SR.GetString(SR.PeerNeighborInvalidState, this.state.ToString(),
                        newState.ToString())));
                }
            }

            public void TraceClosedEvent(PeerNeighborState previousState)
            {
                if (DiagnosticUtility.ShouldTraceInformation)
                {
                    TraceEventType severity = TraceEventType.Information;

                    // Override tracing severity based on close reason
                    switch (this.closeReason)
                    {
                        case PeerCloseReason.InvalidNeighbor:
                        case PeerCloseReason.DuplicateNodeId:
                            severity = TraceEventType.Error;
                            break;

                        case PeerCloseReason.ConnectTimedOut:
                        case PeerCloseReason.InternalFailure:
                        case PeerCloseReason.Faulted:
                            severity = TraceEventType.Warning;
                            break;
                    }

                    PeerNeighborCloseTraceRecord record = new PeerNeighborCloseTraceRecord(
                        this.nodeId, this.config.NodeId, null, null,
                        this.GetHashCode(), this.initiator,
                        PeerNeighborState.Closed.ToString(), previousState.ToString(), null,
                        this.closeInitiator.ToString(), this.closeReason.ToString()
                    );

                    TraceUtility.TraceEvent(severity, TraceCode.PeerNeighborStateChanged,
                        SR.GetString(SR.TraceCodePeerNeighborStateChanged), record, this, this.closeException);
                }
            }

            public void TraceEventHelper(TraceEventType severity, int traceCode, string traceDescription)
            {
                PeerNeighborState nbrState = this.state;
                this.TraceEventHelper(severity, traceCode, traceDescription, null, null, nbrState, nbrState);
            }

            public void TraceEventHelper(TraceEventType severity, int traceCode, string traceDescription, Exception e)
            {
                PeerNeighborState nbrState = this.state;
                this.TraceEventHelper(severity, traceCode, traceDescription, e, null, nbrState, nbrState);
            }

            public void TraceEventHelper(TraceEventType severity, int traceCode, string traceDescription, Exception e,
                string action, PeerNeighborState nbrState, PeerNeighborState previousOrAttemptedState)
            {
                if (DiagnosticUtility.ShouldTrace(severity))
                {
                    string attemptedState = null;
                    string previousState = null;
                    PeerNodeAddress listenAddr = null;
                    IPAddress connectIPAddr = null;

                    if (nbrState >= PeerNeighborState.Opened && nbrState <= PeerNeighborState.Connected)
                    {
                        listenAddr = this.ListenAddress;
                        connectIPAddr = this.ConnectIPAddress;
                    }

                    if (traceCode == TraceCode.PeerNeighborStateChangeFailed)
                        attemptedState = previousOrAttemptedState.ToString();
                    else if (traceCode == TraceCode.PeerNeighborStateChanged)
                        previousState = previousOrAttemptedState.ToString();

                    PeerNeighborTraceRecord record = new PeerNeighborTraceRecord(this.nodeId,
                        this.config.NodeId, listenAddr, connectIPAddr, this.GetHashCode(),
                        this.initiator, nbrState.ToString(), previousState, attemptedState, action);

                    if (severity == TraceEventType.Verbose && e != null)
                        severity = TraceEventType.Information; // need to be >= info for exceptions

                    TraceUtility.TraceEvent(severity, traceCode, traceDescription, record, this, e);
                }
            }

            // Helper class to implement PeerNeighbor's AsyncOpen by iterating over the IPAddress array
            class OpenAsyncResult : AsyncResult
            {
                bool completedSynchronously;
                ClosedCallback closed;
                int currentIndex;           // index into the ipAddress array
                PeerNeighbor neighbor;
                PeerNodeAddress remoteAddress;
                Binding binding;
                PeerService service;
                AsyncCallback onOpen;
                Exception lastException;
                TimeoutHelper timeoutHelper;

                public OpenAsyncResult(PeerNeighbor neighbor, PeerNodeAddress remoteAddress, Binding binding,
                    PeerService service, ClosedCallback closedCallback, TimeSpan timeout,
                    AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    Fx.Assert(remoteAddress != null && remoteAddress.IPAddresses.Count > 0, "Non-empty IPAddress collection expected");

                    this.timeoutHelper = new TimeoutHelper(timeout);
                    this.neighbor = neighbor;
                    this.currentIndex = 0;
                    this.completedSynchronously = true;         // initially
                    this.remoteAddress = remoteAddress;
                    this.service = service;
                    this.binding = binding;
                    this.onOpen = Fx.ThunkCallback(new AsyncCallback(OnOpen));
                    this.closed = closedCallback;
                    BeginOpen();
                }

                void BeginOpen()
                {
                    bool success = false;

                    try
                    {
                        while (this.currentIndex < this.remoteAddress.IPAddresses.Count)
                        {
                            EndpointAddress remoteAddress = PeerIPHelper.GetIPEndpointAddress(
                                        this.remoteAddress.EndpointAddress, this.remoteAddress.IPAddresses[this.currentIndex]);
                            if (this.closed())
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString()));
                            }
                            try
                            {
                                this.neighbor.ConnectIPAddress = this.remoteAddress.IPAddresses[this.currentIndex];
                                IAsyncResult result = this.neighbor.BeginOpenProxy(remoteAddress, binding, new InstanceContext(null, service, false), this.timeoutHelper.RemainingTime(), onOpen, null);
                                if (!result.CompletedSynchronously)
                                {
                                    return;
                                }

                                this.neighbor.EndOpenProxy(result);
                                this.lastException = null;
                                success = true;
                                neighbor.isClosing = false;
                                break;
                            }
#pragma warning suppress 56500 // covered by FxCOP
                            catch (Exception e)
                            {
                                if (Fx.IsFatal(e)) throw;
                                try
                                {
                                    this.neighbor.CleanupProxy();
                                }
                                catch (Exception ee)
                                {
                                    if (Fx.IsFatal(ee)) throw;
                                    DiagnosticUtility.TraceHandledException(ee, TraceEventType.Information);
                                }
                                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                                if (!ContinuableException(e)) throw;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e)) throw;
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                        this.lastException = e;
                    }

                    // Indicate completion to the caller
                    if (success)
                    {
                        Fx.Assert(this.lastException == null, "lastException expected to be null");
                    }
                    else
                    {
                        Fx.Assert(this.lastException != null, "lastException expected to be non-null");
                    }
                    base.Complete(this.completedSynchronously, this.lastException);
                }

                public static void End(IAsyncResult result)
                {
                    AsyncResult.End<OpenAsyncResult>(result);
                }

                // Checks if the exception can be handled
                bool ContinuableException(Exception exception)
                {
                    if (
                            (
                                exception is EndpointNotFoundException
                                || exception is TimeoutException
                            )
                            && timeoutHelper.RemainingTime() > TimeSpan.Zero
                        )
                    {
                        this.lastException = exception;
                        this.currentIndex++;
                        return true;
                    }
                    return false;
                }

                // Open completion callback. If open failed, reattempts with the next IP address in the list
                void OnOpen(IAsyncResult result)
                {
                    Exception exception = null;
                    bool completed = false;

                    if (!result.CompletedSynchronously)
                    {
                        this.completedSynchronously = false;
                        try
                        {
                            this.neighbor.EndOpenProxy(result);
                            completed = true;
                            neighbor.isClosing = false;
                        }
#pragma warning suppress 56500 // covered by FxCOP
                        catch (Exception e)
                        {
                            if (Fx.IsFatal(e)) throw;
                            try
                            {
                                this.neighbor.CleanupProxy();
                            }
                            catch (Exception ee)
                            {
                                if (Fx.IsFatal(ee)) throw;
                                DiagnosticUtility.TraceHandledException(ee, TraceEventType.Information);
                            }
                            exception = e;
                            if (ContinuableException(exception))
                            {
                                // attempt connection with the next IP address
                                try
                                {
                                    BeginOpen();
                                }
                                catch (Exception ee)
                                {
                                    if (Fx.IsFatal(ee)) throw;
                                    DiagnosticUtility.TraceHandledException(ee, TraceEventType.Information);
                                }
                            }
                            else
                            {
                                completed = true;
                            }
                        }
                    }

                    if (completed)
                        base.Complete(this.completedSynchronously, exception);
                }
            }

            #region IInputSessionShutdown Members

            void IInputSessionShutdown.ChannelFaulted(IDuplexContextChannel channel)
            {
                //Noop
            }

            void IInputSessionShutdown.DoneReceiving(IDuplexContextChannel channel)
            {
                //Close it if the neighbor it was connected to has disconnected
                if (channel.State == CommunicationState.Opened)
                {
                    channel.Close();
                }
            }

            #endregion

            public UtilityExtension Utility
            {
                get
                {
                    if (this.utility == null)
                    {
                        this.utility = this.Extensions.Find<UtilityExtension>();
                    }
                    return this.utility;
                }
            }
        }

        // Helper class to implement PeerNeighborManager's async neighbor open
        class NeighborOpenAsyncResult : AsyncResult
        {
            PeerNeighbor neighbor;

            // ClosedCallback is a delegate to determine if caller has closed. If so, we bail out of open operation
            public NeighborOpenAsyncResult(PeerNeighbor neighbor, PeerNodeAddress remoteAddress, Binding binding,
                PeerService service, ClosedCallback closedCallback, TimeSpan timeout, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.neighbor = neighbor;

                IAsyncResult result = null;
                try
                {
                    result = neighbor.BeginOpen(remoteAddress, binding, service, closedCallback, timeout,
                        Fx.ThunkCallback(new AsyncCallback(OnOpen)), null);
                    if (result.CompletedSynchronously)
                    {
                        neighbor.EndOpen(result);
                    }
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e)) throw;
                    neighbor.TraceEventHelper(TraceEventType.Warning, TraceCode.PeerNeighborOpenFailed, SR.GetString(SR.TraceCodePeerNeighborOpenFailed));
                    throw;
                }

                // Indicate [....] completion to the caller
                if (result.CompletedSynchronously)
                    base.Complete(true);
            }

            void OnOpen(IAsyncResult result)
            {
                if (!result.CompletedSynchronously)
                {
                    Exception exception = null;

                    try
                    {
                        this.neighbor.EndOpen(result);
                    }
#pragma warning suppress 56500 // covered by FxCOP
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e)) throw;
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                        neighbor.TraceEventHelper(TraceEventType.Warning, TraceCode.PeerNeighborOpenFailed, SR.GetString(SR.TraceCodePeerNeighborOpenFailed));
                        exception = e;
                    }

                    base.Complete(result.CompletedSynchronously, exception);
                }
            }

            public static IPeerNeighbor End(IAsyncResult result)
            {
                NeighborOpenAsyncResult asyncResult = AsyncResult.End<NeighborOpenAsyncResult>(result);
                return asyncResult.neighbor;
            }
        }
        class PeerNeighborBehavior : IEndpointBehavior
        {
            PeerNeighbor neighbor;

            public PeerNeighborBehavior(PeerNeighbor neighbor)
            {
                this.neighbor = neighbor;
            }

            #region IEndpointBehavior Members

            public void Validate(ServiceEndpoint serviceEndpoint)
            {
            }

            public void AddBindingParameters(ServiceEndpoint serviceEndpoint, BindingParameterCollection bindingParameters)
            {
            }

            public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)
            {
            }

            public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior)
            {
                behavior.DispatchRuntime.InputSessionShutdownHandlers.Add(this.neighbor);
            }

            #endregion
        }

        public IPeerNeighbor SlowestNeighbor()
        {
            List<IPeerNeighbor> neighbors = this.GetConnectedNeighbors();
            IPeerNeighbor slowNeighbor = null;
            UtilityExtension utility = null;
            //if the neighbor has below this number, we wont consider for pruning
            int pending = PeerTransportConstants.MessageThreshold;
            foreach (IPeerNeighbor peer in neighbors)
            {
                utility = peer.Utility;
                if (utility == null || !peer.IsConnected)
                    continue;
                if (utility.PendingMessages > pending)
                {
                    slowNeighbor = peer;
                    pending = utility.PendingMessages;
                }
            }
            return slowNeighbor;
        }

    }
}