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 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
|
// Copyright 2012-2023 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package test
import (
"bufio"
"bytes"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats-server/v2/test"
"github.com/nats-io/nats.go"
)
func TestDefaultConnection(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
nc.Close()
}
func TestConnectionStatus(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
if nc.Status() != nats.CONNECTED || nc.Status().String() != "CONNECTED" {
t.Fatal("Should have status set to CONNECTED")
}
if !nc.IsConnected() {
t.Fatal("Should have status set to CONNECTED")
}
nc.Close()
if nc.Status() != nats.CLOSED || nc.Status().String() != "CLOSED" {
t.Fatal("Should have status set to CLOSED")
}
if !nc.IsClosed() {
t.Fatal("Should have status set to CLOSED")
}
}
func TestConnClosedCB(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
ch := make(chan bool)
o := nats.GetDefaultOptions()
o.Url = nats.DefaultURL
o.ClosedCB = func(_ *nats.Conn) {
ch <- true
}
nc, err := o.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
nc.Close()
if e := Wait(ch); e != nil {
t.Fatalf("Closed callback not triggered\n")
}
}
func TestCloseDisconnectedErrCB(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
ch := make(chan bool)
o := nats.GetDefaultOptions()
o.Url = nats.DefaultURL
o.AllowReconnect = false
o.DisconnectedErrCB = func(_ *nats.Conn, _ error) {
ch <- true
}
nc, err := o.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
nc.Close()
if e := Wait(ch); e != nil {
t.Fatal("Disconnected callback not triggered")
}
}
func TestServerStopDisconnectedErrCB(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
ch := make(chan bool)
o := nats.GetDefaultOptions()
o.Url = nats.DefaultURL
o.AllowReconnect = false
o.DisconnectedErrCB = func(nc *nats.Conn, _ error) {
ch <- true
}
nc, err := o.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
defer nc.Close()
s.Shutdown()
if e := Wait(ch); e != nil {
t.Fatalf("Disconnected callback not triggered\n")
}
}
func TestServerSecureConnections(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tls.conf")
defer s.Shutdown()
endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
secureURL := fmt.Sprintf("nats://%s:%s@%s/", opts.Username, opts.Password, endpoint)
// Make sure this succeeds
nc, err := nats.Connect(secureURL, nats.Secure(), nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Failed to create secure (TLS) connection: %v", err)
}
defer nc.Close()
omsg := []byte("Hello World")
checkRecv := make(chan bool)
received := 0
nc.Subscribe("foo", func(m *nats.Msg) {
received++
if !bytes.Equal(m.Data, omsg) {
t.Fatal("Message received does not match")
}
checkRecv <- true
})
err = nc.Publish("foo", omsg)
if err != nil {
t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
}
nc.Flush()
state, err := nc.TLSConnectionState()
if err != nil {
t.Fatalf("Expected connection state: %v", err)
}
if !state.HandshakeComplete {
t.Fatalf("Expected valid connection state")
}
if err := Wait(checkRecv); err != nil {
t.Fatal("Failed receiving message")
}
nc.Close()
// Server required, but not specified in Connect(), should switch automatically
nc, err = nats.Connect(secureURL, nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Failed to create secure (TLS) connection: %v", err)
}
nc.Close()
// Test flag mismatch
// Wanted but not available..
ds := RunDefaultServer()
defer ds.Shutdown()
nc, err = nats.Connect(nats.DefaultURL, nats.Secure(), nats.RootCAs("./configs/certs/ca.pem"))
if err == nil || nc != nil || err != nats.ErrSecureConnWanted {
if nc != nil {
nc.Close()
}
t.Fatalf("Should have failed to create connection: %v", err)
}
// Let's be more TLS correct and verify servername, endpoint etc.
// Now do more advanced checking, verifying servername and using rootCA.
// Setup our own TLSConfig using RootCA from our self signed cert.
rootPEM, err := os.ReadFile("./configs/certs/ca.pem")
if err != nil || rootPEM == nil {
t.Fatalf("failed to read root certificate")
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
t.Fatal("failed to parse root certificate")
}
tls1 := &tls.Config{
ServerName: opts.Host,
RootCAs: pool,
MinVersion: tls.VersionTLS12,
}
nc, err = nats.Connect(secureURL, nats.Secure(tls1), nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
}
defer nc.Close()
tls2 := &tls.Config{
ServerName: "OtherHostName",
RootCAs: pool,
MinVersion: tls.VersionTLS12,
}
nc2, err := nats.Connect(secureURL, nats.Secure(tls1, tls2))
if err == nil {
nc2.Close()
t.Fatal("Was expecting an error!")
}
}
func TestClientTLSConfig(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tlsverify.conf")
defer s.Shutdown()
endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
secureURL := fmt.Sprintf("nats://%s", endpoint)
// Make sure this fails
nc, err := nats.Connect(secureURL, nats.Secure())
if err == nil {
nc.Close()
t.Fatal("Should have failed (TLS) connection without client certificate")
}
cert, err := os.ReadFile("./configs/certs/client-cert.pem")
if err != nil {
t.Fatal("Failed to read client certificate")
}
key, err := os.ReadFile("./configs/certs/client-key.pem")
if err != nil {
t.Fatal("Failed to read client key")
}
rootCAs, err := os.ReadFile("./configs/certs/ca.pem")
if err != nil {
t.Fatal("Failed to read root CAs")
}
certCB := func() (tls.Certificate, error) {
cert, err := tls.X509KeyPair(cert, key)
if err != nil {
return tls.Certificate{}, fmt.Errorf("nats: error loading client certificate: %w", err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return tls.Certificate{}, fmt.Errorf("nats: error parsing client certificate: %w", err)
}
return cert, nil
}
caCB := func() (*x509.CertPool, error) {
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(rootCAs)
if !ok {
return nil, errors.New("nats: failed to parse root certificate from")
}
return pool, nil
}
// Check parameters validity
_, err = nats.Connect(secureURL, nats.ClientTLSConfig(nil, nil))
if !errors.Is(err, nats.ErrClientCertOrRootCAsRequired) {
t.Fatalf("Expected error %q, got %q", nats.ErrClientCertOrRootCAsRequired, err)
}
certErr := &tls.CertificateVerificationError{}
// Should fail because of missing CA
_, err = nats.Connect(secureURL,
nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"))
if ok := errors.As(err, &certErr); !ok {
t.Fatalf("Expected error %q, got %q", nats.ErrClientCertOrRootCAsRequired, err)
}
// Should fail because of missing certificate
_, err = nats.Connect(secureURL,
nats.ClientTLSConfig(nil, caCB))
if !strings.Contains(err.Error(), "bad certificate") && !strings.Contains(err.Error(), "certificate required") {
t.Fatalf("Expected missing certificate error; got: %s", err)
}
nc, err = nats.Connect(secureURL,
nats.ClientTLSConfig(certCB, caCB))
if err != nil {
t.Fatalf("Failed to create (TLS) connection: %v", err)
}
defer nc.Close()
omsg := []byte("Hello!")
checkRecv := make(chan bool)
received := 0
nc.Subscribe("foo", func(m *nats.Msg) {
received++
if !bytes.Equal(m.Data, omsg) {
t.Fatal("Message received does not match")
}
checkRecv <- true
})
err = nc.Publish("foo", omsg)
if err != nil {
t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
}
nc.Flush()
if err := Wait(checkRecv); err != nil {
t.Fatal("Failed to receive message")
}
}
func TestClientCertificate(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tlsverify.conf")
defer s.Shutdown()
endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
secureURL := fmt.Sprintf("nats://%s", endpoint)
// Make sure this fails
nc, err := nats.Connect(secureURL, nats.Secure())
if err == nil {
nc.Close()
t.Fatal("Should have failed (TLS) connection without client certificate")
}
// Check parameters validity
nc, err = nats.Connect(secureURL, nats.ClientCert("", ""))
if err == nil {
nc.Close()
t.Fatal("Should have failed due to invalid parameters")
}
// Should fail because wrong key
nc, err = nats.Connect(secureURL,
nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/key.pem"))
if err == nil {
nc.Close()
t.Fatal("Should have failed due to invalid key")
}
// Should fail because no CA
nc, err = nats.Connect(secureURL,
nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"))
if err == nil {
nc.Close()
t.Fatal("Should have failed due to missing ca")
}
nc, err = nats.Connect(secureURL,
nats.RootCAs("./configs/certs/ca.pem"),
nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"))
if err != nil {
t.Fatalf("Failed to create (TLS) connection: %v", err)
}
defer nc.Close()
omsg := []byte("Hello!")
checkRecv := make(chan bool)
received := 0
nc.Subscribe("foo", func(m *nats.Msg) {
received++
if !bytes.Equal(m.Data, omsg) {
t.Fatal("Message received does not match")
}
checkRecv <- true
})
err = nc.Publish("foo", omsg)
if err != nil {
t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
}
nc.Flush()
if err := Wait(checkRecv); err != nil {
t.Fatal("Failed to receive message")
}
}
func TestClientCertificateReloadOnServerRestart(t *testing.T) {
copyFiles := func(t *testing.T, cpFiles map[string]string) {
for from, to := range cpFiles {
content, err := os.ReadFile(from)
if err != nil {
t.Fatalf("Error reading file: %s", err)
}
if err := os.WriteFile(to, content, 0640); err != nil {
t.Fatalf("Error writing file: %s", err)
}
}
}
s, opts := RunServerWithConfig("./configs/tlsverify.conf")
defer s.Shutdown()
endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
secureURL := fmt.Sprintf("nats://%s", endpoint)
tmpCertDir := t.TempDir()
certFile := filepath.Join(tmpCertDir, "client-cert.pem")
keyFile := filepath.Join(tmpCertDir, "client-key.pem")
caFile := filepath.Join(tmpCertDir, "ca.pem")
// copy valid cert files to tmp dir
filesToCopy := map[string]string{
"./configs/certs/client-cert.pem": certFile,
"./configs/certs/client-key.pem": keyFile,
"./configs/certs/ca.pem": caFile,
}
copyFiles(t, filesToCopy)
dcChan, rcChan, errChan := make(chan bool, 1), make(chan bool, 1), make(chan error, 1)
nc, err := nats.Connect(secureURL,
nats.RootCAs(caFile),
nats.ClientCert(certFile, keyFile),
nats.ReconnectWait(100*time.Millisecond),
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
errChan <- err
}),
nats.DisconnectErrHandler(func(_ *nats.Conn, _ error) {
dcChan <- true
}),
nats.ReconnectHandler(func(_ *nats.Conn) {
rcChan <- true
}),
)
if err != nil {
t.Fatalf("Failed to create (TLS) connection: %v", err)
}
defer nc.Close()
// overwrite client certificate files with invalid ones, those
// should be loaded on server restart
filesToCopy = map[string]string{
"./configs/certs/client-cert-invalid.pem": certFile,
"./configs/certs/client-key-invalid.pem": keyFile,
}
copyFiles(t, filesToCopy)
// restart server
s.Shutdown()
s, _ = RunServerWithConfig("./configs/tlsverify.conf")
defer s.Shutdown()
// wait for disconnected signal
if err := Wait(dcChan); err != nil {
t.Fatal("Failed to receive disconnect signal")
}
// wait for reconnection error (bad certificate)
select {
case err := <-errChan:
if !strings.Contains(err.Error(), "bad certificate") && !strings.Contains(err.Error(), "certificate required") {
t.Fatalf("Expected bad certificate error; got: %s", err)
}
case <-time.After(5 * time.Second):
t.Fatalf("Timeout waiting for reconnect error")
}
// overwrite cert files with valid ones again,
// so that subsequent reconnect attempt should succeed
// when cert files are reloaded
filesToCopy = map[string]string{
"./configs/certs/client-cert.pem": certFile,
"./configs/certs/client-key.pem": keyFile,
}
copyFiles(t, filesToCopy)
// wait for reconnect signal
if err := Wait(rcChan); err != nil {
t.Fatal("Failed to receive reconnect signal")
}
// pub-sub test message to make sure connection is OK
omsg := []byte("Hello!")
checkRecv := make(chan bool)
received := 0
nc.Subscribe("foo", func(m *nats.Msg) {
received++
if !bytes.Equal(m.Data, omsg) {
t.Fatal("Message received does not match")
}
checkRecv <- true
})
err = nc.Publish("foo", omsg)
if err != nil {
t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
}
nc.Flush()
if err := Wait(checkRecv); err != nil {
t.Fatal("Failed to receive message")
}
}
func TestServerTLSHintConnections(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tls.conf")
defer s.Shutdown()
endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
secureURL := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, opts.Password, endpoint)
nc, err := nats.Connect(secureURL, nats.RootCAs("./configs/certs/badca.pem"))
if err == nil {
nc.Close()
t.Fatal("Expected an error from bad RootCA file")
}
nc, err = nats.Connect(secureURL, nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Failed to create secure (TLS) connection: %v", err)
}
defer nc.Close()
}
func TestClosedConnections(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
sub, _ := nc.SubscribeSync("foo")
if sub == nil {
t.Fatal("Failed to create valid subscription")
}
// Test all API endpoints do the right thing with a closed connection.
nc.Close()
if err := nc.Publish("foo", nil); err != nats.ErrConnectionClosed {
t.Fatalf("Publish on closed conn did not fail properly: %v\n", err)
}
if err := nc.PublishMsg(&nats.Msg{Subject: "foo"}); err != nats.ErrConnectionClosed {
t.Fatalf("PublishMsg on closed conn did not fail properly: %v\n", err)
}
if err := nc.Flush(); err != nats.ErrConnectionClosed {
t.Fatalf("Flush on closed conn did not fail properly: %v\n", err)
}
_, err := nc.Subscribe("foo", nil)
if err != nats.ErrConnectionClosed {
t.Fatalf("Subscribe on closed conn did not fail properly: %v\n", err)
}
_, err = nc.SubscribeSync("foo")
if err != nats.ErrConnectionClosed {
t.Fatalf("SubscribeSync on closed conn did not fail properly: %v\n", err)
}
_, err = nc.QueueSubscribe("foo", "bar", nil)
if err != nats.ErrConnectionClosed {
t.Fatalf("QueueSubscribe on closed conn did not fail properly: %v\n", err)
}
_, err = nc.Request("foo", []byte("help"), 10*time.Millisecond)
if err != nats.ErrConnectionClosed {
t.Fatalf("Request on closed conn did not fail properly: %v\n", err)
}
if _, err = sub.NextMsg(10); err != nats.ErrConnectionClosed {
t.Fatalf("NextMessage on closed conn did not fail properly: %v\n", err)
}
if err = sub.Unsubscribe(); err != nats.ErrConnectionClosed {
t.Fatalf("Unsubscribe on closed conn did not fail properly: %v\n", err)
}
}
func TestErrOnConnectAndDeadlock(t *testing.T) {
// We will hand run a fake server that will timeout and not return a proper
// INFO proto. This is to test that we do not deadlock. Issue #18
l, e := net.Listen("tcp", ":0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
errCh := make(chan error, 1)
go func() {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
errCh <- nil
defer conn.Close()
// Send back a mal-formed INFO.
conn.Write([]byte("INFOZ \r\n"))
}()
go func() {
natsURL := fmt.Sprintf("nats://127.0.0.1:%d/", addr.Port)
nc, err := nats.Connect(natsURL)
if err == nil {
nc.Close()
errCh <- errors.New("expected bad INFO err, got none")
return
}
errCh <- nil
}()
// Setup a timer to watch for deadlock
select {
case e := <-errCh:
if e != nil {
t.Fatal(e.Error())
}
case <-time.After(time.Second):
t.Fatalf("Connect took too long, deadlock?")
}
}
func TestMoreErrOnConnect(t *testing.T) {
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
case1 := make(chan bool)
case2 := make(chan bool)
case3 := make(chan bool)
case4 := make(chan bool)
errCh := make(chan error, 5)
go func() {
for i := 0; i < 5; i++ {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
switch i {
case 0:
// Send back a partial INFO and close the connection.
conn.Write([]byte("INFO"))
case 1:
// Send just INFO
conn.Write([]byte("INFO\r\n"))
// Stick around a bit
<-case1
case 2:
info := fmt.Sprintf("INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n", addr.IP, addr.Port)
// Send complete INFO
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
// Client expect +OK, send it but then something else than PONG
conn.Write([]byte("+OK\r\n"))
// Stick around a bit
<-case2
case 3:
info := fmt.Sprintf("INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n", addr.IP, addr.Port)
// Send complete INFO
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
// Client expect +OK, send it but then something else than PONG
conn.Write([]byte("+OK\r\nXXX\r\n"))
// Stick around a bit
<-case3
case 4:
info := "INFO {'x'}\r\n"
// Send INFO with JSON marshall error
conn.Write([]byte(info))
// Stick around a bit
<-case4
}
conn.Close()
}
// Hang around until asked to quit
<-done
}()
natsURL := fmt.Sprintf("nats://127.0.0.1:%d", addr.Port)
if nc, err := nats.Connect(natsURL, nats.Timeout(20*time.Millisecond)); err == nil {
nc.Close()
t.Fatal("Expected error, got none")
}
if nc, err := nats.Connect(natsURL, nats.Timeout(20*time.Millisecond)); err == nil {
close(case1)
nc.Close()
t.Fatal("Expected error, got none")
}
close(case1)
opts := nats.GetDefaultOptions()
opts.Servers = []string{natsURL}
opts.Timeout = 20 * time.Millisecond
opts.Verbose = true
if nc, err := opts.Connect(); err == nil {
close(case2)
nc.Close()
t.Fatal("Expected error, got none")
}
close(case2)
if nc, err := opts.Connect(); err == nil {
close(case3)
nc.Close()
t.Fatal("Expected error, got none")
}
close(case3)
if nc, err := opts.Connect(); err == nil {
close(case4)
nc.Close()
t.Fatal("Expected error, got none")
}
close(case4)
close(done)
checkErrChannel(t, errCh)
}
func TestErrOnMaxPayloadLimit(t *testing.T) {
expectedMaxPayload := int64(10)
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":%d}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
// Send back an INFO message with custom max payload size on connect.
var conn net.Conn
var err error
errCh := make(chan error, 1)
go func() {
conn, err = l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port, expectedMaxPayload)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
line := make([]byte, 111)
_, err := conn.Read(line)
if err != nil {
errCh <- fmt.Errorf("expected CONNECT and PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Hang around a bit to not err on EOF in client.
time.Sleep(250 * time.Millisecond)
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
got := nc.MaxPayload()
if got != expectedMaxPayload {
t.Fatalf("Expected MaxPayload to be %d, got: %d", expectedMaxPayload, got)
}
err = nc.Publish("hello", []byte("hello world"))
if err != nats.ErrMaxPayload {
t.Fatalf("Expected to fail trying to send more than max payload, got: %s", err)
}
err = nc.Publish("hello", []byte("a"))
if err != nil {
t.Fatalf("Expected to succeed trying to send less than max payload, got: %s", err)
}
checkErrChannel(t, errCh)
}
func TestConnectVerbose(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
o := nats.GetDefaultOptions()
o.Verbose = true
nc, err := o.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
nc.Close()
}
func getStacks(all bool) string {
var (
stacks []byte
stacksSize = 10000
n int
)
for {
stacks = make([]byte, stacksSize)
n = runtime.Stack(stacks, all)
if n == stacksSize {
stacksSize *= 2
continue
}
break
}
return string(stacks[:n])
}
func isRunningInAsyncCBDispatcher() error {
strStacks := getStacks(false)
if strings.Contains(strStacks, "asyncCBDispatcher") {
return nil
}
return fmt.Errorf("callback not executed from dispatcher:\n %s", strStacks)
}
func isAsyncDispatcherRunning() bool {
strStacks := getStacks(true)
return strings.Contains(strStacks, "asyncCBDispatcher")
}
func TestCallbacksOrder(t *testing.T) {
authS, authSOpts := RunServerWithConfig("./configs/tls.conf")
defer authS.Shutdown()
s := RunDefaultServer()
defer s.Shutdown()
firstDisconnect := true
var connTime, dtime1, dtime2, rtime, atime1, atime2, ctime time.Time
cbErrors := make(chan error, 20)
connected := make(chan bool)
reconnected := make(chan bool)
closed := make(chan bool)
asyncErr := make(chan bool, 2)
recvCh := make(chan bool, 2)
recvCh1 := make(chan bool)
recvCh2 := make(chan bool)
connCh := func(nc *nats.Conn) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
connected <- true
return
}
time.Sleep(50 * time.Millisecond)
connTime = time.Now()
connected <- true
}
dch := func(nc *nats.Conn) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
return
}
time.Sleep(100 * time.Millisecond)
if firstDisconnect {
firstDisconnect = false
dtime1 = time.Now()
} else {
dtime2 = time.Now()
}
}
rch := func(nc *nats.Conn) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
reconnected <- true
return
}
time.Sleep(50 * time.Millisecond)
rtime = time.Now()
reconnected <- true
}
ech := func(nc *nats.Conn, sub *nats.Subscription, err error) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
asyncErr <- true
return
}
if sub.Subject == "foo" {
time.Sleep(20 * time.Millisecond)
atime1 = time.Now()
} else {
atime2 = time.Now()
}
asyncErr <- true
}
cch := func(nc *nats.Conn) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
closed <- true
return
}
ctime = time.Now()
closed <- true
}
url := net.JoinHostPort(authSOpts.Host, strconv.Itoa(authSOpts.Port))
url = "nats://" + url + "," + nats.DefaultURL
nc, err := nats.Connect(url,
nats.ConnectHandler(connCh),
nats.DisconnectHandler(dch),
nats.ReconnectHandler(rch),
nats.ClosedHandler(cch),
nats.ErrorHandler(ech),
nats.ReconnectWait(50*time.Millisecond),
nats.ReconnectJitter(0, 0),
nats.DontRandomize())
if err != nil {
t.Fatalf("Unable to connect: %v\n", err)
}
defer nc.Close()
// Wait for notification on connection established
err = Wait(connected)
if err != nil {
t.Fatal("Did not get the connected callback")
}
ncp, err := nats.Connect(nats.DefaultURL,
nats.ReconnectWait(50*time.Millisecond))
if err != nil {
t.Fatalf("Unable to connect: %v\n", err)
}
defer ncp.Close()
// Wait to make sure that if we have closed (incorrectly) the
// asyncCBDispatcher during the connect process, this is caught here.
time.Sleep(time.Second)
s.Shutdown()
s = RunDefaultServer()
defer s.Shutdown()
if err := Wait(reconnected); err != nil {
t.Fatal("Did not get the reconnected callback")
}
var sub1, sub2 *nats.Subscription
recv := func(m *nats.Msg) {
// Signal that one message is received
recvCh <- true
// We will now block
if m.Subject == "foo" {
<-recvCh1
} else {
<-recvCh2
}
m.Sub.Unsubscribe()
}
sub1, err = nc.Subscribe("foo", recv)
if err != nil {
t.Fatalf("Unable to create subscription: %v\n", err)
}
sub1.SetPendingLimits(1, 100000)
sub2, err = nc.Subscribe("bar", recv)
if err != nil {
t.Fatalf("Unable to create subscription: %v\n", err)
}
sub2.SetPendingLimits(1, 100000)
nc.Flush()
ncp.Publish("foo", []byte("test"))
ncp.Publish("bar", []byte("test"))
ncp.Flush()
// Wait notification that message were received
err = Wait(recvCh)
if err == nil {
err = Wait(recvCh)
}
if err != nil {
t.Fatal("Did not receive message")
}
for i := 0; i < 2; i++ {
ncp.Publish("foo", []byte("test"))
ncp.Publish("bar", []byte("test"))
}
ncp.Flush()
if err := Wait(asyncErr); err != nil {
t.Fatal("Did not get the async callback")
}
if err := Wait(asyncErr); err != nil {
t.Fatal("Did not get the async callback")
}
close(recvCh1)
close(recvCh2)
nc.Close()
if err := Wait(closed); err != nil {
t.Fatal("Did not get the close callback")
}
if len(cbErrors) > 0 {
t.Fatalf("%v", <-cbErrors)
}
if (connTime == time.Time{}) || (dtime1 == time.Time{}) || (dtime2 == time.Time{}) || (rtime == time.Time{}) || (atime1 == time.Time{}) || (atime2 == time.Time{}) || (ctime == time.Time{}) {
t.Fatalf("Some callbacks did not fire:\n%v\n%v\n%v\n%v\n%v\n%v", dtime1, rtime, atime1, atime2, dtime2, ctime)
}
if dtime1.Before(connTime) || rtime.Before(dtime1) || dtime2.Before(rtime) || atime2.Before(atime1) || ctime.Before(atime2) {
t.Fatalf("Wrong callback order:\n%v\n%v\n%v\n%v\n%v\n%v\n%v", connTime, dtime1, rtime, atime1, atime2, dtime2, ctime)
}
// Close the other connection
ncp.Close()
// Check that the go routine is gone. Allow plenty of time
// to avoid flappers.
timeout := time.Now().Add(5 * time.Second)
for time.Now().Before(timeout) {
if !isAsyncDispatcherRunning() {
// Good, we are done!
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("The async callback dispatcher(s) should have stopped")
}
func TestReconnectErrHandler(t *testing.T) {
handler := func(ch chan bool) func(*nats.Conn, error) {
return func(*nats.Conn, error) {
ch <- true
}
}
t.Run("with RetryOnFailedConnect, MaxReconnects(-1), no connection", func(t *testing.T) {
opts := test.DefaultTestOptions
// Server should not be reachable to test this one
opts.Port = 4223
s := RunServerWithOptions(&opts)
defer s.Shutdown()
reconnectErr := make(chan bool)
nc, err := nats.Connect(nats.DefaultURL,
nats.ReconnectErrHandler(handler(reconnectErr)),
nats.RetryOnFailedConnect(true),
nats.MaxReconnects(-1))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer nc.Close()
if err = Wait(reconnectErr); err != nil {
t.Fatal("Timeout waiting for reconnect error handler")
}
})
}
func TestConnectHandler(t *testing.T) {
handler := func(ch chan bool) func(*nats.Conn) {
return func(*nats.Conn) {
ch <- true
}
}
t.Run("with RetryOnFailedConnect, connection established", func(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
connected := make(chan bool)
reconnected := make(chan bool)
nc, err := nats.Connect(nats.DefaultURL,
nats.ConnectHandler(handler(connected)),
nats.ReconnectHandler(handler(reconnected)),
nats.RetryOnFailedConnect(true))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer nc.Close()
if err = Wait(connected); err != nil {
t.Fatal("Timeout waiting for connect handler")
}
if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
t.Fatal("Reconnect handler should not have been invoked")
}
})
t.Run("with RetryOnFailedConnect, connection failed", func(t *testing.T) {
connected := make(chan bool)
reconnected := make(chan bool)
nc, err := nats.Connect(nats.DefaultURL,
nats.ConnectHandler(handler(connected)),
nats.ReconnectHandler(handler(reconnected)),
nats.RetryOnFailedConnect(true))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer nc.Close()
if err = WaitTime(connected, 100*time.Millisecond); err == nil {
t.Fatal("Connected handler should not have been invoked")
}
if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
t.Fatal("Reconnect handler should not have been invoked")
}
})
t.Run("no RetryOnFailedConnect, connection established", func(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
connected := make(chan bool)
reconnected := make(chan bool)
nc, err := nats.Connect(nats.DefaultURL,
nats.ConnectHandler(handler(connected)),
nats.ReconnectHandler(handler(reconnected)))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer nc.Close()
if err = Wait(connected); err != nil {
t.Fatal("Timeout waiting for connect handler")
}
if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
t.Fatal("Reconnect handler should not have been invoked")
}
})
t.Run("no RetryOnFailedConnect, connection failed", func(t *testing.T) {
connected := make(chan bool)
reconnected := make(chan bool)
_, err := nats.Connect(nats.DefaultURL,
nats.ConnectHandler(handler(connected)),
nats.ReconnectHandler(handler(reconnected)))
if err == nil {
t.Fatalf("Expected error on connect, got nil")
}
if err = WaitTime(connected, 100*time.Millisecond); err == nil {
t.Fatal("Connected handler should not have been invoked")
}
if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
t.Fatal("Reconnect handler should not have been invoked")
}
})
t.Run("with RetryOnFailedConnect, initial connection failed, reconnect successful", func(t *testing.T) {
connected := make(chan bool)
reconnected := make(chan bool)
nc, err := nats.Connect(nats.DefaultURL,
nats.ConnectHandler(handler(connected)),
nats.ReconnectHandler(handler(reconnected)),
nats.RetryOnFailedConnect(true),
nats.ReconnectWait(100*time.Millisecond))
if err != nil {
t.Fatalf("Expected error on connect, got nil")
}
defer nc.Close()
s := RunDefaultServer()
defer s.Shutdown()
if err != nil {
t.Fatalf("Expected error on connect, got nil")
}
if err = Wait(connected); err != nil {
t.Fatal("Timeout waiting for reconnect handler")
}
if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
t.Fatal("Reconnect handler should not have been invoked")
}
})
t.Run("with RetryOnFailedConnect, initial connection successful, server restart", func(t *testing.T) {
connected := make(chan bool)
reconnected := make(chan bool)
s := RunDefaultServer()
defer s.Shutdown()
nc, err := nats.Connect(nats.DefaultURL,
nats.ConnectHandler(handler(connected)),
nats.ReconnectHandler(handler(reconnected)),
nats.RetryOnFailedConnect(true),
nats.ReconnectWait(100*time.Millisecond))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer nc.Close()
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if err = Wait(connected); err != nil {
t.Fatal("Timeout waiting for connect handler")
}
if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
t.Fatal("Reconnect handler should not have been invoked")
}
s.Shutdown()
s = RunDefaultServer()
defer s.Shutdown()
if err = Wait(reconnected); err != nil {
t.Fatal("Timeout waiting for reconnect handler")
}
if err = WaitTime(connected, 100*time.Millisecond); err == nil {
t.Fatal("Connected handler should not have been invoked")
}
})
}
func TestFlushReleaseOnClose(t *testing.T) {
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
errCh := make(chan error, 1)
go func() {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Hang around until asked to quit
<-done
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.AllowReconnect = false
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
// First try a FlushTimeout() and make sure we timeout
if err := nc.FlushTimeout(50 * time.Millisecond); err == nil || err != nats.ErrTimeout {
t.Fatalf("Expected a timeout error, got: %v", err)
}
go func() {
time.Sleep(50 * time.Millisecond)
nc.Close()
}()
if err := nc.Flush(); err == nil {
t.Fatal("Expected error on Flush() released by Close()")
}
close(done)
checkErrChannel(t, errCh)
}
func TestMaxPendingOut(t *testing.T) {
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
cch := make(chan bool)
errCh := make(chan error, 1)
go func() {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Hang around until asked to quit
<-done
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.PingInterval = 20 * time.Millisecond
opts.MaxPingsOut = 2
opts.AllowReconnect = false
opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
// After 60 ms, we should have closed the connection
time.Sleep(100 * time.Millisecond)
if err := Wait(cch); err != nil {
t.Fatal("Failed to get ClosedCB")
}
if nc.LastError() != nats.ErrStaleConnection {
t.Fatalf("Expected to get %v, got %v", nats.ErrStaleConnection, nc.LastError())
}
close(done)
checkErrChannel(t, errCh)
}
func TestErrInReadLoop(t *testing.T) {
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
cch := make(chan bool)
errCh := make(chan error, 1)
go func() {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Read (and ignore) the SUB from the client
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected SUB from client, got: %s", err)
return
}
// Send something that should make the subscriber fail.
conn.Write([]byte("Ivan"))
// Hang around until asked to quit
<-done
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.AllowReconnect = false
opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
received := int64(0)
nc.Subscribe("foo", func(_ *nats.Msg) {
atomic.AddInt64(&received, 1)
})
if err := Wait(cch); err != nil {
t.Fatal("Failed to get ClosedCB")
}
recv := int(atomic.LoadInt64(&received))
if recv != 0 {
t.Fatalf("Should not have received messages, got: %d", recv)
}
close(done)
checkErrChannel(t, errCh)
}
func TestErrStaleConnection(t *testing.T) {
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
dch := make(chan bool)
rch := make(chan bool)
cch := make(chan bool)
sch := make(chan bool)
firstDisconnect := true
errCh := make(chan error, 1)
go func() {
for i := 0; i < 2; i++ {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
if i == 0 {
// Wait a tiny, and simulate a Stale Connection
time.Sleep(50 * time.Millisecond)
conn.Write([]byte("-ERR 'Stale Connection'\r\n"))
// The client should try to reconnect. When getting the
// disconnected callback, it will close this channel.
<-sch
// Close the connection and go back to accept the new
// connection.
conn.Close()
} else {
// Hang around a bit
<-done
}
}
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.AllowReconnect = true
opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) {
// Interested only in the first disconnect cb
if firstDisconnect {
firstDisconnect = false
close(sch)
dch <- true
}
}
opts.ReconnectedCB = func(_ *nats.Conn) { rch <- true }
opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
opts.ReconnectWait = 20 * time.Millisecond
nats.ReconnectJitter(0, 0)(&opts)
opts.MaxReconnect = 100
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
// We should first gets disconnected
if err := Wait(dch); err != nil {
t.Fatal("Failed to get DisconnectedErrCB")
}
// Then reconneted..
if err := Wait(rch); err != nil {
t.Fatal("Failed to get ReconnectedCB")
}
// Now close the connection
nc.Close()
// We should get the closed cb
if err := Wait(cch); err != nil {
t.Fatal("Failed to get ClosedCB")
}
close(done)
checkErrChannel(t, errCh)
}
func TestServerErrorClosesConnection(t *testing.T) {
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
dch := make(chan bool)
cch := make(chan bool)
serverSentError := "Any Error"
reconnected := int64(0)
errCh := make(chan error, 1)
go func() {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Wait a tiny, and simulate a Stale Connection
time.Sleep(50 * time.Millisecond)
conn.Write([]byte("-ERR '" + serverSentError + "'\r\n"))
// Hang around a bit
<-done
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.AllowReconnect = true
opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) { dch <- true }
opts.ReconnectedCB = func(_ *nats.Conn) { atomic.AddInt64(&reconnected, 1) }
opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
opts.ReconnectWait = 20 * time.Millisecond
nats.ReconnectJitter(0, 0)(&opts)
opts.MaxReconnect = 100
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
// The server sends an error that should cause the client to simply close
// the connection.
// We should first gets disconnected
if err := Wait(dch); err != nil {
t.Fatal("Failed to get DisconnectedErrCB")
}
// We should get the closed cb
if err := Wait(cch); err != nil {
t.Fatal("Failed to get ClosedCB")
}
// We should not have been reconnected
if atomic.LoadInt64(&reconnected) != 0 {
t.Fatal("ReconnectedCB should not have been invoked")
}
// Check LastError(), it should be "nats: <server error in lower case>"
lastErr := nc.LastError().Error()
expectedErr := "nats: " + serverSentError
if lastErr != expectedErr {
t.Fatalf("Expected error: '%v', got '%v'", expectedErr, lastErr)
}
close(done)
checkErrChannel(t, errCh)
}
func TestUseDefaultTimeout(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
opts := &nats.Options{
Servers: []string{nats.DefaultURL},
}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc.Close()
if nc.Opts.Timeout != nats.DefaultTimeout {
t.Fatalf("Expected Timeout to be set to %v, got %v", nats.DefaultTimeout, nc.Opts.Timeout)
}
}
func TestLastErrorNoRace(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
// Access LastError in disconnection and closed handlers to make sure
// that there is no race. It is possible in some cases that
// nc.LastError() returns a non nil error. We don't care here about the
// returned value.
dch := func(c *nats.Conn) {
c.LastError()
}
closedCh := make(chan struct{})
cch := func(c *nats.Conn) {
c.LastError()
closedCh <- struct{}{}
}
nc, err := nats.Connect(nats.DefaultURL,
nats.DisconnectHandler(dch),
nats.ClosedHandler(cch),
nats.MaxReconnects(-1),
nats.ReconnectWait(5*time.Millisecond),
nats.ReconnectJitter(0, 0))
if err != nil {
t.Fatalf("Unable to connect: %v\n", err)
}
defer nc.Close()
// Restart the server several times to trigger a reconnection.
for i := 0; i < 10; i++ {
s.Shutdown()
time.Sleep(10 * time.Millisecond)
s = RunDefaultServer()
}
nc.Close()
s.Shutdown()
select {
case <-closedCh:
case <-time.After(5 * time.Second):
t.Fatal("Timeout waiting for the closed callback")
}
}
type customDialer struct {
ch chan bool
}
func (cd *customDialer) Dial(network, address string) (net.Conn, error) {
cd.ch <- true
return nil, errors.New("on purpose")
}
func TestUseCustomDialer(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
dialer := &net.Dialer{
Timeout: 10 * time.Second,
FallbackDelay: -1,
}
opts := &nats.Options{
Servers: []string{nats.DefaultURL},
Dialer: dialer,
}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc.Close()
if nc.Opts.Dialer != dialer {
t.Fatalf("Expected Dialer to be set to %v, got %v", dialer, nc.Opts.Dialer)
}
// Should be possible to set via variadic func based Option setter
dialer2 := &net.Dialer{
Timeout: 5 * time.Second,
FallbackDelay: -1,
}
nc2, err := nats.Connect(nats.DefaultURL, nats.Dialer(dialer2))
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc2.Close()
if nc2.Opts.Dialer.FallbackDelay > 0 {
t.Fatalf("Expected for dialer to be customized to disable dual stack support")
}
// By default, dialer still uses the DefaultTimeout
nc3, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc3.Close()
if nc3.Opts.Dialer.Timeout != nats.DefaultTimeout {
t.Fatalf("Expected Dialer.Timeout to be set to %v, got %v", nats.DefaultTimeout, nc.Opts.Dialer.Timeout)
}
// Create custom dialer that return error on Dial().
cdialer := &customDialer{ch: make(chan bool, 10)}
// When both Dialer and CustomDialer are set, CustomDialer
// should take precedence. That means that the connection
// should fail for these two set of options.
options := []*nats.Options{
{Dialer: dialer, CustomDialer: cdialer},
{CustomDialer: cdialer},
}
for _, o := range options {
o.Servers = []string{nats.DefaultURL}
nc, err := o.Connect()
// As of now, Connect() would not return the actual dialer error,
// instead it returns "no server available for connections".
// So use go channel to ensure that custom dialer's Dial() method
// was invoked.
if err == nil {
if nc != nil {
nc.Close()
}
t.Fatal("Expected error, got none")
}
if err := Wait(cdialer.ch); err != nil {
t.Fatal("Did not get our notification")
}
}
// Same with variadic
foptions := [][]nats.Option{
{nats.Dialer(dialer), nats.SetCustomDialer(cdialer)},
{nats.SetCustomDialer(cdialer)},
}
for _, fos := range foptions {
nc, err := nats.Connect(nats.DefaultURL, fos...)
if err == nil {
if nc != nil {
nc.Close()
}
t.Fatal("Expected error, got none")
}
if err := Wait(cdialer.ch); err != nil {
t.Fatal("Did not get our notification")
}
}
}
func TestDefaultOptionsDialer(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
opts1 := nats.GetDefaultOptions()
opts2 := nats.GetDefaultOptions()
nc1, err := opts1.Connect()
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc1.Close()
nc2, err := opts2.Connect()
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc2.Close()
if nc1.Opts.Dialer == nc2.Opts.Dialer {
t.Fatalf("Expected each connection to have its own dialer")
}
}
type lowWriteBufferDialer struct{}
func (d *lowWriteBufferDialer) Dial(network, address string) (net.Conn, error) {
c, err := net.Dial(network, address)
if err != nil {
return nil, err
}
c.(*net.TCPConn).SetWriteBuffer(100)
return c, nil
}
func TestCustomFlusherTimeout(t *testing.T) {
if runtime.GOOS == "windows" {
t.SkipNow()
}
s := RunDefaultServer()
defer s.Shutdown()
// Reasonably large flusher timeout will not induce errors
// when we can flush fast
nc1, err := nats.Connect(nats.DefaultURL, nats.FlusherTimeout(10*time.Second))
if err != nil {
t.Fatalf("Expected to be able to connect, got: %s", err)
}
doneCh := make(chan struct{}, 1)
// We want to have a payload size that is big enough so that after
// few publish, the socket buffer will be full and produce the timeout.
// Since we try to produce the error in the flusher and not the publish
// call itself, use a size that is a bit less than the internal
// buffer used by the library.
payloadBytes := make([]byte, 32*1024-200)
errCh := make(chan error, 1)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
for {
select {
case <-time.After(200 * time.Millisecond):
err := nc1.Publish("hello", payloadBytes)
if err != nil {
errCh <- err
return
}
case <-doneCh:
return
}
}
}()
defer nc1.Close()
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
fsDoneCh := make(chan struct{}, 1)
fsErrCh := make(chan error, 1)
go func() {
defer wg.Done()
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":%d}\r\n"
conn, err := l.Accept()
if err != nil {
fsErrCh <- err
return
}
defer conn.Close()
// Make it small on purpose
if err := conn.(*net.TCPConn).SetReadBuffer(1024); err != nil {
fsErrCh <- err
return
}
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port, 1024*1024)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
line := make([]byte, 100)
_, err = conn.Read(line)
if err != nil {
fsErrCh <- fmt.Errorf("Expected CONNECT and PING from client, got: %v", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Don't consume anything at this point and wait to be notified
// that we are done.
<-fsDoneCh
fsErrCh <- nil
}()
nc2, err := nats.Connect(
// URL to fake server
fmt.Sprintf("nats://127.0.0.1:%d", addr.Port),
// Use custom dialer so we can set write buffer to low value
nats.SetCustomDialer(&lowWriteBufferDialer{}),
// Use short flusher timeout to trigger the error
nats.FlusherTimeout(15*time.Millisecond),
// Make sure the library does not close connection due
// to pings for this test.
nats.PingInterval(20*time.Second),
// No reconnect
nats.NoReconnect(),
// Notify when connection lost
nats.ClosedHandler(func(_ *nats.Conn) {
doneCh <- struct{}{}
}),
// Use error handler to silence the stderr output
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {
}))
if err != nil {
t.Fatalf("Expected to be able to connect, got: %s", err)
}
defer nc2.Close()
var (
pubErr error
nc2Err error
tm = time.NewTimer(5 * time.Second)
)
forLoop:
for {
select {
case <-time.After(100 * time.Millisecond):
// We are trying to get the flusher to report the error, but it
// is possible that the Publish() call itself flushes and we don't
// want to fail the test for that.
pubErr = nc2.Publish("world", payloadBytes)
nc2Err = nc2.LastError()
if nc2Err != nil {
break forLoop
}
case <-tm.C:
// We got an error, but not from flusher. Don't fail yet. Will check
// if this is a timeout error as expected.
if pubErr != nil {
break forLoop
}
t.Fatalf("Timeout publishing messages")
}
}
// Notify fake server that it can stop
close(fsDoneCh)
// Wait for go routines to end
wg.Wait()
// Make sure there were no error in the fake server
if err := <-fsErrCh; err != nil {
t.Fatalf("Fake server reported: %v", err)
}
// One of those two are guaranteed to be set.
err = nc2Err
if err == nil {
err = pubErr
}
// Check that error is a timeout error as expected.
ope, ok := err.(*net.OpError)
if !ok {
t.Fatalf("expected a net.Error, got %v", err)
}
if !ope.Timeout() {
t.Fatalf("expected a timeout, got %v", err)
}
if ope.Op != "write" {
t.Fatalf("expected a write error, got %v", err)
}
// Check that there is no error from nc1
select {
case e := <-errCh:
t.Fatal(e)
default:
}
}
func TestNewServers(t *testing.T) {
s1Opts := test.DefaultTestOptions
s1Opts.Host = "127.0.0.1"
s1Opts.Port = 4222
s1Opts.Cluster.Host = "127.0.0.1"
s1Opts.Cluster.Port = 6222
s1 := test.RunServer(&s1Opts)
defer s1.Shutdown()
s2Opts := test.DefaultTestOptions
s2Opts.Host = "127.0.0.1"
s2Opts.Port = 4223
s2Opts.Port = s1Opts.Port + 1
s2Opts.Cluster.Host = "127.0.0.1"
s2Opts.Cluster.Port = 6223
s2Opts.Routes = server.RoutesFromStr("nats://127.0.0.1:6222")
s2 := test.RunServer(&s2Opts)
defer s2.Shutdown()
ch := make(chan bool)
cb := func(_ *nats.Conn) {
ch <- true
}
url := fmt.Sprintf("nats://%s:%d", s1Opts.Host, s1Opts.Port)
nc1, err := nats.Connect(url, nats.DiscoveredServersHandler(cb))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc1.Close()
nc2, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc2.Close()
nc2.SetDiscoveredServersHandler(cb)
opts := nats.GetDefaultOptions()
opts.Url = nats.DefaultURL
opts.DiscoveredServersCB = cb
nc3, err := opts.Connect()
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc3.Close()
// Make sure that handler is not invoked on initial connect.
select {
case <-ch:
t.Fatalf("Handler should not have been invoked")
case <-time.After(500 * time.Millisecond):
}
// Start a new server.
s3Opts := test.DefaultTestOptions
s1Opts.Host = "127.0.0.1"
s1Opts.Port = 4224
s3Opts.Port = s2Opts.Port + 1
s3Opts.Cluster.Host = "127.0.0.1"
s3Opts.Cluster.Port = 6224
s3Opts.Routes = server.RoutesFromStr("nats://127.0.0.1:6222")
s3 := test.RunServer(&s3Opts)
defer s3.Shutdown()
// The callbacks should have been invoked
if err := Wait(ch); err != nil {
t.Fatal("Did not get our callback")
}
if err := Wait(ch); err != nil {
t.Fatal("Did not get our callback")
}
if err := Wait(ch); err != nil {
t.Fatal("Did not get our callback")
}
}
func TestBarrier(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
pubMsgs := int32(0)
ch := make(chan bool, 1)
sub1, err := nc.Subscribe("pub", func(_ *nats.Msg) {
atomic.AddInt32(&pubMsgs, 1)
time.Sleep(250 * time.Millisecond)
})
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
sub2, err := nc.Subscribe("close", func(_ *nats.Msg) {
// The "close" message was sent/received lat, but
// because we are dealing with different subscriptions,
// which are dispatched by different dispatchers, and
// because the "pub" subscription is delayed, this
// callback is likely to be invoked before the sub1's
// second callback is invoked. Using the Barrier call
// here will ensure that the given function will be invoked
// after the preceding messages have been dispatched.
nc.Barrier(func() {
res := atomic.LoadInt32(&pubMsgs) == 2
ch <- res
})
})
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
// Send 2 "pub" messages followed by a "close" message
for i := 0; i < 2; i++ {
if err := nc.Publish("pub", []byte("pub msg")); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
if err := nc.Publish("close", []byte("closing")); err != nil {
t.Fatalf("Error on publish: %v", err)
}
select {
case ok := <-ch:
if !ok {
t.Fatal("The barrier function was invoked before the second message")
}
case <-time.After(2 * time.Second):
t.Fatal("Waited for too long...")
}
// Remove all subs
sub1.Unsubscribe()
sub2.Unsubscribe()
// Barrier should be invoked in place. Since we use buffered channel
// we are ok.
nc.Barrier(func() { ch <- true })
if err := Wait(ch); err != nil {
t.Fatal("Barrier function was not invoked")
}
if _, err := nc.Subscribe("foo", func(m *nats.Msg) {
// To check that the Barrier() function works if the subscription
// is unsubscribed after the call was made, sleep a bit here.
time.Sleep(250 * time.Millisecond)
m.Sub.Unsubscribe()
}); err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := nc.Publish("foo", []byte("hello")); err != nil {
t.Fatalf("Error on publish: %v", err)
}
// We need to Flush here to make sure that message has been received
// and posted to subscription's internal queue before calling Barrier.
if err := nc.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
nc.Barrier(func() { ch <- true })
if err := Wait(ch); err != nil {
t.Fatal("Barrier function was not invoked")
}
// Test with AutoUnsubscribe now...
sub1, err = nc.Subscribe("foo", func(m *nats.Msg) {
// Since we auto-unsubscribe with 1, there should not be another
// invocation of this callback, but the Barrier should still be
// invoked.
nc.Barrier(func() { ch <- true })
})
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
sub1.AutoUnsubscribe(1)
// Send 2 messages and flush
for i := 0; i < 2; i++ {
if err := nc.Publish("foo", []byte("hello")); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
if err := nc.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// Check barrier was invoked
if err := Wait(ch); err != nil {
t.Fatal("Barrier function was not invoked")
}
// Check that Barrier only affects asynchronous subscriptions
sub1, err = nc.Subscribe("foo", func(m *nats.Msg) {
nc.Barrier(func() { ch <- true })
})
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
syncSub, err := nc.SubscribeSync("foo")
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
msgChan := make(chan *nats.Msg, 1)
chanSub, err := nc.ChanSubscribe("foo", msgChan)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := nc.Publish("foo", []byte("hello")); err != nil {
t.Fatalf("Error on publish: %v", err)
}
if err := nc.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// Check barrier was invoked even if we did not yet consume
// from the 2 other type of subscriptions
if err := Wait(ch); err != nil {
t.Fatal("Barrier function was not invoked")
}
if _, err := syncSub.NextMsg(time.Second); err != nil {
t.Fatalf("Sync sub did not receive the message")
}
select {
case <-msgChan:
case <-time.After(time.Second):
t.Fatal("Chan sub did not receive the message")
}
chanSub.Unsubscribe()
syncSub.Unsubscribe()
sub1.Unsubscribe()
atomic.StoreInt32(&pubMsgs, 0)
// Check barrier does not prevent new messages to be delivered.
sub1, err = nc.Subscribe("foo", func(_ *nats.Msg) {
if pm := atomic.AddInt32(&pubMsgs, 1); pm == 1 {
nc.Barrier(func() {
nc.Publish("foo", []byte("second"))
nc.Flush()
})
} else if pm == 2 {
ch <- true
}
})
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := nc.Publish("foo", []byte("first")); err != nil {
t.Fatalf("Error on publish: %v", err)
}
if err := Wait(ch); err != nil {
t.Fatal("Barrier function was not invoked")
}
sub1.Unsubscribe()
// Check that barrier works if called before connection
// is closed.
if _, err := nc.Subscribe("bar", func(_ *nats.Msg) {
nc.Barrier(func() { ch <- true })
nc.Close()
}); err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := nc.Publish("bar", []byte("hello")); err != nil {
t.Fatalf("Error on publish: %v", err)
}
// This could fail if the connection is closed before we get
// here.
nc.Flush()
if err := Wait(ch); err != nil {
t.Fatal("Barrier function was not invoked")
}
// Finally, check that if connection is closed, Barrier returns
// an error.
if err := nc.Barrier(func() { ch <- true }); err != nats.ErrConnectionClosed {
t.Fatalf("Expected error %v, got %v", nats.ErrConnectionClosed, err)
}
// Check that one can call connection methods from Barrier
// when there is no async subscriptions
nc = NewDefaultConnection(t)
defer nc.Close()
if err := nc.Barrier(func() {
ch <- nc.TLSRequired()
}); err != nil {
t.Fatalf("Error on Barrier: %v", err)
}
if err := Wait(ch); err != nil {
t.Fatal("Barrier was blocked")
}
}
func TestReceiveInfoRightAfterFirstPong(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("Error on listen: %v", err)
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
c, err := tl.Accept()
if err != nil {
return
}
defer c.Close()
// Send the initial INFO
c.Write([]byte("INFO {}\r\n"))
buf := make([]byte, 0, 100)
b := make([]byte, 100)
for {
n, err := c.Read(b)
if err != nil {
return
}
buf = append(buf, b[:n]...)
if bytes.Contains(buf, []byte("PING\r\n")) {
break
}
}
// Send PONG and following INFO in one go (or at least try).
// The processing of PONG in sendConnect() should leave the
// rest for the readLoop to process.
c.Write([]byte(fmt.Sprintf("PONG\r\nINFO {\"connect_urls\":[\"127.0.0.1:%d\", \"me:1\"]}\r\n", addr.Port)))
// Wait for client to disconnect
for {
if _, err := c.Read(buf); err != nil {
return
}
}
}()
nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", addr.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc.Close()
var (
ds []string
timeout = time.Now().Add(2 * time.Second)
ok = false
)
for time.Now().Before(timeout) {
ds = nc.DiscoveredServers()
if len(ds) == 1 && ds[0] == "nats://me:1" {
ok = true
break
}
time.Sleep(50 * time.Millisecond)
}
nc.Close()
wg.Wait()
if !ok {
t.Fatalf("Unexpected discovered servers: %v", ds)
}
}
func TestReceiveInfoWithEmptyConnectURLs(t *testing.T) {
ready := make(chan error, 2)
ch := make(chan bool, 1)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
ports := []int{4222, 4223}
for i := 0; i < 2; i++ {
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", ports[i]))
if err != nil {
ready <- fmt.Errorf("error on listen: %v", err)
return
}
tl := l.(*net.TCPListener)
defer tl.Close()
ready <- nil
c, err := tl.Accept()
if err != nil {
return
}
defer c.Close()
// Send the initial INFO
c.Write([]byte(fmt.Sprintf("INFO {\"server_id\":\"server%d\"}\r\n", (i + 1))))
buf := make([]byte, 0, 100)
b := make([]byte, 100)
for {
n, err := c.Read(b)
if err != nil {
return
}
buf = append(buf, b[:n]...)
if bytes.Contains(buf, []byte("PING\r\n")) {
break
}
}
if i == 0 {
// Send PONG and following INFO in one go (or at least try).
// The processing of PONG in sendConnect() should leave the
// rest for the readLoop to process.
c.Write([]byte("PONG\r\nINFO {\"server_id\":\"server1\",\"connect_urls\":[\"127.0.0.1:4222\", \"127.0.0.1:4223\", \"127.0.0.1:4224\"]}\r\n"))
// Wait for the notification
<-ch
// Close the connection in our side and go back into accept
c.Close()
} else {
// Send no connect ULRs (as if this was an older server that could in some cases
// send an empty array)
c.Write([]byte("PONG\r\nINFO {\"server_id\":\"server2\"}\r\n"))
// Wait for client to disconnect
for {
if _, err := c.Read(buf); err != nil {
return
}
}
}
}
}()
// Wait for listener to be up and running
e := <-ready
if e != nil {
t.Fatal(e.Error())
}
rch := make(chan bool)
nc, err := nats.Connect("nats://127.0.0.1:4222",
nats.ReconnectWait(50*time.Millisecond),
nats.ReconnectJitter(0, 0),
nats.ReconnectHandler(func(_ *nats.Conn) {
rch <- true
}))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc.Close()
var (
ds []string
timeout = time.Now().Add(2 * time.Second)
ok = false
)
for time.Now().Before(timeout) {
ds = nc.DiscoveredServers()
if len(ds) == 2 {
if (ds[0] == "nats://127.0.0.1:4223" && ds[1] == "nats://127.0.0.1:4224") ||
(ds[0] == "nats://127.0.0.1:4224" && ds[1] == "nats://127.0.0.1:4223") {
ok = true
break
}
}
time.Sleep(50 * time.Millisecond)
}
if !ok {
t.Fatalf("Unexpected discovered servers: %v", ds)
}
// Make the server close our connection
ch <- true
// Wait for the reconnect
if err := Wait(rch); err != nil {
t.Fatal("Did not reconnect")
}
// Discovered servers should still contain nats://me:1
ds = nc.DiscoveredServers()
if len(ds) != 2 ||
!((ds[0] == "nats://127.0.0.1:4223" && ds[1] == "nats://127.0.0.1:4224") ||
(ds[0] == "nats://127.0.0.1:4224" && ds[1] == "nats://127.0.0.1:4223")) {
t.Fatalf("Unexpected discovered servers list: %v", ds)
}
nc.Close()
wg.Wait()
}
func TestConnectWithSimplifiedURLs(t *testing.T) {
urls := []string{
"nats://127.0.0.1:4222",
"nats://127.0.0.1:",
"nats://127.0.0.1",
"127.0.0.1:",
"127.0.0.1",
}
connect := func(t *testing.T, url string, useRootCA bool) {
t.Helper()
var opt nats.Option
if useRootCA {
opt = nats.RootCAs("./configs/certs/ca.pem")
}
nc, err := nats.Connect(url, opt)
if err != nil {
t.Fatalf("URL %q expected to connect, got %v", url, err)
}
nc.Close()
}
// Start a server that listens on default port 4222.
s := RunDefaultServer()
defer s.Shutdown()
// Try for every connection in the urls array.
for _, u := range urls {
connect(t, u, false)
}
s.Shutdown()
// Use this to build the options for us...
s, opts := RunServerWithConfig("configs/tls.conf")
s.Shutdown()
// Now change listen port to 4222 and remove auth
opts.Port = 4222
opts.Username = ""
opts.Password = ""
// and restart the server
s = RunServerWithOptions(opts)
defer s.Shutdown()
// Test again against a server that wants TLS and check
// that we automatically switch to Secure.
for _, u := range urls {
connect(t, u, true)
}
}
func TestNilOpts(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
// Test a single nil option
var o1, o2, o3 nats.Option
nc, err := nats.Connect(nats.DefaultURL, o1)
if err != nil {
t.Fatalf("Unexpected error with one nil option: %v", err)
}
nc.Close()
// Test nil, opt, nil
o2 = nats.ReconnectBufSize(2222)
nc, err = nats.Connect(nats.DefaultURL, o1, o2, o3)
if err != nil {
t.Fatalf("Unexpected error with multiple nil options: %v", err)
}
defer nc.Close()
// check that the opt was set
if nc.Opts.ReconnectBufSize != 2222 {
t.Fatal("Unexpected error: option not set.")
}
}
func TestGetClientID(t *testing.T) {
if serverVersionAtLeast(1, 2, 0) != nil {
t.SkipNow()
}
optsA := test.DefaultTestOptions
optsA.Port = -1
optsA.Cluster.Port = -1
optsA.Cluster.Name = "test"
srvA := RunServerWithOptions(&optsA)
defer srvA.Shutdown()
ch := make(chan bool, 1)
nc1, err := nats.Connect(srvA.ClientURL(),
nats.DiscoveredServersHandler(func(_ *nats.Conn) {
ch <- true
}),
nats.ReconnectHandler(func(_ *nats.Conn) {
ch <- true
}))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc1.Close()
cid, err := nc1.GetClientID()
if err != nil {
t.Fatalf("Error getting CID: %v", err)
}
if cid == 0 {
t.Fatal("Unexpected cid value, make sure server is 1.2.0+")
}
// Start a second server and verify that async INFO contains client ID
optsB := test.DefaultTestOptions
optsB.Port = -1
optsB.Cluster.Port = -1
optsB.Cluster.Name = "test"
optsB.Routes = server.RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port))
srvB := RunServerWithOptions(&optsB)
defer srvB.Shutdown()
// Wait for the discovered callback to fire
if err := Wait(ch); err != nil {
t.Fatal("Did not fire the discovered callback")
}
// Now check CID should be valid and same as before
newCID, err := nc1.GetClientID()
if err != nil {
t.Fatalf("Error getting CID: %v", err)
}
if newCID != cid {
t.Fatalf("Expected CID to be %v, got %v", cid, newCID)
}
// Create a client to server B
nc2, err := nats.Connect(srvB.ClientURL())
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc2.Close()
// Stop server A, nc1 will reconnect to B, and should have different CID
srvA.Shutdown()
// Wait for nc1 to reconnect
if err := Wait(ch); err != nil {
t.Fatal("Did not reconnect")
}
newCID, err = nc1.GetClientID()
if err != nil {
t.Fatalf("Error getting CID: %v", err)
}
if newCID == 0 {
t.Fatal("Unexpected cid value, make sure server is 1.2.0+")
}
if newCID == cid {
t.Fatalf("Expected different CID since server already had a client")
}
nc1.Close()
newCID, err = nc1.GetClientID()
if err == nil {
t.Fatalf("Expected error, got none")
}
if newCID != 0 {
t.Fatalf("Expected 0 on connection closed, got %v", newCID)
}
// Stop clients and remaining server
nc1.Close()
nc2.Close()
srvB.Shutdown()
// Now have dummy server that returns no CID and check we get expected error.
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
wg := sync.WaitGroup{}
wg.Add(1)
errCh := make(chan error, 1)
go func() {
defer wg.Done()
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf("INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n", addr.IP, addr.Port)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
line := make([]byte, 256)
_, err = conn.Read(line)
if err != nil {
errCh <- fmt.Errorf("expected CONNECT and PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Now wait to be notified that we can finish
<-ch
}()
nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", addr.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc.Close()
if cid, err := nc.GetClientID(); err != nats.ErrClientIDNotSupported || cid != 0 {
t.Fatalf("Expected err=%v and cid=0, got err=%v and cid=%v", nats.ErrClientIDNotSupported, err, cid)
}
// Release fake server
nc.Close()
ch <- true
wg.Wait()
checkErrChannel(t, errCh)
}
func TestTLSDontSkipVerify(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tls_noip_a.conf")
defer s.Shutdown()
// Connect with nats:// prefix to a server that requires TLS.
// The library will automatically switch to TLS, but we should
// not skip hostname verification.
sURL := fmt.Sprintf("nats://derek:porkchop@127.0.0.1:%d", opts.Port)
nc, err := nats.Connect(sURL, nats.RootCAs("./configs/certs/ca.pem"))
// Verify that error is about hostname verification
if err == nil || !strings.Contains(err.Error(), "IP SAN") {
if nc != nil {
nc.Close()
}
t.Fatalf("Expected error about hostname verification, got %v", err)
}
// Check that we can override skip verify by providing our own TLS Config.
nc, err = nats.Connect(sURL, nats.RootCAs("./configs/certs/ca.pem"),
nats.Secure(&tls.Config{InsecureSkipVerify: true}))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
nc.Close()
// Now change the URL to include hostname and verify that using
// nats:// scheme does work.
sURL = fmt.Sprintf("nats://derek:porkchop@%s:%d", opts.Host, opts.Port)
nc, err = nats.Connect(sURL, nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
nc.Close()
}
func TestRetryOnFailedConnect(t *testing.T) {
nc, err := nats.Connect(nats.DefaultURL)
if err == nil {
nc.Close()
t.Fatal("Expected error, did not get one")
}
reconnectedCh := make(chan bool, 1)
connectedCh := make(chan bool, 1)
dch := make(chan bool, 1)
nc, err = nats.Connect(nats.DefaultURL,
nats.RetryOnFailedConnect(true),
nats.MaxReconnects(-1),
nats.ReconnectWait(15*time.Millisecond),
nats.DisconnectErrHandler(func(_ *nats.Conn, _ error) {
dch <- true
}),
nats.ConnectHandler(func(_ *nats.Conn) {
connectedCh <- true
}),
nats.ReconnectHandler(func(_ *nats.Conn) {
reconnectedCh <- true
}),
nats.NoCallbacksAfterClientClose())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
sub, err := nc.SubscribeSync("foo")
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := nc.Publish("foo", []byte("msg")); err != nil {
t.Fatalf("Error on publish: %v", err)
}
for i := 0; i < 2; i++ {
// Start server now
s := RunDefaultServer()
defer s.Shutdown()
switch i {
case 0:
select {
case <-connectedCh:
case <-time.After(2 * time.Second):
t.Fatal("Should have connected")
}
case 1:
select {
case <-reconnectedCh:
case <-time.After(2 * time.Second):
t.Fatal("Should have reconnected")
}
}
// Now make sure that the pub worked and sub worked.
// We should receive the message we have published.
if _, err := sub.NextMsg(time.Second); err != nil {
t.Fatalf("Iter=%v - did not receive message: %v", i, err)
}
// Check that normal disconnect/reconnect works as expected
s.Shutdown()
select {
case <-dch:
case <-time.After(time.Second):
t.Fatal("Should have been disconnected")
}
if i == 0 {
if err := nc.Publish("foo", []byte("msg")); err != nil {
t.Fatalf("Iter=%v - error on publish: %v", i, err)
}
}
}
nc.Close()
// Try again but this time we will restart a server with u/p and auth should fail.
closedCh := make(chan bool, 1)
nc, err = nats.Connect(nats.DefaultURL,
nats.RetryOnFailedConnect(true),
nats.MaxReconnects(-1),
nats.ReconnectWait(15*time.Millisecond),
nats.ReconnectHandler(func(_ *nats.Conn) {
reconnectedCh <- true
}),
nats.ClosedHandler(func(_ *nats.Conn) {
closedCh <- true
}))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer nc.Close()
o := test.DefaultTestOptions
o.Host = "127.0.0.1"
o.Port = 4222
o.Username = "user"
o.Password = "password"
s := RunServerWithOptions(&o)
defer s.Shutdown()
select {
case <-closedCh:
case <-time.After(2 * time.Second):
t.Fatal("Should have stopped trying to connect due to auth failure")
}
// Make sure that we did not get the (re)connected CB
select {
case <-reconnectedCh:
t.Fatal("(re)connected callback should not have been invoked")
default:
}
}
func TestRetryOnFailedConnectWithTLSError(t *testing.T) {
opts := test.DefaultTestOptions
opts.Port = 4222
tc := &server.TLSConfigOpts{
CertFile: "./configs/certs/server.pem",
KeyFile: "./configs/certs/key.pem",
CaFile: "./configs/certs/ca.pem",
}
var err error
if opts.TLSConfig, err = server.GenTLSConfig(tc); err != nil {
t.Fatalf("Can't build TLCConfig: %v", err)
}
opts.TLSTimeout = 0.0001
s := RunServerWithOptions(&opts)
defer s.Shutdown()
connectedCh := make(chan bool, 1)
nc, err := nats.Connect(nats.DefaultURL,
nats.Secure(&tls.Config{InsecureSkipVerify: true}),
nats.RetryOnFailedConnect(true),
nats.MaxReconnects(-1),
nats.ReconnectWait(15*time.Millisecond),
nats.ConnectHandler(func(_ *nats.Conn) {
connectedCh <- true
}),
nats.NoCallbacksAfterClientClose())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer nc.Close()
// Wait for several failed attempts
time.Sleep(100 * time.Millisecond)
// Replace tls timeout to a reasonable value.
s.Shutdown()
opts.TLSTimeout = 2.0
s = RunServerWithOptions(&opts)
defer s.Shutdown()
select {
case <-connectedCh:
case <-time.After(time.Second):
t.Fatal("Should have connected")
}
}
func TestConnStatusChangedEvents(t *testing.T) {
t.Run("default events", func(t *testing.T) {
s := RunDefaultServer()
nc, err := nats.Connect(s.ClientURL())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
statusCh := nc.StatusChanged()
defer close(statusCh)
newStatus := make(chan nats.Status, 10)
// non-blocking channel, so we need to be constantly listening
go func() {
for {
s, ok := <-statusCh
if !ok {
return
}
newStatus <- s
}
}()
time.Sleep(50 * time.Millisecond)
s.Shutdown()
WaitOnChannel(t, newStatus, nats.RECONNECTING)
s = RunDefaultServer()
defer s.Shutdown()
WaitOnChannel(t, newStatus, nats.CONNECTED)
nc.Close()
WaitOnChannel(t, newStatus, nats.CLOSED)
select {
case s := <-newStatus:
t.Fatalf("Unexpected status received: %s", s)
case <-time.After(100 * time.Millisecond):
}
})
t.Run("custom event only", func(t *testing.T) {
s := RunDefaultServer()
nc, err := nats.Connect(s.ClientURL())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
statusCh := nc.StatusChanged(nats.CLOSED)
defer close(statusCh)
newStatus := make(chan nats.Status, 10)
// non-blocking channel, so we need to be constantly listening
go func() {
for {
s, ok := <-statusCh
if !ok {
return
}
newStatus <- s
}
}()
time.Sleep(50 * time.Millisecond)
s.Shutdown()
s = RunDefaultServer()
defer s.Shutdown()
nc.Close()
WaitOnChannel(t, newStatus, nats.CLOSED)
select {
case s := <-newStatus:
t.Fatalf("Unexpected status received: %s", s)
case <-time.After(100 * time.Millisecond):
}
})
t.Run("do not block on channel if it's not used", func(t *testing.T) {
s := RunDefaultServer()
nc, err := nats.Connect(s.ClientURL())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
defer nc.Close()
// do not use the returned channel, client should never block
_ = nc.StatusChanged()
s.Shutdown()
s = RunDefaultServer()
defer s.Shutdown()
if err := nc.Publish("foo", []byte("msg")); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
time.Sleep(100 * time.Millisecond)
})
}
func TestTLSHandshakeFirst(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tls.conf")
defer s.Shutdown()
secureURL := fmt.Sprintf("tls://derek:porkchop@localhost:%d", opts.Port)
nc, err := nats.Connect(secureURL,
nats.RootCAs("./configs/certs/ca.pem"),
nats.TLSHandshakeFirst())
if err == nil || !strings.Contains(err.Error(), "TLS handshake") {
if err == nil {
nc.Close()
}
t.Fatalf("Expected error about not being a TLS handshake, got %v", err)
}
tc := &server.TLSConfigOpts{
CertFile: "./configs/certs/server.pem",
KeyFile: "./configs/certs/key.pem",
}
tlsConf, err := server.GenTLSConfig(tc)
if err != nil {
t.Fatalf("Can't build TLCConfig: %v", err)
}
tlsConf.ServerName = "localhost"
// Start a mockup server that will do the TLS handshake first
// and then send the INFO protocol.
l, e := net.Listen("tcp", ":0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
errCh := make(chan error, 1)
doneCh := make(chan struct{})
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
// Do the TLS handshake now.
conn = tls.Server(conn, tlsConf)
tlsconn := conn.(*tls.Conn)
if err := tlsconn.Handshake(); err != nil {
errCh <- fmt.Errorf("Server error during handshake: %v", err)
return
}
// Send back the INFO
info := fmt.Sprintf("INFO {\"server_id\":\"foobar\",\"host\":\"localhost\",\"port\":%d,\"auth_required\":false,\"tls_required\":true,\"tls_available\":true,\"tls_verify\":true,\"max_payload\":1048576}\r\n", addr.Port)
tlsconn.Write([]byte(info))
// Read connect and ping commands sent from the client
line := make([]byte, 256)
_, err = tlsconn.Read(line)
if err != nil {
errCh <- fmt.Errorf("expected CONNECT and PING from client, got: %s", err)
return
}
tlsconn.Write([]byte("PONG\r\n"))
// Wait for the signal that client is ok
<-doneCh
// Server is done now.
errCh <- nil
}()
time.Sleep(100 * time.Millisecond)
secureURL = fmt.Sprintf("tls://derek:porkchop@localhost:%d", addr.Port)
nc, err = nats.Connect(secureURL,
nats.RootCAs("./configs/certs/ca.pem"),
nats.TLSHandshakeFirst())
if err != nil {
wg.Wait()
e := <-errCh
t.Fatalf("Unexpected error: %v (server error=%s)", err, e.Error())
}
state, err := nc.TLSConnectionState()
if err != nil {
t.Fatalf("Expected connection state: %v", err)
}
if !state.HandshakeComplete {
t.Fatalf("Expected valid connection state")
}
nc.Close()
close(doneCh)
wg.Wait()
select {
case e := <-errCh:
if e != nil {
t.Fatalf("Error from server: %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("Server did not exit")
}
}
|