All files / qlobber-fsq/lib qlobber-fsq.js

98.03% Statements 2751/2806
91.72% Branches 543/592
100% Functions 86/86
98.03% Lines 2751/2806

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 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 280818x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 49438x 49438x 49438x 49438x 49438x 49438x 49438x 49438x 49438x 49438x 49438x 49438x 49436x 49436x 49438x 49438x 18x 18x 18x 18x 49434x 49434x 49434x 49434x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 6x 6x 6x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1949x 1949x 50x 50x 50x 50x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 192x 192x 192x 152x 152x 76x 76x 76x 76x 76x 76x 152x 152x 152x 152x 152x 192x 192x 1999x 1999x 1999x 1999x 1999x 1999x 74x 74x 1999x 1999x 405527x 405527x 405809x 405809x 405809x 405809x 405809x 405691x 405691x 405539x 405539x 6x 6x 405539x 152x 152x 6x 6x 405691x 405809x 405809x 405809x 405527x 405527x 282x 282x 405809x 405809x 405527x 405527x 405527x 1999x 1999x 405567x 405567x 405567x 1999x 1999x 6247615x 6247615x 6247615x 103139x 103139x 103139x 103139x 79536x 79536x 79050x 79050x 79050x 79536x 103139x 103139x 103139x 4x 4x 103139x 6247615x 6247615x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 145018725x 145018725x 145018725x 1993x 1993x 1993x 145018725x 145018725x 1999x 1999x 1999x 174496x 174496x 174496x 1999x 1999x 1999x 6x 6x 6x 6x 1999x 1999x 549786x 549786x 549786x 549768x 549768x 549786x 1999x 1999x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549793x 549731x 549731x 549731x 62x 62x 62x 62x 62x 62x 62x 62x 55x 55x 55x 62x 549793x 1999x 1999x 57757x 57757x 57757x 57757x 57757x 57757x 57757x 7966x 7966x 49791x 49791x 57757x 57757x 1999x 1999x 373x 373x 373x 373x 373x 373x 373x 142x 142x 142x 142x 142x 142x 231x 373x 373x 373x 1999x 1999x 81082x 81082x 81082x 81082x 81082x 81082x 81082x 81082x 81082x 81082x 81082x 81082x 78923x   81082x 81082x 78923x 78923x 81082x 81082x 81082x 81056x 81056x 26x 26x 26x 26x 26x 26x 26x 26x     26x 26x     26x 26x 26x 81082x 81082x 1999x 1999x 130x 130x 130x                   130x 130x 130x 130x 130x 130x 1999x 1999x 49506x 49506x 49504x 49504x 49503x 49506x 49506x 1999x 1999x 405355x 405355x 405355x 405355x 405355x 405355x 405355x 405355x 405355x 405355x 405355x 405355x 256901x 256901x 45x 45x 256901x 256901x 256901x 148454x 148454x 405724x 405724x 405724x 405724x 405724x 405724x 128x 128x 128x 128x 134x 134x 128x 128x 405724x 405724x 405724x 405724x 405724x 405724x 405249x 405249x 405724x 148454x 148454x 405684x 405684x 405684x 405684x 148454x 148454x 346x 346x 346x 346x 346x 158x 158x 24x 24x 134x 134x 134x 134x 158x 346x 148454x 148454x 148171x 148171x 148171x 148171x 148171x 148171x 148171x 49725x 49725x 49725x 49725x 49725x 369x 369x 369x 168x 168x 201x 201x 201x 201x 201x 201x 201x 201x 341x 69x 69x 369x 49725x 49725x 549x 549x 549x 180x 180x 180x 369x 369x 369x 369x 369x 369x 369x 150x 150x 369x 369x 369x 369x 369x 369x 369x 369x 369x 369x 16x 16x 369x 369x 369x 369x 369x 549x 168x 168x 168x 201x 201x 549x 49725x 49725x 340x 340x 340x 4x 4x 340x 49725x 49725x 209x 209x 209x 197x 197x 196x 196x 196x 196x 196x 196x 196x 66x 66x 130x 130x 130x 130x 196x 196x 197x 197x 209x 67x 67x 130x 130x 209x 49725x 49725x 49725x 49725x 49717x 49717x 49717x 49717x 49717x 197x 197x 49520x 49717x 49516x 49717x 49339x 49339x 49516x 49516x 49717x 41x 41x 49516x 49516x 49717x 177x 177x 49339x 49339x 49725x 49725x 49725x 81x 81x 81x 81x 12x 81x 8x 8x 12x 12x 12x 12x 12x 12x 12x 12x 81x 4x 4x 8x 8x 81x 6x 6x 2x 2x 49725x 49725x 49725x 49725x 49725x 49725x 148171x 148171x 49743x 49743x 49743x 49737x 49737x 49737x 49725x 49725x 49725x 49737x 49743x 49743x 49743x 148171x 148171x 69x 69x 69x 148171x 148171x 148171x 148349x 148349x 305x 305x 12x 12x 293x 293x 293x 148044x 148044x 98538x 98538x 98538x 49506x 49506x 49506x 49506x 49438x 49438x     49438x 49438x 49438x 49438x 49506x 49506x 49506x 49506x 49506x 148349x 148171x 148171x 148171x 98446x 98446x 98446x 98446x 98446x 98446x     148171x 148454x 148454x 405319x 53x 53x 53x 53x 53x 53x 53x 53x     53x 53x 53x 53x 53x 148401x 148401x 405290x 98570x 98570x 98570x 98570x 98570x 136x 136x 136x 136x 98570x 98570x 98570x 49831x 49831x 405355x 405355x 49831x 49831x 49548x 49548x 49548x 49548x 49548x 49548x 49548x 49548x 49548x 49548x 49548x 49831x 49831x 49549x 49549x 49549x 37x 37x 49512x 49512x 49512x 49512x 49512x 1x 1x 49511x 49511x 49511x 49512x 49549x 49831x 49831x 49831x 49831x 49831x 49831x 40x 40x 49791x 49831x 49791x 49791x 49831x 445x 445x 445x 445x 445x 214x 214x 231x 231x 231x 231x 231x 231x 231x 231x 231x 231x 231x 231x 231x 406x 406x 406x 406x 203x 203x 231x 231x 231x 203x 203x 203x     203x 203x 203x 203x         231x 231x 231x 28x 28x 28x 231x 445x 445x 49346x 49346x 49346x 49346x 405355x 405355x 1999x 1999x 1999x 23x 77x 77x 77x 23x 23x 1999x 1999x 405355x 405355x 405355x 77x 77x 77x 77x 77x 77x 77x 405278x 405278x 405278x 405278x 405355x 1999x 1999x 549811x 549811x 549811x 549811x 549811x 549811x 549811x 549811x 549804x 549804x 549804x 549804x 549804x 549804x 549804x 549804x 549804x 549804x 549804x 549804x 549804x 549700x 549700x 549700x 404920x 404920x 549700x 549700x 549700x 227926x 227926x 33966x 33966x 193960x 193960x 193960x 193960x 227926x 549700x 549700x 549700x 641x 641x 549700x 549700x 549700x 549804x 549804x 549811x 80952x 80952x     80952x 80952x 80952x 80952x 80952x 80952x 468852x 468852x 549811x 18892x 18892x 449960x 449960x 549811x 193965x 193965x 193965x 193965x 255995x 255995x 255995x 255995x 255995x 255995x 255995x 255995x 255995x 255995x 449960x 449960x 549811x 405044x 405044x 405044x 449960x 449960x 449960x 449960x 449960x 449960x 549811x 591x 591x 66x 66x 525x 525x 525x 591x 377x 377x 591x 591x 591x 525x 525x 525x 525x 525x 18x 18x 507x 507x 495x 495x 473x 473x 473x 473x 495x 12x 12x 12x 12x 40x 40x 591x 591x 449369x 449369x 549811x 404890x 404890x 404890x 404890x     404890x 44479x 44479x 144x 144x 144x 144x 144x 144x 144x 144x 88x 88x 88x 88x 88x 48x 48x 48x 40x 40x 40x 40x 40x 40x 40x 40x 40x 20x 20x 8x 8x 20x 20x 20x 8x 8x 40x 40x 88x 88x 88x 144x 144x 144x 144x 144x 144x 144x 144x 136x 136x 136x     136x 136x 136x 68x 68x 68x 68x 68x 68x 136x 136x 136x 144x 144x 144x 32x 32x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 44335x 44335x 44335x 44335x 405002x 405002x 405002x 405002x 405002x 405002x 405002x 404870x 404870x 132x 132x 132x 132x 404937x 88x 88x 88x 88x 88x 132x 132x 405002x 549811x 1999x 1999x 249072x 249072x 249072x 249072x 249072x 249072x 249072x 249072x 249072x 249055x 249055x 249055x 249055x 249055x 249055x 249055x 249055x 249055x 249055x 249055x 249072x 1999x 1999x 12x 12x 12x 12x 12x 12x 12x 6000x 6000x 6000x 6000x 6000x 6000x 6000x 6000x 12x 12x 1999x 1999x 4792020x 4792020x 4792020x 4792020x 4792020x 4792020x 4792020x 248540x 248540x 248540x 248540x 248540x 248540x 248540x 248540x 248540x 4792020x 4792020x 1999x 1999x 61237185x 61237185x 61237185x 61237185x 61237185x 61237185x 61237185x 295288x 295288x 295288x 294756x 294756x 294756x 294756x 294756x 294756x 294756x 294756x 532x 532x 532x 532x 532x 532x 532x 532x 532x 61237185x 61237185x 1999x 1999x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709756x 63709756x 63709692x 63709756x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 63709837x 12x 12x 12x 12x 6000x 6000x 6000x 4000x 4000x 2000x 2000x 2000x 2000x 2000x 12x 12x 12x 12x 6000x 6000x 12x 12x 12x 12x 12x 12x 12x 12x 63709825x 63709825x 63709837x 1999x 1999x 61237189x 61237189x 61237189x 61237189x 18470x 18470x 18470x 18470x 18470x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 61237189x 1999x 1999x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472648x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 1749839x 1749839x 2472648x 2472648x 2472648x 2472648x 2472648x 2472648x 2472648x 2472648x 2472648x 2472648x 2472648x 2472648x 2472653x 2472653x 1999x 1999x 254351x 254351x 254351x 254351x 254351x 1977x 1977x 1977x 254351x 254351x 254351x 254136x 254136x 254351x 1999x 1999x 254567x 254567x 254567x 12x 12x 254555x 254555x 254555x 254555x 254555x 254555x 254555x 254518x 254555x 254555x       254518x 254518x 254555x 254567x 1999x 1999x 66029222x 66029222x 66029222x 66029222x 66029222x 66029222x 66029222x 66029222x 66029222x 8607591x 8607591x 8607591x 8606546x 8606546x 8607591x 8607591x 8607591x 66029222x 66029222x 4792033x 4792033x 4792033x 4792033x 4792033x 4792033x 4792033x 4792033x 4792033x 4791958x 4791958x 4791958x 4791958x 4791958x 4791958x 4791958x 4791958x 4791958x 4791958x 4791958x 1473451x 1473451x 3318507x 3318507x 4792033x 4792033x 66029222x 66029222x 66029222x 66017958x 66017958x 66017958x 66017958x 1876787x 1876787x 1876787x 64141171x 64141171x 2123802x 2123802x 66017958x 63905420x 63905420x 63905420x 66024870x 66029222x 66029222x 66029222x 55948021x 55948021x 55948021x 55948021x 55948021x 55948021x 55948021x 7957399x 66029222x 66029222x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 228745x 228745x 228745x 228745x 298738x 298738x 298738x 298738x 298738x 298738x 298738x     298738x 298738x 298738x 298738x 298738x 298738x 298738x 298738x 298738x 298738x 298738x 298738x 298738x 298624x 298624x 298624x 298624x 298624x 298624x 298738x 298738x 298738x 298738x 298738x 298738x 298738x 298738x 228745x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 5289168x 2668231x 2668231x 66029222x 1999x 1999x 254530x 254530x 254530x 254530x 254530x 254530x 66029222x 66029222x 254530x 254530x 1999x 1999x 254567x 254567x 254567x 254567x 254567x 254567x 254567x 1999x 1999x 1999x 509488x 509488x 509488x 509488x 509488x 509488x 1999x 1999x 66686783x 66686783x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1999x 1977x 1977x 1977x 1977x 1977x 1947x 1947x 1947x 391533x 391533x 391533x 391533x 391533x 1947x 1947x 1947x 1947x 1947x         1947x 1977x 1999x 1999x 1981x 1981x 1981x 1981x 1981x 1977x 1977x 1981x 1999x 1999x 1999x 509488x 509488x 509488x 509488x 1999x 1999x 1999x 1999x 1999x 1000x 1000x 254496x 254496x 1000x 1999x 1999x 1999x 1993x 1993x 1993x 1993x 1993x 12x 12x 12x 12x 12x 6x 6x 6x 6x 6x 6x 12x 1993x 1993x 1993x 1993x 1993x 1993x 1993x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x         2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 2472653x 1993x 1993x 1993x 1993x 1993x 1993x 1999x 759x 759x 759x 3x 3x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 6x 6x 6x 756x 759x 759x 9x 9x 6x 6x 3x 3x 3x 3x 9x 759x 1987x 1987x 1999x 506416x 506416x 506416x 506416x 1987x 1987x 1019671x 1019671x 1019671x 1019671x 1019671x 1987x 1987x 1987x 1981x 1981x 1987x 6x 6x 1975x 1975x 1975x 1975x 1975x 1975x 1975x 1987x 1999x 1999x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1422x 1422x 1422x 184x 184x 184x 1422x 1422x 1422x 1422x 1422x 1422x 1422x 104x 104x 1422x 1422x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 68x 68x 68x 6x 6x 6x 6x 68x 68x 68x 14x 14x 14x 8x 8x 14x 54x 54x 22x 22x 22x 16x 16x 22x 32x 32x 32x 32x 32x 24x 24x 32x 68x 68x 68x 68x 18x 18x 151145x 151145x 151145x 151145x 151145x 151145x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 151145x 151145x 151145x 151145x 151145x 65x 65x 65x 65x 151145x 151145x 151145x 170x 170x 170x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151127x 151127x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 151145x 100869x 100869x 100869x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 2x 2x 2x 22x 22x 22x 22x 22x 22x 22x 2x 2x 2x 22x 22x 22x 100847x 100847x 100869x 151145x 151145x 8x 8x 8x 8x 8x 151145x 151145x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 151145x 151145x 251948x 251948x 251948x 251948x 12x 12x 251948x 251948x 251948x 251948x 251948x 251942x 251942x 251942x 251942x 4x 4x 4x 4x 4x 4x 4x 251942x 251948x 251948x 151145x 151145x 151121x 151121x 150991x 150991x 150991x 150991x 150991x 150991x 150991x 150991x 150991x 150991x 150991x 150991x 151121x 28x 28x 150991x 150991x 151121x 151145x 151145x 151123x 151123x 151123x 6x 6x 151117x 151117x 151117x 151117x 151117x 151117x 151117x 151117x 151117x 151117x 151117x 151117x 151115x 151115x 151117x 151123x 151145x 151145x 100718x 100718x 100718x 100718x 100718x     100718x 100718x 100718x 151145x 151145x 100718x 100718x 100718x 100718x 100718x 100718x 100718x     100718x 100718x 100718x 100718x 100718x 100718x 151145x 151145x 116401x 116401x 116401x 116401x 116401x 15580x 15580x 15580x 100821x 116401x 100821x 100821x 116401x 50405x 50405x 50416x 50416x 116401x 116401x 151145x 151145x 100821x 100821x 100821x 100821x 100821x 100795x 100795x 26x 26x 26x 26x 26x 26x 26x 26x 100821x 151145x 151145x 151145x 151145x 151145x 100732x 100732x 100732x 100732x 100732x 100732x 50304x 50304x 50304x 100732x 100732x 100732x 100732x 100732x 100732x 100732x 2x 2x 2x 2x 100730x 100730x 100730x 100730x 100730x 100730x 100730x 100730x 100730x 100730x 100946x 100946x 100946x 100946x 100946x 100946x 100690x 100690x 100690x 100690x 100690x 50284x 50284x 100690x 50662x 50662x 100946x 50422x 50422x 50422x 50422x 50422x 50422x 50422x 50422x 2x 2x 2x 50420x 50420x 50420x 50420x 50420x 50420x 50420x 2x 2x 2x 50420x 50420x 50420x 50420x 50422x 6x 6x 6x 6x 6x 6x 50414x 50414x 50414x 50414x 50414x 50414x 50414x 50422x 50660x 50660x 100946x 100730x 100730x 100730x 100730x 100730x 100730x 100730x 151143x 151143x 151145x 50413x 50413x 50413x 50413x 50413x 2x 2x 2x 2x 2x 50411x 50411x 50411x 151141x 151145x 151145x 169x 169x 33x 33x     33x 33x 21x 21x 33x 33x 33x 33x 12x 12x 12x 33x 33x 33x 33x 169x 169x 169x 150972x 150972x 18x 18x 18x 394172x 394172x 394172x 73452x 73452x 73452x 73452x 320720x 320720x 18x 18x 18x 1999x 1999x 1999x 1976x 1976x 23x 23x 1999x     18x 18x 18x 1999x 1999x 1999x 1999x 1999x 1546x 1546x 1999x 1999x 1999x 1743x 1743x 1743x 1743x 1743x 256x 256x 18x 18x 18x 1999x 1999x 1999x 509488x 509488x 509488x 254496x 254496x 254496x 509488x 1999x 1999x 1999x 742x 742x 742x 742x 742x 742x 1257x 1257x 18x 18x 18x 18x 18x 18x 18x 18x 2305x 2305x 2305x 306x 306x 306x 306x 306x 306x 1999x 1999x 1999x 1999x 2305x 1947x 1947x 1947x 1947x 1947x 1947x 1947x 1947x 1947x 1947x     52x 18x 18x 18x 18x 18x 18x 392173x 392173x 392173x 392173x 392173x 71906x 71906x 320267x 320267x 320267x 320267x 18x 18x 18x 18x 18x 18x 626x 626x 626x 626x 626x 160256x 160256x 626x 626x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1999x 1999x 18x 18x 18x    
/**
# qlobber-fsq   [![Build Status](https://github.com/davedoesdev/qlobber-fsq/workflows/ci/badge.svg)](https://github.com/davedoesdev/qlobber-fsq/actions) [![Build status](https://ci.appveyor.com/api/projects/status/k7x8kh1m64vu52ej?svg=true)](https://ci.appveyor.com/project/davedoesdev/qlobber-fsq) [![Coverage Status](https://coveralls.io/repos/davedoesdev/qlobber-fsq/badge.png?branch=master)](https://coveralls.io/r/davedoesdev/qlobber-fsq?branch=master) [![NPM version](https://badge.fury.io/js/qlobber-fsq.png)](http://badge.fury.io/js/qlobber-fsq)
 
Shared file system queue for Node.js.
 
- **Note:** Version 12.1.0 supports direct producer-to-subscriber streams where the data doesn't go via the filesystem. See the `direct_handler` option to the [`QlobberFSQ constructor`](#qlobberfsqoptions) and the `direct` option to [`publish`](#qlobberfsqprototypepublishtopic-payload-options-cb).
- **Note:** Version 9 can use [shared memory LMAX Disruptors](https://github.com/davedoesdev/shared-memory-disruptor) to speed things up on a single multi-core server.
- Supports pub-sub and work queues.
- Supports local file system for multi-core use.
- Tested with [FraunhoferFS (BeeGFS)](http://www.fhgfs.com/) and [CephFS](http://ceph.com/ceph-storage/file-system/) for distributed use.
- **Note:** An alternative module, [`qlobber-pg`](https://github.com/davedoesdev/qlobber-pg), can be used when you need access from multiple hosts. It's API-compatible with `qlobber-fsq` and requires a PostgreSQL database.
- Highly configurable.
- Full set of unit tests, including stress tests.
- Use as a backend-less alternative to [RabbitMQ](http://www.rabbitmq.com/), [Redis pub-sub](http://redis.io/topics/pubsub) etc.
- Supports AMQP-like topics with single- and multi-level wildcards.
- Tested on Linux and Windows.
 
Example:
 
```javascript
var QlobberFSQ = require('qlobber-fsq').QlobberFSQ;
var fsq = new QlobberFSQ({ fsq_dir: '/shared/fsq' });
fsq.subscribe('foo.*', function (data, info)
{
    console.log(info.topic, data.toString('utf8'));
    var assert = require('assert');
    assert.equal(info.topic, 'foo.bar');
    assert.equal(data, 'hello');
});
fsq.on('start', function ()
{
    this.publish('foo.bar', 'hello');
});
```
 
You can publish messages using a separate process if you like:
 
```javascript
var QlobberFSQ = require('qlobber-fsq').QlobberFSQ;
var fsq = new QlobberFSQ({ fsq_dir: '/shared/fsq' });
fsq.stop_watching();
fsq.on('stop', function ()
{
    this.publish('foo.bar', 'hello');
});
```
 
Or use the streaming interface to read and write messages:
 
```javascript
const { QlobberFSQ } = require('qlobber-fsq');
const fsq = new QlobberFSQ({ fsq_dir: '/shared/fsq' });
function handler(stream, info)
{
    const data = [];
 
    stream.on('readable', function ()
    {
        let chunk;
        while (chunk = this.read())
        {
            data.push(chunk);
        }
    });
 
    stream.on('end', function ()
    {
        const str = Buffer.concat(data).toString('utf8');
        console.log(info.topic, str);
        const assert = require('assert');
        assert.equal(info.topic, 'foo.bar');
        assert.equal(str, 'hello');
    });
}
handler.accept_stream = true;
fsq.subscribe('foo.*', handler);
fsq.on('start', function ()
{
    fsq.publish('foo.bar').end('hello');
});
```
 
The API is described [here](#tableofcontents).
 
## Installation
 
```shell
npm install qlobber-fsq
```
 
## Limitations
 
- `qlobber-fsq` provides no guarantee that the order messages are given to subscribers is the same as the order in which the messages were written. If you want to maintain message order between readers and writers then you'll need to do it in your application (using ACKs, sliding windows etc). Alternatively, use the `order_by_expiry` [constructor](#qlobberfsqoptions) option to have messages delivered in order of the time they expire.
 
- `qlobber-fsq` does its best not to lose messages but in exceptional circumstances (e.g. process crash, file system corruption) messages may get dropped. You should design your application to be resilient against dropped messages.
 
- `qlobber-fsq` makes no assurances about the security or privacy of messages in transit or at rest. It's up to your application to encrypt messages if required.
 
- `qlobber-fsq` supports Node 6 onwards.
 
## Distributed filesystems
 
Note: When using a distributed file system with `qlobber-fsq`, ensure that you synchronize the time and date on all the computers you're using.
 
### FraunhoferFS (BeeGFS)
 
When using the FraunhoferFS distributed file system, set the following options in `fhgfs-client.conf`:
 
```
tuneFileCacheType             = none
tuneUseGlobalFileLocks        = true
```
 
`qlobber-fsq` has been tested with FraunhoferFS 2014.01 on Ubuntu 14.04 and FraunhoferFS 2012.10 on Ubuntu 13.10.
 
### CephFS
 
`qlobber-fsq` has been tested with CephFS 0.80 on Ubuntu 14.04. Note that you'll need to [upgrade your kernel](http://www.yourownlinux.com/2014/04/install-upgrade-to-linux-kernel-3-14-1-in-linux.html) to at least 3.14.1 in order to get the fix for [a bug](http://tracker.ceph.com/issues/7371) in CephFS.
 
## How it works
 
![How it works](http://rawgit.davedoesdev.com/davedoesdev/qlobber-fsq/master/diagrams/how_it_works.svg)
 
Under the directory you specify for `fsq_dir`, `qlobber-fsq` creates the following sub-directories:
 
- `staging` Whilst it's being published, each message is written to a file in the staging area. The filename itself contains the message's topic, when it expires, whether it should be read by one subscriber or many and a random sequence of characters to make it unique.
- `messages` Once published to the staging area, each message is moved into this directory. `qlobber-fsq` actually creates a number of sub-directories (called buckets) under `messages` and distributes message between buckets according to the hash of their filenames. This helps to reduce the number of directory entries that have to be read when a single message is written.
- `topics` If a message's topic is long, a separate topic file is created for it in this directory.
- `update` This contains one file, `UPDATE`, which is updated with a random sequence of bytes (called a stamp) every time a message is moved into the `messages` directory. `UPDATE` contains a separate stamp for each bucket.
 
`qlobber-fsq` reads `UPDATE` at regular intervals to determine whether a new message has been written to a bucket. If it has then it processes each filename in the bucket's directory listing.
 
If the expiry time in the filename has passed then it deletes the message.
 
If the filename indicates the message can be read by many subscribers:
 
- If it's processed this filename before then stop processing this filename.
- If the topic in the filename matches any subscribers then call each subscriber with the file's content. It uses [`qlobber`](https://github.com/davedoesdev/qlobber) to pattern match topics to subscribers.
- Remember that we've processed the filename.
 
If the filename indicates the message can be read by only one subscriber (i.e. work queue semantics):
 
- Try to lock the file using `flock`. If it fails to lock the file then stop processing this filename.
- If the topic in the filename matches any subscribers then call one subscriber with the file's content.
- Truncate and delete the file before unlocking it. We truncate the file in case of directory caching.
 
## Licence
 
[MIT](LICENCE)
 
## Test
 
To run the default tests:
 
```shell
grunt test [--fsq-dir=<path>] [--getdents_size=<buffer size>] [--disruptor]
```
 
If you don't specify `--fsq-dir` then the default will be used (a directory named `fsq` in the `test` directory).
 
If you specify `--getdents_size` then use of [`getdents`](https://github.com/davedoesdev/getdents) will be included in the tests.
 
If you specify `--disruptor` then use of [shared memory LMAX Disruptors](https://github.com/davedoesdev/shared-memory-disruptor) will be included in the tests.
 
To run the stress tests (multiple queues in a single Node process):
 
```shell
grunt test-stress [--fsq-dir=<path>] [--disruptor]
```
 
To run the multi-process tests (each process publishing and subscribing to different messages):
 
```shell
grunt test-multi [--fsq-dir=<path>] [--queues=<number of queues>] [--disruptor]
```
 
If you omit `--queues` then one process will be created per core (detected with [`os.cpus()`](http://nodejs.org/api/os.html#os_os_cpus)).
 
To run the distributed tests (one process per remote host, each one publishing and subscribing to different messages):
 
```shell
grunt test-multi --fsq-dir=<path> --remote=<host1> --remote=<host2>
```
 
You can specify as many remote hosts as you like. The test uses [`cp-remote`](https://github.com/davedoesdev/cp-remote) to run a module on each remote host. Make sure on each host:
 
- The `qlobber-fsq` module is installed at the same location.
- Mount the same distributed file system on the directory you specify for `--fsq-dir`. FraunhoferFS and CephFS are the only distributed file systems currently supported.
 
Please note the distributed tests don't run on Windows.
 
## Lint
 
```shell
grunt lint
```
 
## Code Coverage
 
```shell
grunt coverage [--fsq-dir=<path>]
```
 
[c8](https://github.com/bcoe/c8) results are available [here](http://rawgit.davedoesdev.com/davedoesdev/qlobber-fsq/master/coverage/lcov-report/index.html).
 
Coveralls page is [here](https://coveralls.io/r/davedoesdev/qlobber-fsq).
 
## Benchmarks
 
To run the benchmark:
 
```shell
grunt bench [--fsq-dir=<path>] \
            --rounds=<number of rounds> \
            --size=<message size> \
            --ttl=<message time-to-live in seconds> \
            [--disruptor] \
            [--num_elements=<number of disruptor elements>] \
            [--element_size=<disruptor element size>] \
            [--bucket_stamp_size=<number of bytes to write to UPDATE file] \
            [--getdents_size=<buffer size>] \
            [--ephemeral] \
            [--refresh_ttl=<period between expiration check in seconds>] \
            (--queues=<number of queues> | \
             --remote=<host1> --remote=<host2> ...)
```
 
If you don't specify `--fsq-dir` then the default will be used (a directory named `fsq` in the `bench` directory).
 
If you provide at least one `--remote=<host>` argument then the benchmark will be distributed across multiple hosts using [`cp-remote`](https://github.com/davedoesdev/cp-remote). Make sure on each host:
 
- The `qlobber-fsq` module is installed at the same location.
- Mount the same distributed file system on the directory you specify for `--fsq-dir`. FraunhoferFS and CephFS are the only distributed file systems currently supported.
 
# API
*/
"use strict";
 
var stream = require('stream'),
    path = require('path'),
    crypto = require('crypto'),
    util = require('util'),
    events = require('events'),
    constants = require('constants'),
    async = require('async'),
    wu = require('wu'),
    semver = require('semver'),
    qlobber = require('qlobber'),
    Qlobber = qlobber.Qlobber,
    QlobberDedup = qlobber.QlobberDedup;
 
function CollectStream()
{
    stream.Writable.call(this);
 
    this.setMaxListeners(0);
 
    this._chunks = [];
    this._len = 0;
 
    var ths = this;
 
    this.on('finish', function ()
    {
        ths.emit('buffer', Buffer.concat(ths._chunks, ths._len));
    });
}
 
util.inherits(CollectStream, stream.Writable);
 
CollectStream.prototype._write = function (chunk, encoding, callback)
{
    this._chunks.push(chunk);
    this._len += chunk.length;
    callback();
};
 
/*function sum(buf, start, end)
{
    var i, r = 0;
 
    for (i = start; i < end; i += 1)
    {
        r += buf[i];
    }
 
    return r;
}*/
 
/**
Creates a new `QlobberFSQ` object for publishing and subscribing to a file system queue.
 
@constructor
 
@param {Object} [options] Configures the file system queue. Valid properties are listed below:
- `{String} fsq_dir` The path to the file system queue directory. Note that the following sub-directories will be created under this directory if they don't exist: `messages`, `staging`, `topics` and `update`. Defaults to a directory named `fsq` in the `qlobber-fsq` module directory.
 
- `{Boolean} encode_topics` Whether to hex-encode message topics. Because topic strings form part of message filenames, they're first hex-encoded. If you can ensure that your message topics contain only valid filename characters, set this to `false` to skip encoding. Defaults to `true`.
 
- `{Integer} split_topic_at` Maximum number of characters in a short topic. Short topics are contained entirely in a message's filename. Long topics are split so the first `split_topic_at` characters go in the filename and the rest are written to a separate file in the `topics` sub-directory. Obviously long topics are less efficient. Defaults to 200, which is the maximum for most common file systems. Note: if your `fsq_dir` is on an [`ecryptfs`](http://ecryptfs.org/) file system then you should set `split_topic_at` to 100.
 
- `{Integer} bucket_base`, `{Integer} bucket_num_chars` Messages are distributed across different _buckets_ for efficiency. Each bucket is a sub-directory of the `messages` directory. The number of buckets is determined by the `bucket_base` and `bucket_num_chars` options. `bucket_base` is the radix to use for bucket names and `bucket_num_chars` is the number of digits in each name. For example, `bucket_base: 26` and `bucket_num_chars: 4` results in buckets `0000` through `pppp`. Defaults to `base_base: 16` and `bucket_num_chars: 2` (i.e. buckets `00` through `ff`). The number of buckets is available as the `num_buckets` property of the `QlobberFSQ` object.
 
- `{Integer} bucket_stamp_size` The number of bytes to write to the `UPDATE` file when a message is published. The `UPDATE` file (in the `update` directory) is used to determine whether any messages have been published without having to scan all the bucket directories. Each bucket has a section in the `UPDATE` file, `bucket_stamp_size` bytes long. When a message is written to a bucket, its section is filled with random bytes. Defaults to 32. If you set this to 0, the `UPDATE` file won't be written to and all the bucket directories will be scanned even if no messages have been published.
 
- `{Integer} flags` Extra flags to use when reading and writing files. You shouldn't need to use this option but if you do then it should be a bitwise-or of values in the (undocumented) Node `constants` module (e.g. `constants.O_DIRECT | constants.O_SYNC`). Defaults to 0.
 
- `{Integer} unique_bytes` Number of random bytes to append to each message's filename (encoded in hex), in order to avoid name clashes. Defaults to 16. If you increase it (or change the algorithm to add some extra information like the hostname), be sure to reduce `split_topic_at` accordingly.
 
- `{Integer} single_ttl` Default time-to-live (in milliseconds) for messages which should be read by at most one subscriber. This value is added to the current time and the resulting expiry time is put into the message's filename. After the expiry time, the message is ignored and deleted when convenient. Defaults to 1 hour.
 
- `{Integer} multi_ttl` Default time-to-live (in milliseconds) for messages which can be read by many subscribers. This value is added to the current time and the resulting expiry time is put into the message's filename. After the expiry time, the message is ignored and deleted when convenient. Defaults to 1 minute.
 
- `{Integer} poll_interval` `qlobber-fsq` reads the `UPDATE` file at regular intervals to check whether any messages have been written. `poll_interval` is the time (in milliseconds) between each check. Defaults to 1 second.
 
- `{Boolean} notify` Whether to use [`fs.watch`](http://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener) to watch for changes to the `UPDATE` file. Note that this will be done in addition to reading it every `poll_interval` milliseconds because `fs.watch` (`inotify` underneath) can be unreliable, especially under high load. Defaults to `true`.
 
- `{Integer} retry_interval` Some I/O operations can fail with an error indicating they should be retried. `retry_interval` is the time (in milliseconds) to wait before retrying. Defaults to 1 second.
 
- `{Integer} message_concurrency` The number of messages in each bucket to process at once. Defaults to 1.
 
- `{Integer} bucket_concurrency` The number of buckets to process at once. Defaults to 1.
 
- `{Integer} handler_concurrency` By default, a message is considered handled by a subscriber only when all its data has been read. If you set `handler_concurrency` to non-zero, a message is considered handled as soon as a subscriber receives it. The next message will then be processed straight away. The value of `handler_concurrency` limits the number of messages being handled by subscribers at any one time. Defaults to 0 (waits for all message data to be read).
 
- `{Boolean} order_by_expiry` Pass messages to subscribers in order of their expiry time. If `true` then `bucket_base` and `bucket_num_chars` are forced to 1 so messages are written to a single bucket. Defaults to `false`.
 
- `{Boolean} dedup` Whether to ensure each handler function is called at most once when a message is received. Defaults to `true`.
 
- `{Boolean} single` Whether to process messages meant for _at most_ one subscriber (across all `QlobberFSQ` objects), i.e. work queues. This relies on the optional dependency [`fs-ext`](https://github.com/baudehlo/node-fs-ext). Defaults to `true` if `fs-ext` is installed, otherwise `false` (in which case a [`single_disabled`](#qlobberfsqeventssingle_disablederr) event will be emitted).
 
- `{String} separator` The character to use for separating words in message topics. Defaults to `.`.
 
- `{String} wildcard_one` The character to use for matching exactly one word in a message topic to a subscriber. Defaults to `*`.
 
- `{String} wildcard_some` The character to use for matching zero or more words in a message topic to a subscriber. Defaults to `#`.
 
- `{Integer} getdents_size` If positive, use [`getdents`](https://github.com/davedoesdev/getdents) to enumerate messages in bucket directories. `getdents_size` is the buffer size to use with `getdents`. Otherwise, use [`fs.readdir`](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback) (which is the default). If `getdents` is requested but unavailable, a [`getdents_disabled`](#qlobberfsqeventsgetdents_disablederr) event will be emitted.
 
- `{Function (info, handlers, cb(err, ready, filtered_handlers)) | Array} filter` Function called before each message is processed.
 
  - You can use this to filter the subscribed handler functions to be called for the message (by passing the filtered list as the third argument to `cb`).
 
  - If you want to ignore the message _at this time_ then pass `false` as the second argument to `cb`. `filter` will be called again later with the same message.
 
  - Defaults to a function which calls `cb(null, true, handlers)`.
 
  - `handlers` is an ES6 Set, or array if `options.dedup` is falsey.
 
  - `filtered_handlers` should be an ES6 Set, or array if `options.dedup` is falsey. If not, `new Set(filtered_handlers)` or `Array.from(filtered_handlers)` will be used to convert it.
 
  - You can supply an array of filter functions - each will be called in turn with the `filtered_handlers` from the previous one.
 
  - An array containing the filter functions is also available as the `filters` property of the `QlobberFSQ` object and can be modified at any time.
 
- `{Function (bucket)} [get_disruptor]` You can speed up message processing on a single multi-core server by using [shared memory LMAX Disruptors](https://github.com/davedoesdev/shared-memory-disruptor). Message metadata and (if it fits) payload will be sent through the Disruptor. `get_disruptor` will be called for each bucket number and should return the Disruptor to use for that bucket or `null`. The same disruptor can be used for more than one bucket if you wish.
 
- `{Integer} refresh_ttl` If you use a shared memory LMAX Disruptor for a bucket (see `get_disruptor` above), notification of new messages in the bucket is received through the Disruptor. However, checking for expired messages still needs to read the filesystem. `refresh_ttl` is the time (in milliseconds) between checking for expired messages when a Disruptor is in use. Defaults to 10 seconds.
 
- `{Integer} disruptor_spin_interval` If a Disruptor is shared across multiple buckets or multiple `QlobberFSQ` instances, contention can occur when publishing a message. In this case [`publish`](#qlobberfsqprototypepublishtopic-payload-options-cb) will try again until it succeeds. `disruptor_spin_interval` is the time (in milliseconds) to wait before retrying. Defaults to 0.
 
- `{Object} [direct_handler]` Object with the following methods, used for transferring messages direct from publisher to subscribers without writing them to disk:
 
  - `{Function (filename, direct)} get_stream_for_publish` Called by [`publish`](#qlobberfsqprototypepublishtopic-payload-options-cb) when truthy `options.direct` is passed to it instead of writing data to disk. This method receives the name of the file to which data would have been written plus the value of `options.direct` that was passed to [`publish`](#qlobberfsqprototypepublishtopic-payload-options-cb). Whatever it returns will be returned by the call to [`publish`](#qlobberfsqprototypepublishtopic-payload-options-cb).
 
  - `{Function (filename)} get_stream_for_subscribers` Called when a stream published by calling [`publish`](#qlobberfsqprototypepublishtopic-payload-options-cb) with truthy `options.direct` needs to be given to subscribers. It receives the name of the file to which data would have been written. It must return a [Readable](http://nodejs.org/api/stream.html#stream_class_stream_readable) stream.
 
  - `{Function (filename, stream)} publish_stream_destroyed` Called when a stream returned by `get_stream_for_publish()` has been destroyed or the message has expired. It receives the name of the file passed to `get_stream_for_publish() and the destroyed stream.
 
  - `{Function (filename)} publish_stream_expired` Called when a stream returned by `get_stream_for_publish()` has expired and should be destroyed. It receives the name of the file passed to `get_stream_for_publish()`.
 
  - `{Function (filename, stream)} subscriber_stream_destroyed` Called when a stream returned by `get_stream_for_subscribers()` has been destroyed or the message has expired. It receives the name of the file passed to `get_stream_for_subscribers()` and the destroyed stream.
 
  - `{Function (filename)} subscriber_stream_ignored` Called when a stream published by calling [`publish`](#qlobberfsqprototypepublishtopic-payload-options-cb) with truthy `options.direct` doesn't have any subscribers. It receives the name of the file to which data would have been written.
*/
function QlobberFSQ(options)
{
    events.EventEmitter.call(this);
 
    options = options || {};
 
    this._fsq_dir = options.fsq_dir || path.join(__dirname, '..', 'fsq');
    this._msg_dir = this._fsq_dir + path.sep + 'messages';
    this._topic_dir = this._fsq_dir + path.sep + 'topics';
    this._staging_dir = this._fsq_dir + path.sep + 'staging';
    this._update_dir = this._fsq_dir + path.sep + 'update';
    this._update_fname = this._update_dir + path.sep + 'UPDATE';
 
    this._encode_topics = options.encode_topics === undefined ? true : options.encode_topics;
    this._split_topic_at = options.split_topic_at || 200;
 
    this._bucket_base = options.bucket_base || 16;
    this._bucket_num_chars = options.bucket_num_chars || 2;
    this._bucket_stamp_size = options.bucket_stamp_size === undefined ? 32 : options.bucket_stamp_size;
 
    this._flags = options.flags || 0;
 
    this._unique_bytes = options.unique_bytes || 16;
 
    this._single_ttl = options.single_ttl || (60 * 60 * 1000); // 1 hour
    this._multi_ttl = options.multi_ttl || (60 * 1000); // 1 minute
 
    this._poll_interval = options.poll_interval || 1000; // 1 second
    this._retry_interval = options.retry_interval || 1000; // 1 second
 
    this._disruptor_spin_interval = options.disruptor_spin_interval === undefined ? 0 : options.disruptor_spin_interval;
 
    this._message_concurrency = options.message_concurrency || 1;
    this._bucket_concurrency = options.bucket_concurrency || 1;
 
    this._order_by_expiry = options.order_by_expiry;
    if (this._order_by_expiry)
    {
        this._bucket_base = 1;
        this._bucket_num_chars = 1;
    }
 
    this._do_dedup = options.dedup === undefined ? true : options.dedup;
    this._do_single = options.single === undefined ? true : options.single;
 
    this._direct_handler = options.direct_handler;
 
    if (this._do_dedup)
    {
        this._matcher = new QlobberDedup(options);
    }
    else
    {
        this._matcher = new Qlobber(options);
    }
 
    this._matcher_marker = {};
 
    this._extra_matcher = null;
 
    this._leading_byte = Buffer.from([0]);
 
    this._disruptors = [];
 
    this.num_buckets = QlobberFSQ.get_num_buckets(this._bucket_base,
                                                  this._bucket_num_chars);
 
    this._last_refreshed = new Map();
 
    var ths = this,
        delivered = new Map(),
        pending = new Map(),
        bucket_formats = [],
        handler_queue,
        refresh_ttl = options.refresh_ttl === undefined ?
                            10 * 1000 : options.refresh_ttl,
        dirs = [this._fsq_dir,
                this._staging_dir,
                this._update_dir,
                this._msg_dir,
                this._topic_dir];
 
    this._ensure_extra_matcher = function ()
    {
        if (!ths._extra_matcher)
        {
            if (ths._do_dedup)
            {
                ths._extra_matcher = new QlobberDedup(options);
            }
            else
            {
                ths._extra_matcher = new Qlobber(options);
            }
 
            ths._extra_matcher._extra_handlers = new Map();
            ths._extra_matcher._matcher_markers = new Map();
            ths._extra_matcher._not_seen = new Map();
        }
 
        return ths._extra_matcher;
    };
 
    this.filters = options.filter || [];
 
    if (typeof this.filters[Symbol.iterator] !== 'function')
    {
        this.filters = [this.filters];
    }
 
    function filter(info, handlers, cb)
    {
        function next(i)
        {
            return function (err, ready, handlers)
            {
                if (handlers)
                {
                    if (ths._do_dedup)
                    {
                        if (!(handlers instanceof Set))
                        {
                            handlers = new Set(handlers);
                        }
                    }
                    else if (!Array.isArray(handlers))
                    {
                        handlers = Array.from(handlers);
                    }
                }
 
                if (err || !ready || (i === ths.filters.length))
                {
                    return cb(err, ready, handlers);
                }
 
                ths.filters[i].call(ths, info, handlers, next(i + 1));
            };
        }
 
        next(0)(null, true, handlers);
    }
 
    function copy(handlers)
    {
        return ths._do_dedup ? new Set(handlers) : Array.from(handlers);
    }
 
    this._error = function (err)
    {
        if (err)
        {
            var i, silent = false;
 
            for (i = 1; i < arguments.length; i += 1)
            {
                if (arguments[i] && (err.code === arguments[i]))
                {
                    silent = true;
                    break;
                }
            }
 
            if ((!silent) && !ths.emit('warning', err))
            {
                console.error(err);
            }
        }
 
        return err;
    };
 
    this.stopped = false;
    this.active = true;
    this.initialized = false;
 
    this._chkstop = function ()
    {
        if (ths.stopped && ths.active)
        {
            ths.active = false;
            ths.emit('stop');
        }
 
        return ths.stopped;
    };
 
    this._try_again = function (err)
    {
        // graceful-fs takes care of EAGAIN
        return err && (err.code === 'EBUSY');
    };
 
    function emit_error(err)
    {
        ths.active = false;
        ths.emit('error', err);
    }
 
    function decode_topic(info)
    {
        if (ths._encode_topics)
        {
            info.topic = Buffer.from(info.topic, 'hex').toString();
        }
    }
 
    function parse_fname(bucket_fmt, fname, cb)
    {
        var at_pos = fname.lastIndexOf('@'), metadata, info;
 
        if (at_pos < 0) { return cb(); }
 
        metadata = fname.substr(at_pos + 1).split('+');
        if (metadata.length !== 4) { return cb(); }
 
        info = {
            fname: fname,
            path: ths._msg_dir + path.sep + bucket_fmt + path.sep + fname,
            topic: fname.substr(0, at_pos),
            expires: parseInt(metadata[1], 16),
            single: metadata[2] === 's',
            direct: metadata[2] === 'd'
        };
 
        if (metadata[0] === 's')
        {
            decode_topic(info);
            return cb(info);
        }
 
        info.topic_path = ths._topic_dir + path.sep + bucket_fmt + path.sep + fname;
 
        ths._fs.readFile(info.topic_path,
                         { flag: constants.O_RDONLY | ths._flags },
        function (err, split)
        {
            if (ths._error(err, 'ENOENT')) { return cb(); }
            info.topic += split.toString('utf8');
            decode_topic(info);
            cb(info);
        });
    }
 
    function close(fd, err, cb)
    {
        ths._fs.close(fd, function (err2)
        {
            ths._error(err2);
 
            if (ths._try_again(err2))
            {
                return setTimeout(close, ths._retry_interval, fd, err, cb);
            }
 
            if (cb) { cb(err || err2); }
        });
    }
 
    function unlock_and_close(fd, err, cb)
    {
        // close should be enough but just in case
        ths._fsext.flock(fd, 'un', function (err2)
        {
            if (ths._error(err2, 'EAGAIN') &&
                (ths._try_again(err2) || (err2.code === 'EAGAIN')))
            {
                return setTimeout(unlock_and_close,
                                  ths._retry_interval,
                                  fd,
                                  err,
                                  cb);
            }
 
            close(fd, err || err2, cb);
        });
    }
 
    function unlink(info, err, cb)
    {
        ths._fs.unlink(info.path, function (err2)
        {
            // Ignore EBUSY, rely on truncate having happened.
            // When we see it again and it's expired or we can't read a byte,
            // we'll unlink again.
 
            ths._error(err2,
                       'ENOENT',
                       (process.platform === 'win32') ? 'EPERM' : null);
 
            if (err2 &&
                ((err2.code === 'ENOENT') ||
                 ((process.platform === 'win32') &&
                  (err2.code === 'EPERM'))))
            {
                err2 = null;
            }
 
            if (!info.topic_path)
            {
                return cb(err || err2);
            }
 
            ths._fs.unlink(info.topic_path, function (err3)
            {
                ths._error(err3,
                           'ENOENT',
                           (process.platform === 'win32') ? 'EPERM' : null);
 
                if (err3 &&
                    ((err3.code === 'ENOENT') ||
                     ((process.platform === 'win32') &&
                      (err3.code === 'EPERM'))))
                {
                    err3 = null;
                }
 
                cb(err || err2 || err3);
            });
        });
    }
 
    function unlink_unlock_and_close(info, fd, err, cb)
    {
        if (process.platform === 'win32')
        {
            // Windows can't unlink while the file is open.
            // Another reader opening the file between us closing and
            // unlinking it will find it empty.

            return unlock_and_close(fd, err, function (err2)
            {
                unlink(info, err2, cb);
            });
        }
 
        unlink(info, err, function (err2)
        {
            unlock_and_close(fd, err || err2, cb);
        });
    }
 
    function collected(handler, info, cb)
    {
        return function (buf)
        {
            if (ths._chkstop()) { return; }
            handler.call(ths, buf, info, cb);
        };
    }
 
    function call_handlers2(handlers, info, cb)
    {
        //console.log('call_handlers', require('os').hostname(), info.topic, handlers.length);
 
        var called = false,
            done_err = null,
            waiting = [],
            len = ths._do_dedup ? handlers.size : handlers.length;
 
        if (ths._chkstop()) { return done(); }
 
        if (len === 0)
        {
            if (info.direct && ths._direct_handler)
            {
                ths._direct_handler.subscriber_stream_ignored(info.fname);
            }
 
            return done();
        }
 
        function done_ne(err)
        {
            var was_waiting = waiting;
            waiting = [];
 
            if (was_waiting.length > 0)
            {
                process.nextTick(function ()
                {
                    for (var f of was_waiting)
                    {
                        f(err);
                    }
                });
            }
 
            var was_called = called;
            called = true;
            done_err = err;
 
            if (ths._chkstop() || was_called) { return; }
 
            cb();
        }
 
        function done(err)
        {
            ths._error(err);
            done_ne(err);
        }
 
        function wait_for_done(err, cb)
        {
            ths._error(err);
 
            if (cb)
            {
                if (called)
                {
                    cb(done_err);
                }
                else
                {
                    waiting.push(cb);
                }
            }
        }
 
        function deliver_message(make_stream, data, fd)
        {
            var stream,
                cstream,
                hcb,
                delivered_stream = false;
 
            function deliver_stream()
            {
                var stream_ended = false,
                    destroyed = false;
 
                function destroy(err)
                {
                    if (fd < 0)
                    {
                        return stream.destroy(err);
                    }
 
                    // We can't call stream.destroy() because it closes the
                    // file descriptor and we want to close it ourselves
                    // (we might want to truncate and unlock it first).
 
                    destroyed = stream.destroyed = true;
 
                    if (err)
                    {
                        stream.emit('error', err);
                    }
                }
 
                function common_callback(err, cb)
                {
                    if (destroyed)
                    {
                        wait_for_done(err, cb);
                        return null;
                    }
 
                    destroy(err);
                    
                    function cb2(err)
                    {
                        if (cb)
                        {
                            process.nextTick(cb, err);
                        }
                        stream.push(null);
                        // From Node 10, 'readable' not emitted after destroyed.
                        stream.emit('readable');
                        // From Node 16, 'end' isn't emitted either.
                        // However, we have code which relies on the stream ending
                        // so fix this up by emitting 'end' here.
                        setImmediate(() =>
                        {
                            if (!stream_ended)
                            {
                                stream.emit('end');
                            }
                        });
                        done(err);
                    }
 
                    if (fd < 0)
                    {
                        cb2();
                        return null;
                    }
 
                    return cb2;
                }
 
                function multi_callback(err, cb)
                {
                    var cb2 = common_callback(err, cb);
                    if (!cb2) { return; }
 
                    close(fd, null, cb2);
                }
 
                function single_callback(err, cb)
                {
                    var cb2 = common_callback(err, cb);
                    if (!cb2) { return; }
 
                    function truncate()
                    {
                        ths._fs.ftruncate(fd, 0, function (err)
                        {
                            ths._error(err);
 
                            if (ths._try_again(err))
                            {
                                return setTimeout(truncate, ths._retry_interval);
                            }
 
                            //console.log('truncated', info.fname);
 
                            unlink_unlock_and_close(info, fd, err, cb2);
                        });
                    }
 
                    if (err)
                    {
                        return unlock_and_close(fd, null, cb2);
                    }
 
                    truncate();
                }
 
                stream.setMaxListeners(0);
 
                stream.once('end', function ()
                {
                    stream_ended = true;
 
                    if (info.single)
                    {
                        return done();
                    }
 
                    if (destroyed) { return; }
                    if (fd >= 0)
                    {
                        destroyed = stream.destroyed = true;
                    }
 
                    if (info.direct)
                    {
                        ths._direct_handler.subscriber_stream_destroyed(info.fname, this);
                    }
 
                    if (fd < 0)
                    {
                        return done();
                    }
 
                    close(fd, null, done);
                });
 
                stream.on('error', function (err)
                {
                    ths._error(err);
 
                    if (destroyed) { return; }
                    if (fd >= 0)
                    {
                        destroyed = stream.destroyed = true;
                    }
 
                    function cb(err)
                    {
                        stream.push(null);
                        done(err);
                    }
 
                    if (fd < 0)
                    {
                        return cb();
                    }
 
                    if (info.single)
                    {
                        return unlock_and_close(fd, null, cb);
                    }
 
                    close(fd, null, cb);
                });
 
                var hcb = info.single ? single_callback : multi_callback;
                hcb.num_handlers = len;
                return hcb;
            }
 
            function ensure_stream()
            {
                if (!stream)
                {
                    stream = make_stream();
                    if (stream)
                    {
                        stream.emit('predeliver');
                        hcb = deliver_stream();
                    }
                }
 
                return stream;
            }
 
            function unpipe()
            {
                stream.unpipe(cstream);
            }
 
            for (var handler of handlers)
            {
                if (handler.accept_stream)
                {
                    if (!ensure_stream())
                    {
                        break;
                    }
                    handler.call(ths, stream, info, hcb);
                    delivered_stream = true;
                }
                else if (data)
                {
                    wait_for_done.num_handlers = len;
                    handler.call(ths, data, info, wait_for_done);
                }
                else
                {
                    if (!cstream)
                    {
                        if (!ensure_stream())
                        {
                            break;
                        }
                        cstream = new CollectStream();
                        stream.pipe(cstream);
                        stream.on('error', unpipe);
                    }
 
                    cstream.on('buffer', collected(handler, info, hcb));
 
                    delivered_stream = true;
                }
            }
 
            if (!delivered_stream)
            {
                // an unsubscribe might have modified handlers
                // or we don't have a stream to wait for
                if (fd < 0)
                {
                    return done();
                }
                close(fd, null, done);
            }
        }
 
        if (info.direct)
        {
            return process.nextTick(function ()
            {
                if (ths._chkstop()) { return done(); }
 
                deliver_message(function ()
                {
                    if (!ths._direct_handler)
                    {
                        return null;
                    }
 
                    return ths._direct_handler.get_stream_for_subscribers(info.fname);
                }, null, -1);
            });
        }
 
        if (info.data)
        {
            return process.nextTick(function ()
            {
                if (ths._chkstop()) { return done(); }
 
                deliver_message(function ()
                {
                    var s = new stream.PassThrough();            
                    s.end(info.data);
                    return s;
                }, info.data, -1);
            });
        }
 
        ths._fs.open(info.path,
                     (info.single ? constants.O_RDWR : constants.O_RDONLY) | ths._flags,
        function (err, fd)
        {
            function read2()
            {
                deliver_message(function ()
                {
                    return ths._fs.createReadStream(null,
                    {
                        fd: fd,
                        autoClose: false,
                        start: 1
                    });
                }, null, fd);
            }
 
            function read()
            {
                if (info.size !== undefined)
                {
                    return read2();
                }
 
                ths._fs.fstat(fd, function (err, stats)
                {
                    if (ths._error(err) || ths._chkstop())
                    {
                        return close(fd, null, done);
                    }
 
                    info.size = Math.max(stats.size - 1, 0);
                    read2();
                });
            }
 
            if ((info.single &&
                 err && (err.code === 'EPERM') &&
                 (process.platform === 'win32')) ||
                ths._error(err, 'ENOENT'))
            {
                return done_ne(err);
            }
 
            if (ths._chkstop()) { return close(fd, null, done); }
 
            if (info.single)
            {
                ths._fsext.flock(fd, 'exnb', function (err)
                {
                    if (ths._error(err, 'EAGAIN', 'EWOULDBLOCK') ||
                        ths._chkstop())
                    {
                        return close(fd, null, done);
                    }
 
                    //console.log('locked', info.fname);
 
                    var stream = ths._fs.createReadStream(null,
                        {
                            fd: fd,
                            autoClose: false,
                            start: 0,
                            end: 0
                        }),
                        got_data = 0;
 
                    stream.on('readable', function ()
                    {
                        var data = this.read();
                        if (data)
                        {
                            got_data += data.length;
                        }
                    });
 
                    stream.once('end', function ()
                    {
                        if (ths._chkstop())
                        {
                            unlock_and_close(fd, null, done);
                        }
                        else if (got_data > 0)
                        {
                            read();
                        }
                        else
                        {
                            unlink_unlock_and_close(info, fd, null, done);
                        }
                    });
 
                    stream.once('error', function (err)
                    {
                        ths._error(err);
                        unlock_and_close(fd, null, done);
                    });
                });
            }
            else
            {
                read();
            }
        });
    }
 
    if (options.handler_concurrency)
    {
        handler_queue = async.queue(function (task, cb)
        {
            setImmediate(task.cb);
            call_handlers2(task.handlers, task.info, cb);
        }, options.handler_concurrency);
    }
 
    function call_handlers(handlers, info, cb)
    {
        if (handler_queue)
        {
            handler_queue.push(
            {
                handlers: handlers,
                info: info,
                cb: cb
            });
        }
        else
        {
            call_handlers2(handlers, info, cb);
        }
    }
 
    function handle_info(delivered,
                         delivered2,
                         pending2,
                         extra_matcher,
                         only_check_expired,
                         info,
                         next)
    {
        if (ths._chkstop() || !info) { return setImmediate(next); }
 
        var now = Date.now(),
            reset_delay = false,
            extra_handlers,
            has_extra_handlers = false,
            prev_extra_handlers,
            not_seen,
            handlers,
            matcher_marker,
            h,
            info2;
 
        function cb(not_found, is_pending)
        {
            if (reset_delay)
            {
                ths._delay = 0;
            }
 
            if (delivered2)
            {
                if (not_found || is_pending)
                {
                    delivered2.delete(info.fname);
                }
                else
                {
                    delivered2.add(info.fname);
                }
            }
 
            if ((info.single || is_pending) && !not_found)
            {
                pending2.push(info.data ? info : info.fname);
            }
 
            setImmediate(next);
        }
 
        if (info.expires <= now)
        {
            if (info.direct && ths._direct_handler)
            {
                ths._direct_handler.publish_stream_expired(info.fname);
            }
 
            return unlink(info, null, function ()
            {
                cb(true);
            });
        }
 
        if (only_check_expired)
        {
            return cb();
        }
 
        if (delivered)
        {
            // New message if not in cache. If we're intializing, we just want
            // to store the message in the cache so we know what's existing.
            not_seen = ths.initialized && !delivered.has(info.fname);
        }
        else
        {
            // No cache. We're either called with file on disk to get existing
            // (extra_matcher true) or new (extra_matcher false).
            // Multi messages are always new, single messages are only new
            // the first time we process them.
            not_seen = ths.initialized &&
                       (info.new || !info.single) &&
                       !extra_matcher;
        }
 
        if (not_seen)
        {
            //console.log('not_seen', require('os').hostname(), info.fname, handlers.length);
            reset_delay = true;
        }
        /*else
        {
            console.log('seen', require('os').hostname(), info.fname, handlers.length);
        }*/
 
        if (info.single)
        {
            if (!ths._do_single)
            {
                return cb();
            }
 
            handlers = copy(ths._matcher.match(info.topic));
 
            info2 = not_seen ? info : Object.assign(
            {
                existing: true
            }, info);
 
            return filter(info2, handlers, function (err, ready, handlers)
            {
                ths._error(err);
 
                if (!ready)
                {
                    reset_delay = false;
                }
                else if (ths._do_dedup)
                {
                    if (handlers.size > 0)
                    {
                        return call_handlers(new Set([handlers.values().next().value]),
                                             info2,
                                             cb);
                    }
                }
                else if (handlers.length > 0)
                {
                    return call_handlers([handlers[0]], info2, cb);
                }
 
                cb();
            });
        }
 
        if (not_seen)
        {
            handlers = copy(ths._matcher.match(info.topic));
            info2 = info;
            if (ths._extra_matcher)
            {
                ths._extra_matcher._not_seen.set(info.path, copy(handlers));
            }
        }
        else if (extra_matcher && !info.direct)
        {
            // Need to get existing messages
            extra_handlers = extra_matcher.match(info.topic);
            has_extra_handlers = (ths._do_dedup ?
                    extra_handlers.size : extra_handlers.length) > 0;
            prev_extra_handlers =
                    extra_matcher._extra_handlers.get(info.path);
            if (prev_extra_handlers)
            {
                // We had handlers to receive this as an existing message
                if ((extra_matcher._matcher_markers.get(info.path) ===
                     ths._matcher_marker) &&
                    !has_extra_handlers)
                {
                    // No unsubscribe happened and no new handlers
                    extra_handlers = prev_extra_handlers;
                }
                else
                {
                    // Add previous handlers to new ones
                    extra_handlers = copy(extra_handlers);
                    handlers = ths._matcher.match(info.topic);
                    for (h of prev_extra_handlers)
                    {
                        if (ths._do_dedup)
                        {
                            if (handlers.has(h))
                            {
                                extra_handlers.add(h);
                            }
                        }
                        else if (handlers.indexOf(h) >= 0)
                        {
                            extra_handlers.push(h);
                        }
                    }
                }
                extra_matcher._extra_handlers.delete(info.path);
                extra_matcher._matcher_markers.delete(info.path);
            }
 
            // Make a copy of handlers, filtering out any we've already
            // delivered as new while extra_matcher was waiting to be processed
            handlers = ths._do_dedup ? new Set() : [];
            has_extra_handlers = false;
 
            for (h of extra_handlers)
            {
                const not_seen = extra_matcher._not_seen.get(info.path);
                if (not_seen && not_seen.has(h))
                {
                    continue;
                }
 
                if (ths._do_dedup)
                {
                    handlers.add(h);
                }
                else
                {
                    handlers.push(h);
                }
 
                has_extra_handlers = true;
            }
 
            if (!has_extra_handlers)
            {
                return cb();
            }
 
            // Handlers may be modified by filter functions (below) but we
            // may also need to store them in _extra_handlers (also below)
            // so make another copy
            extra_handlers = copy(handlers);
 
            // If message is delayed by filter, remember marker so we know
            // if any unsubscribe happened
            matcher_marker = ths._matcher_marker;
 
            info2 = Object.assign(
            {
                existing: true
            }, info);
        }
        else
        {
            return cb();
        }
 
        filter(info2, handlers, function (err, ready, handlers)
        {
            ths._error(err);
 
            if (ready)
            {
                return call_handlers(handlers, info2, cb);
            }
 
            reset_delay = false;
 
            if (has_extra_handlers)
            {
                // Remember handlers for existing messages
                var em = ths._ensure_extra_matcher();
                em._extra_handlers.set(info.path, extra_handlers);
                em._matcher_markers.set(info.path, matcher_marker);
            }
 
            cb(false, not_seen);
        });
    }
 
    function handle_fname(delivered,
                          delivered2,
                          pending2,
                          bucket_fmt,
                          extra_matcher,
                          only_check_expired,
                          fname,
                          next)
    {
        if (ths._chkstop()) { return setImmediate(next); }
 
        parse_fname(bucket_fmt, fname, function (info)
        {
            handle_info(delivered,
                        delivered2,
                        pending2,
                        extra_matcher,
                        only_check_expired,
                        info,
                        next);
        });
    }
 
    function make_info_handler(delivered,
                               delivered2,
                               pending2,
                               bucket_fmt,
                               extra_matcher,
                               only_check_expired)
    {
        return function (info, next)
        {
            handle_info(delivered,
                        delivered2,
                        pending2,
                        extra_matcher,
                        only_check_expired,
                        info,
                        next);
        };
    }
 
    function make_fname_handler(delivered,
                                delivered2,
                                pending2,
                                bucket_fmt,
                                extra_matcher,
                                only_check_expired)
    {
        return function (fname, next)
        {
            handle_fname(delivered,
                         delivered2,
                         pending2,
                         bucket_fmt,
                         extra_matcher,
                         only_check_expired,
                         fname,
                         next);
        };
    }
 
    function make_mixed_handler(delivered,
                                delivered2,
                                pending2,
                                bucket_fmt,
                                extra_matcher,
                                only_check_expired)
    {
        return function (info, next)
        {
            if (info.fname)
            {
                return handle_info(delivered,
                                   delivered2,
                                   pending2,
                                   extra_matcher,
                                   only_check_expired,
                                   info,
                                   next);
            }
 
            return handle_fname(delivered,
                                delivered2,
                                pending2,
                                bucket_fmt,
                                extra_matcher,
                                only_check_expired,
                                info,
                                next);
        };
    }
 
    function handle(infos,
                    delivered,
                    delivered2,
                    pending2,
                    bucket_fmt,
                    extra_matcher,
                    only_check_expired,
                    make_handler,
                    cb)
    {
        function cb2()
        {
            if (ths._chkstop()) { return; }
            process.nextTick(cb);
        }
 
        function cb3()
        {
            async.eachLimit(infos,
                            ths._message_concurrency,
                            make_handler(delivered,
                                         delivered2,
                                         pending2,
                                         bucket_fmt,
                                         extra_matcher,
                                         only_check_expired),
                            cb2);
        }
 
        if (ths._order_by_expiry)
        {
            return async.mapLimit(
                infos,
                ths._message_concurrency,
                function (info, cb)
                {
                    if (info.data)
                    {
                        return process.nextTick(cb, null, info);
                    }
 
                    parse_fname(bucket_fmt, info, function (pinfo)
                    {
                        process.nextTick(cb, null, pinfo);
                    });
                },
                function (err, pinfos)
                {
                    async.sortBy(pinfos, function (info, next)
                    {
                        process.nextTick(next, null, info ? info.expires : 0);
                    }, function (err, sinfos)
                    {
                        infos = sinfos;
                        make_handler = make_info_handler;
                        cb3();
                    });
                });
        }
 
        cb3();
    }
 
    function process_pending(bucket, bucket_fmt, extra_matcher, cache, cb)
    {
        // Note we never call with extra_matcher true and cache false
        var d = cache ? delivered.get(bucket) : null,
            infos = extra_matcher ?
                        // 1. Ensure pending picked up as existing
                        // 2. Ensure pending are processed (otherwise
                        //    any pending not delivered will be lost)
                        // This supports adding to pending outside polling but
                        // we don't do that currently
                        wu.chain(d, pending.get(bucket)) :
                        pending.get(bucket),
            pending2 = [];
 
        pending.set(bucket, pending2);
 
        handle(infos,
               d,
               d,
               pending2,
               bucket_fmt,
               extra_matcher,
               false,
               make_mixed_handler,
               cb);
    }
 
    function process_all_readdir(bucket,
                                 bucket_fmt,
                                 extra_matcher,
                                 cache,
                                 only_check_expired,
                                 cb)
    {
        ths._fs.readdir(ths._msg_dir + path.sep + bucket_fmt,
        function (err, files)
        {
            ths._error(err);
            if (ths._chkstop()) { return; }
            if (err) { return cb(err); }
 
            var d = cache ? delivered.get(bucket) : null,
                d2 = cache ? new Set() : null,
                pending2 = [];
 
            if (cache)
            {
                delivered.set(bucket, d2);
            }
 
            pending.set(bucket, pending2);
 
            handle(files,
                   d,
                   d2,
                   pending2,
                   bucket_fmt,
                   extra_matcher,
                   only_check_expired,
                   make_fname_handler,
                   cb);
        });
    }
 
    function polled()
    {
        if (ths._chkstop()) { return; }
 
        if (!ths.initialized)
        {
            ths.initialized = true;
            ths.emit('start');
        }
 
        if (!ths._chkstop())
        {
            ths._timeout = setTimeout(ths._poll, ths._delay);
        }
    }
 
    function read_update(cb)
    {
        if (ths._update_size === 0)
        {
            return cb();
        }
 
        ths._fs.readFile(ths._update_fname,
                         { flag: constants.O_RDONLY | ths._flags },
        function (err, update)
        {
            ths._error(err);
            if (ths._chkstop()) { return; }
 
            if (err || (update.length < ths._update_size))
            {
                ths._timeout = setTimeout(ths._poll, ths._retry_interval);
                return;
            }
 
            cb(update);
        });
    }
 
    function check_update(update, bucket, extra_matcher, cb)
    {
        if (ths._chkstop()) { return; }
 
        var bucket_fmt = ths._format_bucket(bucket),
            start = bucket * ths._bucket_stamp_size,
            end = (bucket + 1) * ths._bucket_stamp_size,
            disruptor = ths._disruptors[bucket];       
 
        function save_update(err)
        {
            if (update && !err)
            {
                update.copy(ths._last_update, start, start, end);
            }
 
            cb();
        }
 
        function refresh(expired)
        {
            //console.log('update', require('os').hostname(), bucket);
            ths._process_all(
                    bucket,
                    bucket_fmt,
                    extra_matcher,
                    !disruptor,
                    disruptor && !extra_matcher,
                    function (err)
                    {
                        if (refresh_ttl > 0)
                        {
                            var now = Date.now();
                            // Use negative to stop a constantly timed out
                            // bucket never processing pending messages
                            ths._last_refreshed.set(bucket, expired ? -now : now);
                        }
 
                        if (disruptor)
                        {
                            return cb();
                        }
 
                        save_update(err);
                    });
        }
 
        if (refresh_ttl > 0)
        {
            var last_refresh = ths._last_refreshed.get(bucket);
 
            if (last_refresh < 0)
            {
                // We timed out last time, refresh next time
                ths._last_refreshed.set(bucket, -last_refresh);
            }
            else if ((Date.now() - last_refresh) > refresh_ttl)
            {
                return refresh(true);
            }
        }
 
        //console.log('upsum', require('os').hostname(), sum(update, start, end), bucket);
 
        if (update &&
            update.slice(start, end).equals(ths._last_update.slice(start, end)) &&
            !(extra_matcher && disruptor))
        {
            //console.log('no update', require('os').hostname(), bucket);
            return process_pending(bucket,
                                   bucket_fmt,
                                   extra_matcher,
                                   !disruptor,
                                   cb);
        }
 
        if (disruptor && !extra_matcher)
        {
            var element_size = disruptor.elementSize;
            if (element_size >= 6)
            {
                var bucket_pending = pending.get(bucket),
                    bufs = disruptor.consumeNewSync();
 
                return async.eachSeries(bufs, function (buf, next)
                {
                    var n = buf.length / element_size;
 
                    async.timesSeries(n, function (i, next)
                    {
                        var start = i * element_size,
                            end = start + element_size,
                            len = buf.readUInt16LE(end - 2);
 
                        if (len === 0)
                        {
                            return process.nextTick(next);
                        }
 
                        var fname_end = start + len,
                            fname = buf.toString('utf8', start, fname_end);
 
                        parse_fname(bucket_fmt, fname, function (info)
                        {
                            if (info)
                            {
                                info.size = buf.readUInt32LE(end - 6);
 
                                if ((info.size <= element_size - 6 - len) &&
                                    !info.single)
                                {
                                    info.data = Buffer.alloc(info.size);
                                    buf.copy(info.data,
                                             0,
                                             fname_end,
                                             fname_end + info.size);
                                }
 
                                info.new = true;
 
                                bucket_pending.push(info);
                            }
 
                            process.nextTick(next);
                        });
                    }, next);
                }, function ()
                {
                    if (ths._chkstop()) { return; }
                    disruptor.consumeCommit();
                    process_pending(bucket,
                                    bucket_fmt,
                                    extra_matcher,
                                    false,
                                    save_update);
                });
            }
        }
 
        refresh(false);
    }
 
    function process_messages(update)
    {
        var extra_matcher = ths._extra_matcher;
        ths._extra_matcher = null;
 
        async.timesLimit(ths.num_buckets, ths._bucket_concurrency,
        function (bucket, next)
        {
            check_update(update, bucket, extra_matcher, next);
        }, polled);
    }
 
    this._poll = function ()
    {
        ths._timeout = null;
        if (ths._chkstop()) { return; }
 
        ths._delay = ths._poll_interval;
 
        read_update(process_messages);
    };
 
    function format_bucket(b)
    {
        var bs = ths._bucket_base > 1 ? b.toString(ths._bucket_base) : '0',
            arr = [];
        arr.length = ths._bucket_num_chars + 1;
        return (arr.join('0') + bs).slice(-ths._bucket_num_chars);
    }
 
    this._format_bucket = function (b)
    {
        return bucket_formats[b];
    };
 
    this._update_size = this.num_buckets * this._bucket_stamp_size;
    this._last_update = crypto.randomBytes(this._update_size);
 
    this._require_fs = require;
    this._require_getdents = require;
 
    function create_watcher()
    {
        ths._timeout = setTimeout(ths._poll, 0);
 
        if ((ths._update_size > 0) && (options.notify !== false))
        {
            try
            {
                ths._watcher = ths._fs.watch(ths._update_dir, function (event)
                {
                    if (event === 'change')
                    {
                        ths.refresh_now();
                    }
                });
 
                ths._watcher.on('error', ths._error);
            }
            catch (err)
            {
                ths._stop_timeout();
                emit_error(err);
            }
        }
    }
 
    function start_notifiers(err)
    {
        //console.log('wrote update file', require('os').hostname());
 
        if (err) { return emit_error(err); }
        if (ths._chkstop()) { return; }
 
        create_watcher();
    }
 
    for (var i = 0; i < this.num_buckets; i += 1)
    {
        pending.set(i, []);
        ths._last_refreshed.set(i, 0);
        bucket_formats[i] = format_bucket(i);
    }
 
    process.nextTick(function ()
    {
        if (options.get_disruptor)
        {
            for (let i = 0; i < ths.num_buckets; i += 1)
            {
                ths._disruptors[i] = options.get_disruptor.call(ths, i);
            }
        }
 
        if (ths._do_single)
        {
            try
            {
                ths._fsext = ths._require_fs('fs-ext');
            }
            catch (err)
            {
                ths._do_single = false;
 
                if (ths.emit('single_disabled', err))
                {
                    if (ths._chkstop()) { return; }
                }
                else
                {
                    console.warn("single messages won't be processed", err);
                }
            }
        }
 
        ths._fs = Object.assign({}, ths._require_fs('fs'));
 
        // prevent graceful-fs readdir file sort overhead
        var orig_readdir = ths._fs.readdir;
        ths._fs.readdir = function (path, options, cb)
        {
            var args = [path];
            if (typeof options !== 'function')
            {
                args.push(options);
            }
            else
            {
                cb = options;
            }
            args.push(function (err, files)
            {
                if (files)
                {
                    files.sort = null;
                }
 
                if (typeof cb === 'function')
                {
                    cb.apply(this, arguments);
                }
            });
            return orig_readdir.apply(this, args);
        };
 
        require('graceful-fs').gracefulify(ths._fs);
 
        ths._process_all = process_all_readdir;
        if (options.getdents_size > 0)
        {
            var err = null;
            if (ths._order_by_expiry)
            {
                err = new Error("getdents can't be used with order-by-expiry");
            }
            else
            {
                try
                {
                    ths._process_all =
                        ths._require_getdents('./process_all_getdents').call(ths,
                              options.getdents_size,
                              ths.num_buckets,
                              delivered,
                              pending,
                              make_fname_handler);
                }
                catch (ex)
                {
                    err = ex;
                }
            }
            if (err)
            {
                if (ths.emit('getdents_disabled', err))
                {
                    if (ths._chkstop()) { return; }
                }
                else
                {
                    console.warn("getdents won't be used", err);
                }
            }
        }
 
        for (let i = 0; i < ths.num_buckets; i += 1)
        {
            var b = ths._format_bucket(i);
            dirs.push(ths._msg_dir + path.sep + b);
            dirs.push(ths._topic_dir + path.sep + b);
        }
 
        async.eachSeries(dirs, function (dir, next)
        {
            ths._fs.mkdir(dir, function (err)
            {
                next(err && (err.code !== 'EEXIST') ? err : null);
            });
        }, function (err)
        {
            if (err) { return emit_error(err); }
 
            if (ths._update_size === 0)
            {
                return start_notifiers();
            }
 
            ths._fs.writeFile(ths._update_fname,
                              crypto.randomBytes(ths._update_size),
                              { flag: constants.O_CREAT |
                                      constants.O_WRONLY |
                                      ths._flags },
                              start_notifiers);
        });
    });
}
 
util.inherits(QlobberFSQ, events.EventEmitter);
 
/**
Subscribe to messages in the file system queue.
 
@param {String} topic Which messages you're interested in receiving. Message topics are split into words using `.` as the separator. You can use `*` to match exactly one word in a topic or `#` to match zero or more words. For example, `foo.*` would match `foo.bar` whereas `foo.#` would match `foo`, `foo.bar` and `foo.bar.wup`. Note you can change the separator and wildcard characters by specifying the `separator`, `wildcard_one` and `wildcard_some` options when [constructing `QlobberFSQ` objects](#qlobberfsqoptions). See the [`qlobber` documentation](https://github.com/davedoesdev/qlobber#qlobberoptions) for more information.
 
@param {Function} handler Function to call when a new message is received on the file system queue and its topic matches against `topic`. `handler` will be passed the following arguments:
- `{Readable|Buffer} data` [Readable](http://nodejs.org/api/stream.html#stream_class_stream_readable) stream or message content as a [Buffer](http://nodejs.org/api/buffer.html#buffer_class_buffer). By default you'll receive the message content. If `handler` has a property `accept_stream` set to a truthy value then you'll receive a stream. Note that _all_ subscribers will receive the same stream or content for each message. You should take this into account when reading from the stream. The stream can be piped into multiple [Writable](http://nodejs.org/api/stream.html#stream_class_stream_writable) streams but bear in mind it will go at the rate of the slowest one.
 
- `{Object} info` Metadata for the message, with the following properties:
 
  - `{String} fname` Name of the file in which the message is stored.
  - `{String} path` Full path to the file in which the message is stored.
  - `{String} topic` Topic the message was published with.
  - `{String} [topic_path]` Full path to the file in which the topic overspill is stored (only present if the topic is too long to fit in the file name).
  - `{Integer} expires` When the message expires (number of milliseconds after 1 January 1970 00:00:00 UTC).
  - `{Boolean} single` Whether this message is being given to at most one subscriber (across all `QlobberFSQ` objects).
  - `{Integer} size` Message size in bytes.
 
- `{Function} done` Function to call once you've handled the message. Note that calling this function is only mandatory if `info.single === true`, in order to delete and unlock the file. `done` takes two arguments:
 
  - `{Object} err` If an error occurred then pass details of the error, otherwise pass `null` or `undefined`.
  - `{Function} [finish]` Optional function to call once the message has been deleted and unlocked, in the case of `info.single === true`, or straight away otherwise. It will be passed the following argument:
    - `{Object} err` If an error occurred then details of the error, otherwise `null`.
 
@param {Object} [options] Optional settings for this subscription:
- `{Boolean} subscribe_to_existing` If `true` then `handler` will be called with any existing, unexpired messages that match `topic`, as well as new ones. Note that `handler` will only receive new streams that were published by calling [`publish`](#qlobberfsqprototypepublishtopic-payload-options-cb) with truthy `options.direct`, not existing direct streams.  Defaults to `false` (only new messages).
 
@param {Function} [cb] Optional function to call once the subscription has been registered. This will be passed the following argument:
- `{Object} err` If an error occurred then details of the error, otherwise `null`.
*/
QlobberFSQ.prototype.subscribe = function (topic, handler, options, cb)
{
    if (typeof options === 'function')
    {
        cb = options;
        options = undefined;
    }
 
    options = options || {};
 
    this._matcher.add(topic, handler);
 
    if (options.subscribe_to_existing)
    {
        this._ensure_extra_matcher().add(topic, handler);
    }
 
    if (cb) { cb.call(this); }
};
 
/**
Unsubscribe from messages in the file system queue.
 
@param {String} [topic] Which messages you're no longer interested in receiving via the `handler` function. This should be a topic you've previously passed to [`subscribe`](#qlobberfsqprototypesubscribetopic-handler-options-cb). If topic is `undefined` then all handlers for all topics are unsubscribed.
 
@param {Function} [handler] The function you no longer want to be called with messages published to the topic `topic`. This should be a function you've previously passed to [`subscribe`](#qlobberfsqprototypesubscribetopic-handler-options-cb). If you subscribed `handler` to a different topic then it will still be called for messages which match that topic. If `handler` is `undefined`, all handlers for the topic `topic` are unsubscribed.
 
@param {Function} [cb] Optional function to call once `handler` has been unsubscribed from `topic`. This will be passed the following argument:
- `{Object} err` If an error occurred then details of the error, otherwise `null`.
*/
QlobberFSQ.prototype.unsubscribe = function (topic, handler, cb)
{
    if (typeof topic === 'function')
    {
        cb = topic;
        topic = undefined;
        handler = undefined;
    }
 
    if (topic === undefined)
    {
        this._matcher.clear();
        if (this._extra_matcher)
        {
            this._extra_matcher.clear();
        }
    }
    else if (handler === undefined)
    {
        this._matcher.remove(topic);
        if (this._extra_matcher)
        {
            this._extra_matcher.remove(topic);
        }
    }
    else
    {
        this._matcher.remove(topic, handler);
        if (this._extra_matcher)
        {
            this._extra_matcher.remove(topic, handler);
        }
    }
 
    this._matcher_marker = {};
 
    if (cb) { cb.call(this); }
};
 
function default_hasher(fname)
{
    var h = crypto.createHash('md5'); // not for security, just mapping!
    h.update(fname);
    return h.digest();
}
 
/**
Publish a message to the file system queue.
 
@param {String} topic Message topic. The topic should be a series of words separated by `.` (or the `separator` character you provided to the [`QlobberFSQ constructor`](#qlobberfsqoptions)). Topic words can contain any character, unless you set `encode_topics` to `false` in the [`QlobberFSQ constructor`](#qlobberfsqoptions). In that case they can contain any valid filename character for your file system, although it's probably sensible to limit it to alphanumeric characters, `-`, `_` and `.`.
 
@param {String|Buffer} [payload] Message payload. If you don't pass a payload then `publish` will return a [Writable stream](http://nodejs.org/api/stream.html#stream_class_stream_writable) for you to write the payload into.
 
@param {Object} [options] Optional settings for this publication:
- `{Boolean} single` If `true` then the message will be given to _at most_ one interested subscriber, across all `QlobberFSQ` objects scanning the file system queue. Otherwise all interested subscribers will receive the message (the default).
 
- `{Integer} ttl` Time-to-live (in milliseconds) for this message. If you don't specify anything then `single_ttl` or `multi_ttl` (provided to the [`QlobberFSQ constructor`](#qlobberfsqoptions)) will be used, depending on the value of `single`. After the time-to-live for the message has passed, the message is ignored and deleted when convenient.
 
- `{String} encoding` If `payload` is a string, the encoding to use when writing it out to the message file. Defaults to `utf8`.
 
- `{Integer} mode` The file mode (permissions) to set on the message file. Defaults to octal `0666` (readable and writable to everyone).
 
- `{Function} hasher` A hash function to use for deciding into which bucket the message should be placed. The hash function should return a `Buffer` at least 4 bytes long. It defaults to running `md5` on the message file name. If you supply a `hasher` function it will be passed the following arguments:
 
  - `{String} fname` Message file name.
  - `{Integer} expires` When the message expires (number of milliseconds after 1 January 1970 00:00:00 UTC).
  - `{String} topic` Message topic.
  - `{String|Buffer} payload` Message payload.
  - `{Object} options` The optional settings for this publication.
 
- `{Integer} bucket` Which bucket to write the message into, instead of using `hasher` to calculate it.
 
- `{Boolean} ephemeral` This applies only if a shared memory LMAX Disruptor is being used for the message's bucket (see the `get_disruptor` option to the [`QlobberFSQ constructor`](#qlobberfsqoptions)). By default, the message is written both to the Disruptor and the filesystem. If `ephemeral` is truthy, the message is written only to the Disruptor.
  
  - If the Disruptor's elements aren't large enough to contain the message's metadata, the message won't be written  to the Disruptor and `cb` (below) will receive an error with a property `code` equal to the string `buffer-too-small`.
    
  - However, if the Disruptor's elements aren't large enough for the message's payload, the message _will_ be written to disk. The amount of space available in the Disruptor for the payload can be found via the `ephemeral_size` property on the stream returned by this function. If your message won't fit and you don't want to write it to disk, emit an `error` event on the stream without ending it.
 
- `{Any} direct` Defaults to `false`. If truthy:
 
  - Writes an empty message to disk instead of any data.
  - Calls the `direct_handler.get_stream_for_publish()` method that was passed to the [`QlobberFSQ constructor`](#qlobberfsqoptions). It will be passed the name of the file to which data would otherwise have been written and the value of `direct`.
  - Returns the value that `direct_handler.get_stream_for_publish()` returns.
  - Ignores `single` (i.e. publish to all interested subscribers).
    
@param {Function} [cb] Optional function to call once the message has been written to the file system queue. This will be called after the message has been moved into its bucket and is therefore available to subscribers in any `QlobberFSQ` object scanning the queue. It will be passed the following arguments:
- `{Object} err` If an error occurred then details of the error, otherwise `null`.
 
- `{Object} info` Metadata for the message. See [`subscribe`](#qlobberfsqprototypesubscribetopic-handler-options-cb) for a description of `info`'s properties.
 
@return {Stream|undefined} A [Writable stream](http://nodejs.org/api/stream.html#stream_class_stream_writable) if no `payload` was passed, otherwise `undefined`.
*/
QlobberFSQ.prototype.publish = function (topic, payload, options, cb)
{
    if ((typeof payload !== 'string') &&
        !Buffer.isBuffer(payload) &&
        (payload !== undefined))
    {
        cb = options;
        options = payload;
        payload = undefined;
    }
 
    if (typeof options === 'function')
    {
        cb = options;
        options = undefined;
    }
 
    options = options || {};
 
    var unencoded_topic = topic;
 
    if (this._encode_topics)
    {
        topic = Buffer.from(topic).toString('hex');
    }
 
    var ths = this,
        write_options = {
                          flags: constants.O_EXCL |
                                 constants.O_CREAT |
                                 constants.O_WRONLY |
                                 this._flags,
                          emitClose: true // defaults to false on Node 12
                        },
        now = Date.now(),
        expires = now + (options.ttl || (options.single ? this._single_ttl :
                                                          this._multi_ttl)),
        split = topic.substr(this._split_topic_at),
        unique_bytes = crypto.randomBytes(this._unique_bytes).toString('hex'),
        fname = topic.substr(0, this._split_topic_at) + '@' +
                (split ? 'l' : 's') + '+' +
                expires.toString(16) + '+' +
                (options.direct ? 'd' : options.single ? 's' : 'm') + '+' +
                unique_bytes,
        staging_fname = this._staging_dir + path.sep + fname,
        bucket,
        bucket_fmt,
        msg_fname,
        topic_fname,
        out_stream,
        hasher = options.hasher || default_hasher,
        disruptor,
        element_size,
        element,
        count = 0;
 
    write_options.flag = write_options.flags;
    write_options.encoding = options.encoding || 'utf8';
    write_options.mode = options.mode || 438; // 0666
 
    bucket = (options.bucket === undefined ?
            hasher(fname, expires, topic, payload, options).readUInt32BE(0) :
            options.bucket) % this.num_buckets;
    bucket_fmt = this._format_bucket(bucket);
    msg_fname = this._msg_dir + path.sep + bucket_fmt + path.sep + fname;
    topic_fname = this._topic_dir + path.sep + bucket_fmt + path.sep + fname;
 
    function errored(err)
    {
        if (err)
        {
            ths._error(err);
 
            const unlink_topic = err2 =>
            {
                ths._error(err2, 'ENOENT');
 
                function callback(err3)
                {
                    ths._error(err3, 'ENOENT');
                    if (cb) { cb.call(ths, err); }
                }
 
                try
                {
                    ths._fs.unlink(topic_fname, callback);
                }
                catch (err3)
                {
                    process.nextTick(callback, err3);
                }
            };
 
            try
            {
                ths._fs.unlink(staging_fname, unlink_topic);
            }
            catch (err2)
            {
                process.nextTick(unlink_topic, err2);
            }
 
            return true;
        }
 
        return false;
    }
 
    function onerror(err)
    {
        /*jshint validthis: true */
        this.end();
        errored(err);
    }
 
    function derror(err)
    {
        let called = false;
 
        const check = () =>
        {
            if (!called)
            {
                called = true;
                errored(err);
            }
        };
 
        this.removeListener('finish', claim);
 
        this.once('finish', check);
        this.once('close', check);
 
        this.end();
    }
 
    function register(s, onclose)
    {
        s.once('close', onclose);
 
        s.once('error', function ()
        {
            this.removeListener('close', onclose);
        });
 
        s.once('error', onerror);
 
        s.once('open', function ()
        {
            this.removeListener('error', onerror);
 
            this.once('error', function (err)
            {
                this.once('close', function ()
                {
                    errored(err);
                });
 
                this.end();
            });
        });
    }
 
    function done()
    {
        if (!cb) { return; }
 
        var info = {
            fname: fname,
            path: msg_fname,
            topic: unencoded_topic,
            expires: expires,
            single: !!options.single,
            size: count,
            direct: !!options.direct
        };
 
        if (split)
        {
            info.topic_path = topic_fname;
        }
 
        cb.call(ths, null, info);
    }
 
    function update()
    {
        if (ths._update_size === 0)
        {
            return done();
        }
 
        var update_stream = ths._fs.createWriteStream(ths._update_fname,
        {
            flags: constants.O_CREAT |
                   constants.O_WRONLY |
                   ths._flags,
            start: bucket * ths._bucket_stamp_size
        });
 
        register(update_stream, done);
 
        update_stream.once('open', function ()
        {
            this.end(crypto.randomBytes(ths._bucket_stamp_size));
        });
    }
 
    function commit(start, end)
    {
        if (ths.stopped) { return errored(new Error('stopped')); }
 
        if (!disruptor.produceCommitSync(start, end))
        {
            return setTimeout(commit, ths._disruptor_spin_interval, start, end);
        }
 
        update();
    }
 
    function claim()
    {
        if (ths.stopped) { return errored(new Error('stopped')); }
 
        var b = disruptor.produceClaimSync();
 
        if (b.length == 0)
        {
            return setTimeout(claim, ths._disruptor_spin_interval);
        }
 
        element.copy(b);
        b.writeUInt32LE(count, element_size);
 
        commit(disruptor.prevClaimStart, disruptor.prevClaimEnd);
    }
 
    function rename()
    {
        ths._fs.rename(staging_fname, msg_fname, function (err)
        {
            if (ths._try_again(err))
            {
                ths._error(err);
                return setTimeout(rename, ths._retry_interval);
            }
 
            if (errored(err)) { return; }
 
            if (!disruptor)
            {
                return update();
            }
 
            claim();
        });
    }
 
    function maybe_split()
    {
        count = Math.max(out_stream.bytesWritten - 1, 0);
 
        if (!split)
        {
            return rename();
        }
 
        write_options.encoding = 'utf8';
 
        ths._fs.writeFile(topic_fname, split, write_options, function (err)
        {
            if (errored(err)) { return; }
            rename();
        });
    }
 
    disruptor = ths._disruptors[bucket];
 
    if (disruptor)
    {
        element_size = disruptor.elementSize;
        element = Buffer.alloc(element_size);
        element_size -= 6; // space for data length and filename length
 
        var ephemeral = options.ephemeral && (options.direct || !options.single),
            dfname = ephemeral ?
                (topic + '@s+' +
                 expires.toString(16) + '+' +
                 (options.direct ? 'd' : 'm') + '+' +
                 unique_bytes) :
                fname;
 
        var start = element.write(dfname);
 
        if (start > element_size)
        {
            var err = new Error('buffer too small');
            err.code = 'buffer-too-small';
            return errored(err);
        }
 
        element.writeUInt16LE(start, element_size + 4);
 
        var space = element_size - start,
            pos = start,
            opened = false;
 
        out_stream = new class extends stream.PassThrough
        {
            _write(chunk, encoding, cb)
            {
                const len = chunk.length;
                count += len;
 
                if (count <= space)
                {
                    chunk.copy(element, pos);
                    pos += len;
 
                    if (ephemeral)
                    {
                        return cb();
                    }
                }
 
                if (!opened)
                {
                    opened = true;
 
                    let fs_stream;
                    try
                    {
                        fs_stream = ths._fs.createWriteStream(staging_fname, write_options);
                    }
                    catch (ex)
                    {
                        return cb(ex);
                    }
 
                    out_stream.removeListener('finish', claim);
                    out_stream.removeListener('error', derror);
 
                    register(fs_stream, maybe_split);
                    out_stream.pipe(fs_stream);
                    out_stream.on('error', function (err)
                    {
                        fs_stream.destroy(err);
                        this.end();
                    });
                    out_stream = fs_stream;
 
                    if (ephemeral)
                    {
                        chunk = Buffer.concat([
                            ths._leading_byte,
                            element.slice(start, pos),
                            chunk
                        ]);
                    }
                    else
                    {
                        chunk = Buffer.concat([
                            ths._leading_byte,
                            chunk
                        ]);
                    }
                }
 
                return super._write(chunk, encoding, cb);
            }
        }();
 
        out_stream.ephemeral_size = space;
 
        out_stream.once('finish', claim);
        out_stream.once('error', derror);
    }
 
    if (!out_stream)
    {
        try
        {
            out_stream = this._fs.createWriteStream(staging_fname, write_options);
        }
        catch (ex)
        {
            this._error(ex);
            if (cb) { cb.call(ths, ex); }
            return;
        }
        register(out_stream, maybe_split);
        out_stream.write(ths._leading_byte);
    }
 
    if ((typeof payload !== 'string') && !Buffer.isBuffer(payload))
    {
        if (options.direct)
        {
            if (!this._direct_handler)
            {
                return out_stream.emit(new Error('direct messages not supported'));
            }
            const direct_stream = this._direct_handler.get_stream_for_publish(fname, options.direct);
            const onclose = function ()
            {
                ths._direct_handler.publish_stream_destroyed(fname, this);
            };
            direct_stream.on('close', onclose);
            direct_stream.on('error', ths._error);
            direct_stream.on('predeliver', function ()
            {
                this.removeListener('close', onclose);
                this.removeListener('error', ths._error);
            });
            out_stream.end();
            out_stream = direct_stream;
        }
 
        return out_stream;
    }
 
    out_stream.end(payload);
};
 
QlobberFSQ.prototype._stop_timeout = function ()
{
    if (this._timeout)
    {
        clearTimeout(this._timeout);
        this._timeout = null;
        return true;
    }
 
    return false;
};
 
QlobberFSQ.prototype.___stop_watching = function (err, cb)
{
    if (cb)
    {
        return cb.call(this, err);
    }
 
    if (err)
    {
        this.emit('error', err);
    }
};
 
QlobberFSQ.prototype.__stop_watching = function (err, cb)
{
    this._error(err);
 
    if (this._stop_timeout())
    {
        setImmediate(this._chkstop);
    }
 
    if (this.active)
    {
        return this.once('stop', function ()
        {
            this.___stop_watching(err, cb);
        });
    }
 
    this.___stop_watching(err, cb);
};
 
QlobberFSQ.prototype._stop_watching = function (cb)
{
    for (var i = 0; i < this.num_buckets; i += 1)
    {
        var disruptor = this._disruptors[i];
        if (disruptor)
        {
            this._disruptors[i] = null;
            disruptor.release();
        }
    }
 
    if (this._process_all && this._process_all.stop)
    {
        var ths = this;
        return this._process_all.stop(function (err)
        {
            ths.__stop_watching(err, cb);
        });
    }
 
    this.__stop_watching(null, cb);
};
 
/**
Stop scanning for new messages.
 
@param {Function} [cb] Optional function to call once scanning has stopped. Alternatively, you can listen for the [`stop` event](#qlobberfsqeventsstop).
*/
QlobberFSQ.prototype.stop_watching = function (cb)
{
    if (this.stopped)
    {
        if (cb)
        {
            cb.call(this);
        }
        return;
    }
    this.stopped = true;
 
    var watcher = this._watcher;
    if (watcher)
    {
        this._watcher = null;
        if (semver.gte(process.version, '10.0.0'))
        {
            var ths = this;
            watcher.on('close', function ()
            {
                ths._stop_watching(cb);
            });
            return watcher.close();
        }
        watcher.close();
    }
    this._stop_watching(cb);
};
 
/**
Check the `UPDATE` file now rather than waiting for the next periodic check to occur
*/
QlobberFSQ.prototype.refresh_now = function ()
{
    if (this.stopped) { return; }
 
    if (this._stop_timeout())
    {
        this._poll();
    }
    else
    {
        this._delay = 0;
    }
};
 
/**
Scan for new messages in the `messages` sub-directory without checking whether the `UPDATE` file has changed.
*/
QlobberFSQ.prototype.force_refresh = function ()
{
   this._last_update = crypto.randomBytes(this._update_size);
 
   for (var i = 0; i < this.num_buckets; i += 1)
   {
       this._last_refreshed.set(i, 0);
   }
 
   this.refresh_now();
};
 
/**
Given a radix to use for characters in bucket names and the number of digits in
each name, return the number of buckets that can be represented.
 
@param {Integer} bucket_base Radix for bucket name characters.
 
@param {Integer} bucket_num_chars Number of characters in bucket names.
 
@return {Integer} The number of buckets that can be represented.
*/
QlobberFSQ.get_num_buckets = function (base, num_chars)
{
    return Math.pow(base || 16, num_chars || 2);
};
 
exports.QlobberFSQ = QlobberFSQ;