Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 | 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 334x 334x 196x 196x 196x 196x 196x 196x 334x 41x 41x 41x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 334x 334x 334x 334x 334x 334x 334x 334x 335x 335x 335x 335x 41x 41x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 334x 3x 334x 334x 335x 335x 335x 335x 41x 41x 243x 243x 243x 41x 41x 114x 114x 114x 41x 41x 41x 41x 139x 138x 138x 138x 138x 138x 138x 139x 139x 41x 41x 138x 138x 138x 138x 138x 138x 41x 41x 1278x 1278x 41x 41x 8x 1x 1x 1x 8x 41x 41x 114x 114x 114x 114x 114x 41x 41x 2510x 2510x 2510x 2510x 51x 51x 51x 51x 2459x 2459x 2459x 2459x 2459x 2459x 2459x 2470x 2435x 2435x 2435x 2435x 2435x 2435x 2435x 2510x 13x 13x 13x 2459x 2459x 2459x 2459x 2459x 2459x 2459x 2510x 2459x 2470x 2435x 2435x 2435x 2459x 2459x 2510x 41x 41x 42x 42x 41x 41x 14x 14x 14x 14x 41x 41x 2x 2x 2x 2x 2x 41x 41x 1x 1x 1x 41x 41x 5x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 5x 41x 41x 942x 942x 942x 942x 942x 1x 1x 942x 942x 942x 942x 1x 1x 1x 941x 941x 868x 868x 941x 941x 942x 1x 1x 942x 1x 1x 1x 1x 942x 41x 41x 6644x 6644x 41x 41x 34x 30x 30x 29x 34x 4x 4x 4x 34x 41x 41x 26x 26x 41x 41x 1x 1x 41x 41x 11x 11x 11x 41x 41x 4222x 4222x 4222x 4222x 4222x 4222x 4222x 4222x 4222x 337x 337x 336x 336x 336x 336x 337x 4222x 3885x 3642x 3642x 15x 15x 15x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3457x 3642x 3642x 3457x 3642x 3457x 3457x 3457x 3457x 3457x 3457x 3642x 3457x 3457x 3457x 3457x 3457x 3457x 3642x 3457x 3457x 3457x 3457x 3642x 3457x 3642x 3x 3x 3642x 3364x 3364x 3454x 3454x 3697x 3885x 3607x 3607x 3607x 3885x 4034x 4222x 578x 487x 578x 244x 244x 243x 243x 243x 243x 243x 243x 4222x 3456x 3456x 3456x 3456x 3454x 3454x 3456x 3456x 2x 2x 2x 3456x 4222x 264x 264x 264x 3699x 3699x 3699x 4218x 1144x 1144x 4222x 41x 41x 3699x 3699x 3699x 3699x 243x 243x 243x 243x 243x 3699x 3699x 3699x 3699x 3451x 2419x 2419x 2419x 3451x 3451x 942x 942x 942x 942x 3451x 3699x 3699x 3699x 2662x 2662x 2662x 2662x 2662x 2662x 2662x 3699x 41x 41x 335x 335x 335x 335x 334x 334x 335x 335x 196x 196x 196x 335x 335x 335x 91x 55x 55x 55x 55x 55x 335x 186x 186x 186x 186x 186x 166x 186x 186x 166x 166x 186x 186x 335x 335x 92x 92x 92x 335x 335x 335x 335x 11x 11x 335x 335x 335x 335x 335x 335x 335x 335x 335x 138x 138x 138x 138x 1x 138x 137x 138x 1x 1x 1x 138x 335x 335x 2x 2x 2x 2x 2x 335x 335x 335x 335x 334x 334x 335x 335x 41x 41x 7848x 7848x 41x 41x 5306x 5306x 41x 41x 482x 1x 1x 481x 482x 482x 482x 482x 41x 41x 1x 1x 1x 41x 41x 41x 41x 41x 41x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 41x 41x 1851x 589x 589x 589x 589x 589x 589x 1x 1x 1x 588x 589x 335x 335x 335x 335x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 335x 589x 589x 589x 589x 1850x 1850x 1851x 1850x 1851x 1850x 1851x 1363x 1363x 1363x 1850x 1850x 1850x 1851x 1851x 1851x 244x 244x 244x 244x 244x 244x 244x 1851x 1851x 243x 243x 243x 243x 1851x 1851x 243x 243x 1851x 1851x 1851x 1851x 449x 449x 57x 57x 392x 392x 1851x 1851x 336x 1x 1x 335x 335x 335x 335x 335x 1851x 1851x 335x 335x 335x 335x 1851x 1851x 1851x 1851x 1792x 1792x 1792x 1851x 195x 195x 195x 1851x 335x 335x 1792x 1792x 1851x 41x 41x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 41x 41x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 41x 41x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 41x 41x 670x 670x 335x 335x 244x 244x 244x 244x 244x 244x 670x 41x 41x 487x 244x 244x 244x 487x 487x 244x 244x 243x 243x 243x 243x 243x 243x 243x 243x 487x 487x 243x 487x 243x 243x 243x 243x 243x 243x 487x 243x 243x 243x 243x 243x 243x 487x 243x 243x 487x 243x 243x 487x 243x 243x 243x 243x 243x 243x 243x 243x 243x 243x 301x 185x 185x 243x 307x 242x 242x 242x 243x 487x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 41x 41x 3547x 3547x 3547x 3547x 2x 2x 2x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3545x 3547x 3543x 3543x 3543x 3543x 2x 2x 2x 2x 2x 3547x 41x 41x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 67x 67x 67x 67x 67x 3454x 3454x 942x 942x 942x 942x 942x 942x 942x 942x 942x 942x 942x 942x 942x 3454x 3454x 3454x 3454x 2422x 2422x 2422x 2422x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2419x 2422x 3x 3x 2422x 2422x 3454x 3454x 23x 23x 23x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 41x 41x 942x 942x 942x 942x 942x 942x 942x 942x 941x 941x 941x 941x 1x 1x 1x 1x 1x 1x 942x 942x 942x 942x 942x 942x 942x 941x 941x 941x 941x 941x 51x 51x 941x 941x 941x 942x 41x 41x 3x 1x 1x 3x 3x 41x 41x 1x 1x 1x 1x 1x 1x 1x 1x 41x 41x 41x 41x 5510x 5510x 5510x 669x 114x 114x 669x 669x 5510x 41x 41x 7493x 7493x 7493x 1443x 1443x 1443x 1443x 1443x 7323x 7493x 41x 41x 3545x 3545x 3545x 681x 681x 681x 681x 681x 3545x 3545x 41x 41x 2x 2x 2x 2x 2x 2x 2x 41x 41x 4765x 4765x 41x 41x 41x 41x 41x 41x 41x 3454x 3454x 3454x 3454x 3454x 3454x 3454x 41x 41x 41x 41x 41x 41x 41x 41x 3547x 3547x 3547x 3547x 3547x 3547x 3547x 3547x 3547x 3547x 3547x 3547x 3547x 3547x 41x 41x 2x 2x 2x 41x 41x 41x 3545x 2457x 2457x 3545x 41x 41x 41x 41x 41x 41x 41x 1088x 1088x 41x 41x 41x 2459x 2459x 41x | // Copyright (c) ZeroC, Inc. import { LocalException } from "./LocalException.js"; import { ObjectAdapterDestroyedException, CommunicatorDestroyedException, CloseConnectionException, ConnectionAbortedException, ConnectionClosedException, ConnectTimeoutException, ConnectionLostException, CloseTimeoutException, FeatureNotSupportedException, MarshalException, UnknownException, ObjectNotExistException, ProtocolException, } from "./LocalExceptions.js"; import { BatchRequestQueue } from "./BatchRequestQueue.js"; import { InputStream } from "./InputStream.js"; import { OutputStream } from "./OutputStream.js"; import { Protocol } from "./Protocol.js"; import { Ice as Ice_Version } from "./Version.js"; const { ProtocolVersion, EncodingVersion } = Ice_Version; import { throwMemoryLimitException } from "./ExUtil.js"; import { Timer } from "./Timer.js"; import { Promise } from "./Promise.js"; import { SocketOperation } from "./SocketOperation.js"; import { TraceUtil } from "./TraceUtil.js"; import { AsyncStatus } from "./AsyncStatus.js"; import { RetryException } from "./RetryException.js"; import { ConnectionFlushBatch, OutgoingAsync } from "./OutgoingAsync.js"; import { IdleTimeoutTransceiverDecorator } from "./IdleTimeoutTransceiverDecorator.js"; import { ObjectAdapter } from "./ObjectAdapter.js"; import { ObjectPrx } from "./ObjectPrx.js"; import { IncomingRequest } from "./IncomingRequest.js"; import "./CurrentExtensions.js"; const StateNotInitialized = 0; const StateNotValidated = 1; const StateActive = 2; // StateHolding is a very transient state in JS: the connection is in StateHolding once the connection establishment // has succeeded and until the outgoing connection factory activates the connection - which is essentially immediate. const StateHolding = 3; const StateClosing = 4; const StateClosingPending = 5; const StateClosed = 6; const StateFinished = 7; function scheduleCloseTimeout(connection) { if (connection._closeTimeout > 0 && connection._closeTimeoutId === undefined) { // Schedules a one-time check. connection._closeTimeoutId = connection._timer.schedule( () => connection.closeTimedOut(), connection._closeTimeout, ); } } export class ConnectionI { constructor(communicator, instance, transceiver, endpoint, adapter, removeFromFactory, options) { this._communicator = communicator; this._instance = instance; this._desc = transceiver.toString(); this._type = transceiver.type(); this._endpoint = endpoint; this._adapter = adapter; this._removeFromFactory = removeFromFactory; this._connectTimeout = options.connectTimeout * 1000; // Seconds to milliseconds this._connectTimeoutId = undefined; this._closeTimeout = options.closeTimeout * 1000; // Seconds to milliseconds. this._closeTimeoutId = undefined; this._inactivityTimeout = options.inactivityTimeout; this._inactivityTimer = undefined; const initData = instance.initializationData(); this._logger = initData.logger; // Cached for better performance. this._traceLevels = instance.traceLevels(); // Cached for better performance. this._timer = instance.timer(); this._hasMoreData = { value: false }; this._warn = initData.properties.getIcePropertyAsInt("Ice.Warn.Connections") > 0; this._nextRequestId = 1; this._messageSizeMax = instance.messageSizeMax(); this._batchRequestQueue = new BatchRequestQueue(instance); this._sendStreams = []; this._readStream = new InputStream(instance, Protocol.currentProtocolEncoding); this._readHeader = false; this._writeStream = new OutputStream(); // temporary stream this._readStreamPos = -1; this._writeStreamPos = -1; // The number of user calls currently executed by the event-loop (servant dispatch, invocation response, etc.). this._upcallCount = 0; // The number of outstanding dispatches. Maintained only while state is StateActive. this._dispatchCount = 0; this._state = StateNotInitialized; this._shutdownInitiated = false; this._initialized = false; this._validated = false; this._asyncRequests = new Map(); // Map<int, OutgoingAsync> this._exception = null; this._startPromise = null; this._closed = undefined; this._finishedPromises = []; if (options.idleTimeout > 0) { transceiver = new IdleTimeoutTransceiverDecorator( transceiver, this, this._timer, options.idleTimeout, options.enableIdleCheck, ); } this._transceiver = transceiver; this._closeCallback = null; } start() { console.assert(this._startPromise === null); try { // The connection might already be closed if the communicator was destroyed. if (this._state >= StateClosed) { console.assert(this._exception !== null); return Promise.reject(this._exception); } this._startPromise = new Promise(); this._transceiver.setCallbacks( () => this.message(SocketOperation.Write), // connected callback () => this.message(SocketOperation.Read), // read callback () => this.message(SocketOperation.Write), // write callback ); if (!this.initialize()) { if (this._connectTimeout > 0) { this._connectTimeoutId = this._timer.schedule(() => { this.connectTimedOut(); }, this._connectTimeout); } } } catch (ex) { const startPromise = this._startPromise; this.exception(ex); return startPromise; } return this._startPromise; } activate() { if (this._state <= StateNotValidated) { return; } this.setState(StateActive); } destroy() { // Called by Communicator.destroy this.setState(StateClosing, new CommunicatorDestroyedException()); } abort() { this.setState( StateClosed, new ConnectionAbortedException("The connection was aborted by the application.", true), ); } close() { if (this._closed === undefined) { this._closed = new Promise(); scheduleCloseTimeout(this); if (this._asyncRequests.size === 0) { this.doApplicationClose(); } } return this._closed; } doApplicationClose() { console.assert(this._state < StateClosing); this.setState( StateClosing, new ConnectionClosedException("The connection was closed gracefully by the application.", true), ); } isActiveOrHolding() { return this._state > StateNotValidated && this._state < StateClosing; } throwException() { if (this._exception !== null) { console.assert(this._state >= StateClosing); throw this._exception; } } waitUntilFinished() { const promise = new Promise(); this._finishedPromises.push(promise); this.checkState(); return promise; } sendAsyncRequest(out, response, batchRequestNum) { let requestId = 0; const ostr = out.getOs(); if (this._exception !== null) { // If the connection is closed before we even have a chance to send our request, we always try to send the // request again. throw new RetryException(this._exception); } console.assert(this._state > StateNotValidated); console.assert(this._state < StateClosing); // Notify the request that it's cancelable with this connection. This will throw if the request is canceled. out.cancelable(this); if (response) { // Create a new unique request ID. requestId = this._nextRequestId++; if (requestId <= 0) { this._nextRequestId = 1; requestId = this._nextRequestId++; } // Fill in the request ID. ostr.pos = Protocol.headerSize; ostr.writeInt(requestId); } else if (batchRequestNum > 0) { ostr.pos = Protocol.headerSize; ostr.writeInt(batchRequestNum); } // We're just about to send a request, so we are not inactive anymore. this.cancelInactivityTimer(); let status; try { status = this.sendMessage(OutgoingMessage.create(out, out.getOs(), requestId)); } catch (ex) { if (ex instanceof LocalException) { this.setState(StateClosed, ex); console.assert(this._exception !== null); throw this._exception; } else { throw ex; } } if (response) { // Add the request to the async requests map. this._asyncRequests.set(requestId, out); } return status; } getBatchRequestQueue() { return this._batchRequestQueue; } flushBatchRequests() { const result = new ConnectionFlushBatch(this, this._communicator, "flushBatchRequests"); result.invoke(); return result; } setCloseCallback(callback) { if (this._state >= StateClosed) { if (callback !== null) { Timer.setImmediate(() => { try { callback(this); } catch (ex) { this._logger.error(`connection callback exception:\n${ex}\n${ex.stack}\n${this._desc}`); } }); } } else { this._closeCallback = callback; } } disableInactivityCheck() { this.cancelInactivityTimer(); this._inactivityTimeout = 0; } asyncRequestCanceled(outAsync, ex) { for (let i = 0; i < this._sendStreams.length; i++) { const o = this._sendStreams[i]; if (o.outAsync === outAsync) { if (o.requestId > 0) { this._asyncRequests.delete(o.requestId); } // If the request is being sent, don't remove it from the send streams, it will be removed once the // sending is finished. o.canceled(); if (i !== 0) { this._sendStreams.splice(i, 1); } outAsync.completedEx(ex); if (this._closed !== undefined && this._state < StateClosing && this._asyncRequests.size === 0) { this.doApplicationClose(); } return; // We're done. } } if (outAsync instanceof OutgoingAsync) { for (const [key, value] of this._asyncRequests) { if (value === outAsync) { this._asyncRequests.delete(key); outAsync.completedEx(ex); if (this._closed !== undefined && this._state < StateClosing && this._asyncRequests.size === 0) { this.doApplicationClose(); } return; // We're done. } } } } sendResponse(response, isTwoWay) { console.assert(this._state > StateNotValidated); try { if (--this._upcallCount === 0) { if (this._state === StateFinished) { this._removeFromFactory(this); } this.checkState(); } if (this._state >= StateClosed) { console.assert(this._exception !== null); throw this._exception; } if (isTwoWay) { this.sendMessage(OutgoingMessage.createForStream(response.outputStream)); } --this._dispatchCount; if (this._state === StateClosing && this._upcallCount === 0) { this.initiateShutdown(); } } catch (ex) { if (ex instanceof LocalException) { this.setState(StateClosed, ex); } else { throw ex; } } } endpoint() { return this._endpoint; } setAdapter(adapter) { if (adapter !== null) { adapter.checkForDestruction(); if (this._state <= StateNotValidated || this._state >= StateClosing) { return; } this._adapter = adapter; } else { if (this._state <= StateNotValidated || this._state >= StateClosing) { return; } this._adapter = null; } } getAdapter() { return this._adapter; } getEndpoint() { return this._endpoint; } createProxy(ident) { ObjectAdapter.checkIdentity(ident); return new ObjectPrx(this._instance.referenceFactory().createFixed(ident, this)); } message(operation) { if (this._state >= StateClosed) { return; } // Keep reading until no more data is available. this._hasMoreData.value = (operation & SocketOperation.Read) !== 0; let info = null; let response = null; try { if ((operation & SocketOperation.Write) !== 0) { if (this._writeStream.buffer.remaining > 0) { console.assert(this._sendStreams.length > 0); const completedSynchronously = this.write(this._writeStream.buffer); if (this._writeStream.buffer.remaining === 0) { // If the write call consumed the complete buffer, we assume the message is sent now for // at-most-once semantics. this._sendStreams[0].isSent = true; } if (!completedSynchronously) { console.assert(!this._writeStream.isEmpty()); return; } console.assert(this._writeStream.buffer.remaining === 0); } else if (this._transceiver instanceof IdleTimeoutTransceiverDecorator) { // The writing of the current message completed, schedule a heartbeat in case the connection has // nothing more to write. this._transceiver.scheduleHeartbeat(); } } if ((operation & SocketOperation.Read) !== 0 && !this._readStream.isEmpty()) { if (this._readHeader) { // Read header if necessary. if (!this.read(this._readStream.buffer)) { // We didn't get enough data to complete the header. return; } console.assert(this._readStream.buffer.remaining === 0); this._readHeader = false; // Connection is validated on first message. This is only used by setState() to check whether or not // we can print a connection warning (a client might close the connection forcefully if the // connection isn't validated, we don't want to print a warning in this case). this._validated = true; const pos = this._readStream.pos; console.assert(pos >= Protocol.headerSize); this._readStream.pos = 0; const magic0 = this._readStream.readByte(); const magic1 = this._readStream.readByte(); const magic2 = this._readStream.readByte(); const magic3 = this._readStream.readByte(); if ( magic0 !== Protocol.magic[0] || magic1 !== Protocol.magic[1] || magic2 !== Protocol.magic[2] || magic3 !== Protocol.magic[3] ) { throw new ProtocolException( `Bad magic in message header: ${magic0.toString(16)} ${magic1.toString(16)} ${magic2.toString(16)} ${magic3.toString(16)}`, ); } const protocolVersion = new ProtocolVersion(); protocolVersion._read(this._readStream); if ( protocolVersion.major != Protocol.currentProtocol.major || protocolVersion.minor != Protocol.currentProtocol.minor ) { throw new MarshalException( `Invalid protocol version in message header: ${protocolVersion.major}.${protocolVersion.minor}`, ); } const encodingVersion = new EncodingVersion(); encodingVersion._read(this._readStream); if ( encodingVersion.major != Protocol.currentProtocolEncoding.major || protocolVersion.minor != Protocol.currentProtocolEncoding.minor ) { throw new MarshalException( `Invalid protocol encoding version in message header: ${encodingVersion.major}.${encodingVersion.minor}`, ); } this._readStream.readByte(); // messageType this._readStream.readByte(); // compress const size = this._readStream.readInt(); if (size < Protocol.headerSize) { throw new MarshalException(`Received Ice message with unexpected size ${size}.`); } if (size > this._messageSizeMax) { throwMemoryLimitException(size, this._messageSizeMax); } if (size > this._readStream.size) { this._readStream.resize(size); } this._readStream.pos = pos; } if (this._readStream.pos != this._readStream.size) { if (!this.read(this._readStream.buffer)) { console.assert(!this._readStream.isEmpty()); return; } console.assert(this._readStream.buffer.remaining === 0); } } if (this._state <= StateNotValidated) { if (this._state === StateNotInitialized && !this.initialize()) { return; } if (this._state <= StateNotValidated && !this.validate()) { return; } // We start out in holding state. this.setState(StateHolding); if (this._startPromise !== null) { ++this._upcallCount; } } else { console.assert(this._state <= StateClosingPending); // We parse messages first, if we receive a close connection message we won't send more messages. if ((operation & SocketOperation.Read) !== 0) { info = this.parseMessage(); } if ((operation & SocketOperation.Write) !== 0) { response = this.sendNextMessage(); if (response !== null) { // The first message in the send queue was a request with a response waiting until the message // was marked as sent. ++this._upcallCount; } } } } catch (ex) { this.setState(StateClosed, ex); return; } this.upcall(info, response); if (this._hasMoreData.value) { Timer.setImmediate(() => this.message(SocketOperation.Read)); // Don't tie up the thread. } } upcall(info, response) { let count = 0; // Notify the factory that the connection establishment and validation has completed. if (this._startPromise !== null) { this._startPromise.resolve(); this._startPromise = null; ++count; } if (response != null) { // A response to a request which was delayed until the request was marked as sent. response.outAsync.completed(response.stream); ++count; } if (info !== null) { if (info.outAsync !== null) { info.outAsync.completed(info.stream); ++count; } if (info.requestCount > 0) { this.dispatchAll(info.stream, info.requestCount, info.requestId, info.adapter); // Don't increase count, the dispatch count is decreased when the incoming reply is sent. } } // Decrease the upcall count. if (count > 0) { this._upcallCount -= count; if (this._upcallCount === 0) { if (this._state === StateClosing) { try { this.initiateShutdown(); } catch (ex) { if (ex instanceof LocalException) { this.setState(StateClosed, ex); } else { throw ex; } } } else if (this._state === StateFinished) { this._removeFromFactory(this); } this.checkState(); } } } finish() { console.assert(this._state === StateClosed); // Cancel the timers to ensure they don't keep the event loop alive. if (this._connectTimeoutId !== undefined) { this._timer.cancel(this._connectTimeoutId); } if (this._closeTimeoutId !== undefined) { this._timer.cancel(this._closeTimeoutId); this._closeTimeoutId = undefined; } const traceLevels = this._traceLevels; if (!this._initialized) { if (traceLevels.network >= 2) { this._logger.trace( traceLevels.networkCat, `failed to establish ${this._endpoint.protocol()} connection\n${this}\n${this._exception}`, ); } } else if (traceLevels.network >= 1) { let s = `closed ${this._endpoint.protocol()} connection\n${this}`; // Trace the cause of most connection closures if ( !( this._exception instanceof CommunicatorDestroyedException || this._exception instanceof ObjectAdapterDestroyedException ) ) { s += `\n${this._exception}`; } this._logger.trace(traceLevels.networkCat, s); } if (this._startPromise !== null) { this._startPromise.reject(this._exception); this._startPromise = null; } if (this._sendStreams.length > 0) { if (!this._writeStream.isEmpty()) { // Return the stream to the outgoing call. This is important for retriable AMI calls, which are not // marshaled again. const message = this._sendStreams[0]; this._writeStream.swap(message.stream); // The current message might have been sent but not yet removed from _sendStreams. We mark it as sent // and remove it from _sendStreams to avoid calling finish on a message that has already been processed. if (message.isSent || message.response !== null) { message.sent(); if (message.response !== null) { // If the response has already been received, process it now. message.outAsync.completed(message.response.stream); } this._sendStreams.shift(); } } // For two-way requests that are not sent, `finished` may be called twice: // the first time because the outgoing message is in the `_sendStreams` set, and the second time because // it's also in the `_asyncRequests` map. This behavior is acceptable; only the first call should be // processed by the `finished` implementation. for (const message of this._sendStreams) { if (message.requestId > 0) { this._asyncRequests.delete(message.requestId); } message.completed(this._exception); } this._sendStreams = []; } for (const request of this._asyncRequests.values()) { request.completedEx(this._exception); } this._asyncRequests.clear(); // Don't wait to be reaped to reclaim memory allocated by read/write streams. this._readStream.clear(); this._readStream.buffer.clear(); this._writeStream.clear(); this._writeStream.buffer.clear(); if (this._closed !== undefined) { if ( this._exception instanceof ConnectionClosedException || this._exception instanceof CloseConnectionException || this._exception instanceof CommunicatorDestroyedException || this._exception instanceof ObjectAdapterDestroyedException ) { this._closed.resolve(); } else { console.assert(this._exception !== null); this._closed.reject(this._exception); } } if (this._closeCallback !== null) { try { this._closeCallback(this); } catch (ex) { this._logger.error(`connection callback exception:\n${ex}\n${this._desc}`); } this._closeCallback = null; } // This must be done last as this will cause waitUntilFinished() to return (and communicator objects such as // the timer might be destroyed too). if (this._upcallCount === 0) { this._removeFromFactory(this); } this.setState(StateFinished); } toString() { return this._desc; } type() { return this._type; } getInfo() { if (this._state >= StateClosed) { throw this._exception; } return this._transceiver.getInfo( this._adapter !== null ? this._adapter.getName() : "", this._endpoint.connectionId(), ); } setBufferSize(rcvSize, sndSize) { if (this._state >= StateClosed) { throw this._exception; } this._transceiver.setBufferSize(rcvSize, sndSize); } exception(ex) { this.setState(StateClosed, ex); } dispatchException(ex, requestCount) { // Fatal exception while invoking a request. Since sendResponse isn't called in case of a fatal exception we // decrement this._upcallCount here. this.setState(StateClosed, ex); if (requestCount > 0) { console.assert(this._upcallCount > requestCount); this._upcallCount -= requestCount; console.assert(this._upcallCount >= 0); if (this._upcallCount === 0) { if (this._state === StateFinished) { this._removeFromFactory(this); } this.checkState(); } } } inactivityCheck(inactivityTimer) { // If the timers are different, it means this inactivityTimer is no longer current. if (inactivityTimer == this._inactivityTimer) { this._inactivityTimer = undefined; inactivityTimer.destroy(); if (this._state == StateActive) { this.setState( StateClosing, new ConnectionClosedException( "connection closed because it remained inactive for longer than the inactivity timeout", ), ); } } // Else this timer was already canceled and disposed. Nothing to do. } setState(state, ex) { if (ex !== undefined) { console.assert(ex instanceof LocalException, ex); // If setState() is called with an exception, then only closed and closing states are permissible. console.assert(state >= StateClosing); if (this._state === state) { // Don't switch twice. return; } if (this._exception === null) { this._exception = ex; // We don't warn if we are not validated. if (this._warn && this._validated) { // Don't warn about certain expected exceptions. if ( !( this._exception instanceof CloseConnectionException || this._exception instanceof ConnectionClosedException || this._exception instanceof CommunicatorDestroyedException || this._exception instanceof ObjectAdapterDestroyedException || (this._exception instanceof ConnectionLostException && this._state === StateClosing) ) ) { this.warning("connection exception", this._exception); } } } // We must set the new state before we notify requests of any exceptions. Otherwise new requests may retry // on a connection that is not yet marked as closed or closing. } // Skip graceful shutdown if we are destroyed before validation. if (this._state <= StateNotValidated && state === StateClosing) { state = StateClosed; } if (this._state === state) { // Don't switch twice. return; } if (state > StateActive) { // Cancel the inactivity timer, if not null. this.cancelInactivityTimer(); } try { switch (state) { case StateNotInitialized: { console.assert(false); break; } case StateNotValidated: { if (this._state !== StateNotInitialized) { console.assert(this._state === StateClosed); return; } // Register to receive validation message. Once validation is complete, a new connection starts out // in the Holding state. We only want to register the transceiver now if we need to receive data in // order to validate the connection. this._transceiver.register(); break; } case StateActive: { console.assert(this._state <= StateHolding); this._transceiver.register(); break; } case StateHolding: console.assert(this._state === StateNotValidated); this._transceiver.unregister(); break; // see comment on StateHolding definition case StateClosing: case StateClosingPending: { // Can't change back from closing pending. if (this._state >= StateClosingPending) { return; } break; } case StateClosed: { if (this._state === StateFinished) { return; } this._batchRequestQueue.destroy(this._exception); this._transceiver.unregister(); this._transceiver.close(); break; } case StateFinished: { console.assert(this._state === StateClosed); this._transceiver.destroy(); break; } default: { console.assert(false); break; } } } catch (ex) { if (ex instanceof LocalException) { this._logger.error(`unexpected connection exception:\n${this._desc}\n${ex.toString()}`); } else { throw ex; } } this._state = state; if (this._state === StateClosing && this._upcallCount === 0) { try { this.initiateShutdown(); } catch (ex) { if (ex instanceof LocalException) { this.setState(StateClosed, ex); } else { throw ex; } } } else if (this._state === StateClosed) { this.finish(); } this.checkState(); } initiateShutdown() { console.assert(this._state === StateClosing && this._upcallCount === 0); if (this._shutdownInitiated) { return; } this._shutdownInitiated = true; // Before we shut down, we send a close connection message. const os = new OutputStream(Protocol.currentProtocolEncoding); os.writeBlob(Protocol.magic); Protocol.currentProtocol._write(os); Protocol.currentProtocolEncoding._write(os); os.writeByte(Protocol.closeConnectionMsg); os.writeByte(0); // compression status: always report 0 for CloseConnection. os.writeInt(Protocol.headerSize); // Message size. scheduleCloseTimeout(this); if ((this.sendMessage(OutgoingMessage.createForStream(os)) & AsyncStatus.Sent) > 0) { this.setState(StateClosingPending); } } idleCheck(idleTimeout) { if (this._state === StateActive || this._state === StateHolding) { this.setState( StateClosed, new ConnectionAbortedException( `Connection aborted by the idle check because it did not receive any bytes for ${idleTimeout}s.`, false, ), ); } // else nothing to do } sendHeartbeat() { if (this._state === StateActive || this._state === StateHolding || this._state === StateClosing) { // We check if the connection has become inactive. if ( this._inactivityTimer === undefined && // timer not already scheduled this._inactivityTimeout > 0 && // inactivity timeout is enabled this._state === StateActive && // only schedule the timer if the connection is active this._dispatchCount === 0 && // no pending dispatch this._asyncRequests.size === 0 && // no pending invocation this._readHeader && // we're not waiting for the remainder of an incoming message this._sendStreams.length <= 1 // there is at most one pending outgoing message ) { // We may become inactive while the peer is back-pressuring us. In this case, we only schedule the // inactivity timer if there is no pending outgoing message or the pending outgoing message is a // heartbeat. // The stream of the first _sendStreams message is in _writeStream. if ( this._sendStreams.length === 0 || this._writeStream.buffer.getAt(8) === Protocol.validateConnectionMsg ) { this.scheduleInactivityTimer(); } } // We send a heartbeat to the peer to generate a "write" on the connection. This write in turns creates // a read on the peer, and resets the peer's idle check timer. When _sendStream is not empty, there is // already an outstanding write, so we don't need to send a heartbeat. It's possible the first message // of _sendStreams was already sent but not yet removed from _sendStreams: it means the last write // occurred very recently, which is good enough with respect to the idle check. // As a result of this optimization, the only possible heartbeat in _sendStreams is the first // _sendStreams message. if (this._sendStreams.length === 0) { const os = new OutputStream(Protocol.currentProtocolEncoding); os.writeBlob(Protocol.magic); Protocol.currentProtocol._write(os); Protocol.currentProtocolEncoding._write(os); os.writeByte(Protocol.validateConnectionMsg); os.writeByte(0); os.writeInt(Protocol.headerSize); // Message size. try { this.sendMessage(OutgoingMessage.createForStream(os)); } catch (ex) { this.setState(StateClosed, ex); } } } } initialize() { const s = this._transceiver.initialize(this._readStream.buffer, this._writeStream.buffer); if (s != SocketOperation.None) { return false; } // Update the connection description once the transceiver is initialized. this._desc = this._transceiver.toString(); this._initialized = true; this.setState(StateNotValidated); return true; } validate() { if (this._readStream.size === 0) { this._readStream.resize(Protocol.headerSize); this._readStream.pos = 0; } if (this._readStream.pos !== this._readStream.size && !this.read(this._readStream.buffer)) { return false; } this._validated = true; console.assert(this._readStream.pos === Protocol.headerSize); this._readStream.pos = 0; const m = this._readStream.readBlob(4); if ( m[0] !== Protocol.magic[0] || m[1] !== Protocol.magic[1] || m[2] !== Protocol.magic[2] || m[3] !== Protocol.magic[3] ) { throw new ProtocolException( `Bad magic in message header: ${m[0].toString(16)} ${m[1].toString(16)} ${m[2].toString(16)} ${m[3].toString(16)}`, ); } const protocolVersion = new ProtocolVersion(); protocolVersion._read(this._readStream); if ( protocolVersion.major != Protocol.currentProtocol.major || protocolVersion.minor != Protocol.currentProtocol.minor ) { throw new MarshalException( `Invalid protocol version in message header: ${protocolVersion.major}.${protocolVersion.minor}`, ); } const encodingVersion = new EncodingVersion(); encodingVersion._read(this._readStream); if ( encodingVersion.major != Protocol.currentProtocolEncoding.major || protocolVersion.minor != Protocol.currentProtocolEncoding.minor ) { throw new MarshalException( `Invalid protocol encoding version in message header: ${encodingVersion.major}.${encodingVersion.minor}`, ); } const messageType = this._readStream.readByte(); if (messageType !== Protocol.validateConnectionMsg) { throw new ProtocolException( `Received message of type ${messageType} over a connection that is not yet validated.`, ); } this._readStream.readByte(); // Ignore compression status for validate connection. const size = this._readStream.readInt(); if (size !== Protocol.headerSize) { throw new MarshalException(`Received ValidateConnection message with unexpected size ${size}.`); } TraceUtil.traceRecv(this._readStream, this, this._logger, this._traceLevels); this._writeStream.resize(0); this._writeStream.pos = 0; this._readStream.resize(Protocol.headerSize); this._readHeader = true; this._readStream.pos = 0; const traceLevels = this._traceLevels; if (traceLevels.network >= 1) { this._logger.trace(traceLevels.networkCat, `established ${this._endpoint.protocol()} connection\n${this}`); } if (this._transceiver instanceof IdleTimeoutTransceiverDecorator) { // Client connection starts sending heartbeats once it has received the ValidateConnection message. this._transceiver.scheduleHeartbeat(); } return true; } /** * Called when the connection is ready to start sending the next message in the send queue. The connection queues * protocol messages to be sent when the sending cannot complete synchronously or when another protocol message is * in the process of being sent. * * When this method is called, the first message in the send queue (the message currently being sent) has already * been sent and will be removed from the queue. * * This method will continue sending messages until the send queue is empty or until a protocol message cannot be * sent synchronously. * * If the first message in the queue is an outgoing request and its response was received before this method was * called, the response should be cached in the message's response field and will be returned as the result. The * caller is then responsible for processing the response, now that the message has been marked as sent. * * @returns The response of the first message in the send queue if it has been received; null otherwise. */ sendNextMessage() { let response = null; console.assert(!this._writeStream.isEmpty() && this._writeStream.pos === this._writeStream.size); // The first message in the queue has already been sent, notify the message and remove it from the sent queue. let message = this._sendStreams.shift(); this._writeStream.swap(message.stream); message.sent(); // If the response for the first message in the queue was received before this method was called, we will return // the response to the caller to be processed upon return. if (message.response !== null) { response = message.response; } try { // Continue sending messages until the send queue is empty, a message cannot be sent synchronously, // or the connection is closing. while (this._sendStreams.length > 0 && this._state < StateClosingPending) { // Prepare the next message stream for writing. message = this._sendStreams[0]; const stream = message.stream; stream.pos = 10; stream.writeInt(stream.size); stream.prepareWrite(); TraceUtil.traceSend(stream, this._instance, this, this._logger, this._traceLevels); this._writeStream.swap(message.stream); // Send the message. if (this._writeStream.pos != this._writeStream.size) { const completedSynchronously = this.write(this._writeStream.buffer); if (this._writeStream.buffer.remaining === 0) { // If the write call consumed the complete buffer, we assume the message is sent now for // at-most-once semantics. message.isSent = true; } if (!completedSynchronously) { console.assert(!this._writeStream.isEmpty()); return response; // not done } } // The message was sent synchronously, notify the message, remove it from the sent queue and keep going. this._sendStreams.shift(); this._writeStream.swap(message.stream); message.sent(); } // Once the CloseConnection message is sent, we transition to the StateClosingPending state. if (this._state === StateClosing && this._shutdownInitiated) { this.setState(StateClosingPending); } } catch (ex) { if (ex instanceof LocalException) { this.setState(StateClosed, ex); return response; } else { throw ex; } } console.assert(this._writeStream.isEmpty()); return response; } sendMessage(message) { console.assert(this._state >= StateActive); console.assert(this._state < StateClosed); if (this._sendStreams.length > 0) { this._sendStreams.push(message); return AsyncStatus.Queued; } const stream = message.stream; stream.pos = 10; stream.writeInt(stream.size); stream.prepareWrite(); TraceUtil.traceSend(stream, this._instance, this, this._logger, this._traceLevels); const completedSynchronously = this.write(stream.buffer); if (stream.buffer.remaining === 0) { // If the write call consumed the complete buffer, we assume the message is sent now for at-most-once // semantics. message.isSent = true; } if (completedSynchronously) { // Entire buffer was written immediately. message.sent(); return AsyncStatus.Sent; } this._writeStream.swap(message.stream); this._sendStreams.push(message); return AsyncStatus.Queued; } parseMessage() { console.assert(this._state > StateNotValidated && this._state < StateClosed); let info = new IncomingMessage(this._instance); this._readStream.swap(info.stream); this._readStream.resize(Protocol.headerSize); this._readStream.pos = 0; this._readHeader = true; console.assert(info.stream.pos === info.stream.size); try { // We don't need to check magic and version here. This has already been done by the caller. info.stream.pos = 8; const messageType = info.stream.readByte(); const compress = info.stream.readByte(); if (compress === 2) { throw new FeatureNotSupportedException("Cannot decompress compressed message"); } info.stream.pos = Protocol.headerSize; switch (messageType) { case Protocol.closeConnectionMsg: { TraceUtil.traceRecv(info.stream, this, this._logger, this._traceLevels); // We transition directly to StateClosed, not StateClosingPending. this.setState(StateClosed, new CloseConnectionException()); break; } case Protocol.requestMsg: { if (this._state >= StateClosing) { TraceUtil.trace( "received request during closing\n(ignored by server, client will retry)", info.stream, this, this._logger, this._traceLevels, ); } else { TraceUtil.traceRecv(info.stream, this, this._logger, this._traceLevels); info.requestId = info.stream.readInt(); info.requestCount = 1; info.adapter = this._adapter; ++this._upcallCount; this.cancelInactivityTimer(); ++this._dispatchCount; } break; } case Protocol.requestBatchMsg: { if (this._state >= StateClosing) { TraceUtil.trace( "received batch request during closing\n(ignored by server, client will retry)", info.stream, this, this._logger, this._traceLevels, ); } else { TraceUtil.traceRecv(info.stream, this, this._logger, this._traceLevels); const requestCount = info.stream.readInt(); if (info.requestCount < 0) { throw new MarshalException(`Received batch request with ${requestCount} batches.`); } info.requestCount = requestCount; info.adapter = this._adapter; this._upcallCount += info.requestCount; this.cancelInactivityTimer(); ++this._dispatchCount; } break; } case Protocol.replyMsg: { TraceUtil.traceRecv(info.stream, this, this._logger, this._traceLevels); info.requestId = info.stream.readInt(); info.outAsync = this._asyncRequests.get(info.requestId); if (info.outAsync !== undefined) { this._asyncRequests.delete(info.requestId); // If we receive a response for a request that hasn’t been marked as sent, we store the response // in the request's response field and delay processing until the request is marked as sent. // This can occur if the request is sent asynchronously and the response is processed before the // write-ready callback has a chance to run and invoke sendNextMessage. const message = this._sendStreams.length > 0 ? this._sendStreams[0] : null; if (message !== null && message.outAsync === info.outAsync) { message.response = info; info = null; } else { ++this._upcallCount; console.assert(info.outAsync.isSent()); } if ( this._closed !== undefined && this._state < StateClosing && this._asyncRequests.size === 0 ) { this.doApplicationClose(); } } else { info = null; } break; } case Protocol.validateConnectionMsg: { TraceUtil.traceRecv(info.stream, this, this._logger, this._traceLevels); break; } default: { TraceUtil.trace( "received unknown message\n(invalid, closing connection)", info.stream, this, this._logger, this._traceLevels, ); throw new ProtocolException(`Received Ice protocol message with unknown type: ${messageType}`); } } } catch (ex) { if (ex instanceof LocalException) { this.setState(StateClosed, ex); } else { throw ex; } } return info; } dispatchAll(stream, requestCount, requestId, adapter) { const dispatcher = adapter !== null ? adapter.dispatchPipeline : null; try { while (requestCount > 0) { // adapter can be null here, however the adapter set in current can't be null, and we never pass // a null current.adapter to the application code. const request = new IncomingRequest(requestId, this, adapter, stream); if (dispatcher !== null) { // We don't and can't await the dispatchAsync: with batch requests, we want all the dispatches to // execute synchronously. If we awaited the dispatchAsync, we could switch to another event loop task. dispatchAsync(this, request); } else { // Received request on a connection without an object adapter. this.sendResponse( request.current.createOutgoingResponseWithException(new ObjectNotExistException()), requestId != 0, ); } --requestCount; } stream.clear(); } catch (ex) { if (ex instanceof LocalException) { this.dispatchException(ex, requestCount); } else { // An Error was raised outside of servant code (i.e., by Ice code), log the error and clean up. this._logger.error(`unexpected exception:\n ${ex}\n${ex.stack}`); this.dispatchException( new UnknownException("unexpected exception dispatching request", { cause: ex }), requestCount, ); } } async function dispatchAsync(connection, request) { try { let response; try { response = await dispatcher.dispatch(request); } catch (ex) { response = request.current.createOutgoingResponseWithException(ex); } connection.sendResponse(response, requestId != 0); } catch (ex) { connection.dispatchException(ex, 1); } } } connectTimedOut() { if (this._state < StateActive) { this.setState(StateClosed, new ConnectTimeoutException()); } // else ignore since we're already connected } closeTimedOut() { if (this._state < StateClosed) { // We don't use setState(state, exception) because we want to overwrite the exception set by a // graceful closure. this._exception = new CloseTimeoutException(); this.setState(StateClosed); } // else ignore since we're already closed. } warning(msg, ex) { this._logger.warning(msg + ":\n" + this._desc + "\n" + ex.toString()); } checkState() { // We aren't finished until the state is finished and all outstanding requests are completed. Otherwise we // couldn't guarantee that there are no outstanding calls when deactivate() is called on the servant locators. if (this._state === StateFinished && this._upcallCount === 0) { for (const p of this._finishedPromises) { p.resolve(); } this._finishedPromises = []; } } read(buf) { const start = buf.position; const ret = this._transceiver.read(buf, this._hasMoreData); if (this._traceLevels.network >= 3 && buf.position != start) { this._logger.trace( this._traceLevels.networkCat, `received ${buf.position - start} of ${buf.limit - start} bytes via ${this._endpoint.protocol()}\n${this}`, ); } return ret; } write(buffer) { const start = buffer.position; const ret = this._transceiver.write(buffer); if (this._traceLevels.network >= 3 && buffer.position != start) { this._logger.trace( this._traceLevels.networkCat, `sent ${buffer.position - start} of ${buffer.limit - start} bytes via ${this._endpoint.protocol()}\n${this}`, ); } return ret; } scheduleInactivityTimer() { console.assert(this._inactivityTimer === undefined); console.assert(this._inactivityTimeout > 0); this._inactivityTimer = new Timer(); const inactivityTimer = this._inactivityTimer; this._inactivityTimer.schedule(() => this.inactivityCheck(inactivityTimer), this._inactivityTimeout); } cancelInactivityTimer() { if (this._inactivityTimer !== undefined) { this._inactivityTimer.destroy(); this._inactivityTimer = undefined; } } } /** * Represents an incoming protocol message received by the connection. */ class IncomingMessage { constructor(instance) { this.stream = new InputStream(instance, Protocol.currentProtocolEncoding); this.requestCount = 0; this.requestId = 0; this.adapter = null; this.outAsync = null; this.upcallCount = 0; } } /** * Represents an outgoing protocol message sent by the connection. */ class OutgoingMessage { // Not used directly, see createForStream and create static methods below. constructor(requestId, stream, outAsync) { // The OutputStream containing the message to be sent. The connection swaps this stream with its own write stream // while the message is being sent and swaps it back once the message has been sent. this.stream = stream; // The OutgoingAsync object associated with an outgoing request; it is always null for other message types. this.outAsync = outAsync; // The request ID for two-way requests; 0 for one-way requests and other message types. this.requestId = requestId; // For a request message: if the response is received before the request is marked as sent and removed from the // send queue, we store the response in this field and delay its processing until the message is marked as sent. this.response = null; // Set to true by the transport bufferFullyWriteCallback to ensure "at most once" semantics for non-idempotent, // retriable requests. this.isSent = false; } canceled() { console.assert(this.outAsync !== null); this.outAsync = null; } // If the outgoing message represents an outgoing request, notify it that the request has been sent. sent() { if (this.outAsync !== null) { this.outAsync.sent(); } } // If the outgoing message represents an outgoing request, notify it that the request has been completed. completed(ex) { if (this.outAsync !== null) { this.outAsync.completedEx(ex); } } // Creates an OutgoingMessage from a stream containing the encoded protocol message. This method is never used for // outgoing requests. static createForStream(stream) { return new OutgoingMessage(0, stream, null); } // Creates an OutgoingMessage for an outgoing request. static create(out, stream, requestId) { return new OutgoingMessage(requestId, stream, out); } } |