1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409 18410 18411 18412 18413 18414 18415 18416 18417 18418 18419 18420 18421 18422 18423 18424 18425 18426 18427 18428 18429 18430 18431 18432 18433 18434 18435 18436 18437 18438 18439 18440 18441 18442 18443 18444 18445 18446 18447 18448 18449 18450 18451 18452 18453 18454 18455 18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472 18473 18474 18475 18476 18477 18478 18479 18480 18481 18482 18483 18484 18485 18486 18487 18488 18489 18490 18491 18492 18493 18494 18495 18496 18497 18498 18499 18500 18501 18502 18503 18504 18505 18506 18507 18508 18509 18510 18511 18512 18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524 18525 18526 18527 18528 18529 18530 18531 18532 18533 18534 18535 18536 18537 18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550 18551 18552 18553 18554 18555 18556 18557 18558 18559 18560 18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575 18576 18577 18578 18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592 18593 18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609 18610 18611 18612 18613 18614 18615 18616 18617 18618 18619 18620 18621 18622 18623 18624 18625 18626 18627 18628 18629 18630 18631 18632 18633 18634 18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645 18646 18647 18648 18649 18650 18651 18652 18653 18654 18655 18656 18657 18658 18659 18660 18661 18662 18663 18664 18665 18666 18667 18668 18669 18670 18671 18672 18673 18674 18675 18676 18677 18678 18679 18680 18681 18682 18683 18684 18685 18686 18687 18688 18689 18690 18691 18692 18693 18694 18695 18696 18697 18698 18699 18700 18701 18702 18703 18704 18705 18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732 18733 18734 18735 18736 18737 18738 18739 18740 18741 18742 18743 18744 18745 18746 18747 18748 18749 18750 18751 18752 18753 18754 18755 18756 18757 18758 18759 18760 18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794 18795 18796 18797 18798 18799 18800 18801 18802 18803 18804 18805 18806 18807 18808 18809 18810 18811 18812 18813 18814 18815 18816 18817 18818 18819 18820 18821 18822 18823 18824 18825 18826 18827 18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852 18853 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912 18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957 18958 18959 18960 18961 18962 18963 18964 18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015 19016 19017 19018 19019 19020 19021 19022 19023 19024 19025 19026 19027 19028 19029 19030 19031 19032 19033 19034 19035 19036 19037 19038 19039 19040 19041 19042 19043 19044 19045 19046 19047 19048 19049 19050 19051 19052 19053 19054 19055 19056 19057 19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087 19088 19089 19090 19091 19092 19093 19094 19095 19096 19097 19098 19099 19100 19101 19102 19103 19104 19105 19106 19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117 19118 19119 19120 19121 19122 19123 19124 19125 19126 19127 19128 19129 19130 19131 19132 19133 19134 19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148 19149 19150 19151 19152 19153 19154 19155 19156 19157 19158 19159 19160 19161 19162 19163 19164 19165 19166 19167 19168 19169 19170 19171 19172 19173 19174 19175 19176 19177 19178 19179 19180 19181 19182 19183 19184 19185 19186 19187 19188 19189 19190 19191 19192 19193 19194 19195 19196 19197 19198 19199 19200 19201 19202 19203 19204 19205 19206 19207 19208 19209 19210 19211 19212 19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225 19226 19227 19228 19229 19230 19231 19232 19233 19234 19235 19236 19237 19238 19239 19240 19241 19242 19243 19244 19245 19246 19247 19248 19249 19250 19251 19252 19253 19254 19255 19256 19257 19258 19259 19260 19261 19262 19263 19264 19265 19266 19267 19268 19269 19270 19271 19272 19273 19274 19275 19276 19277 19278 19279 19280 19281 19282 19283 19284 19285 19286 19287 19288 19289 19290 19291 19292 19293 19294 19295 19296 19297 19298 19299 19300 19301 19302 19303 19304 19305 19306 19307 19308 19309 19310 19311 19312 19313 19314 19315 19316 19317 19318 19319 19320 19321 19322 19323 19324 19325 19326 19327 19328 19329 19330 19331 19332 19333 19334 19335 19336 19337 19338 19339 19340 19341 19342 19343 19344 19345 19346 19347 19348 19349 19350 19351 19352 19353 19354 19355 19356 19357 19358 19359 19360 19361 19362 19363 19364 19365 19366 19367 19368 19369 19370 19371 19372 19373 19374 19375 19376 19377 19378 19379 19380 19381 19382 19383 19384 19385 19386 19387 19388 19389 19390 19391 19392 19393 19394 19395 19396 19397 19398 19399 19400 19401 19402 19403 19404 19405 19406 19407 19408 19409 19410 19411 19412 19413 19414 19415 19416 19417 19418 19419 19420 19421 19422 19423 19424 19425 19426 19427 19428 19429 19430 19431 19432 19433 19434 19435 19436 19437 19438 19439 19440 19441 19442 19443 19444 19445 19446 19447 19448 19449 19450 19451 19452 19453 19454 19455 19456 19457 19458 19459 19460 19461 19462 19463 19464 19465 19466 19467 19468 19469 19470 19471 19472 19473 19474 19475 19476 19477 19478 19479 19480 19481 19482 19483 19484 19485 19486 19487 19488 19489 19490 19491 19492 19493 19494 19495 19496 19497 19498 19499 19500 19501 19502 19503 19504 19505 19506 19507 19508 19509 19510 19511 19512 19513 19514 19515 19516 19517 19518 19519 19520 19521 19522 19523 19524 19525 19526 19527 19528 19529 19530 19531 19532 19533 19534 19535 19536 19537 19538 19539 19540 19541 19542 19543 19544 19545 19546 19547 19548 19549 19550 19551 19552 19553 19554 19555 19556 19557 19558 19559 19560 19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572 19573 19574 19575 19576 19577 19578 19579 19580 19581 19582 19583 19584 19585 19586 19587 19588 19589 19590 19591 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623 19624 19625 19626 19627 19628 19629 19630 19631 19632 19633 19634 19635 19636 19637 19638 19639 19640 19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653 19654 19655 19656 19657 19658 19659 19660 19661 19662 19663 19664 19665 19666 19667 19668 19669 19670 19671 19672 19673 19674 19675 19676 19677 19678 19679 19680 19681 19682 19683 19684 19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701 19702 19703 19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716 19717 19718 19719 19720 19721 19722 19723 19724 19725 19726 19727 19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739 19740 19741 19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760 19761 19762 19763 19764 19765 19766 19767 19768 19769 19770 19771 19772 19773 19774 19775 19776 19777 19778 19779 19780 19781 19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796 19797 19798 19799 19800 19801 19802 19803 19804 19805 19806 19807 19808 19809 19810 19811 19812 19813 19814 19815 19816 19817 19818 19819 19820 19821 19822 19823 19824 19825 19826 19827 19828 19829 19830 19831 19832 19833 19834 19835 19836 19837 19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854 19855 19856 19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885 19886 19887 19888 19889 19890 19891 19892 19893 19894 19895 19896 19897 19898 19899 19900 19901 19902 19903 19904 19905 19906 19907 19908 19909 19910 19911 19912 19913 19914 19915 19916 19917 19918 19919 19920 19921 19922 19923 19924 19925 19926 19927 19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942 19943 19944 19945 19946 19947 19948 19949 19950 19951 19952 19953 19954 19955 19956 19957 19958 19959 19960 19961 19962 19963 19964 19965 19966 19967 19968 19969 19970 19971 19972 19973 19974 19975 19976 19977 19978 19979 19980 19981 19982 19983 19984 19985 19986 19987 19988 19989 19990 19991 19992 19993 19994 19995 19996 19997 19998 19999 20000 20001 20002 20003 20004 20005 20006 20007 20008 20009 20010 20011 20012 20013 20014 20015 20016 20017 20018 20019 20020 20021 20022 20023 20024 20025 20026 20027 20028 20029 20030 20031 20032 20033 20034 20035 20036 20037 20038 20039 20040 20041 20042 20043 20044 20045 20046 20047 20048 20049 20050 20051 20052 20053 20054 20055 20056 20057 20058 20059 20060 20061 20062 20063 20064 20065 20066 20067 20068 20069 20070 20071 20072 20073 20074 20075 20076 20077 20078 20079 20080 20081 20082 20083 20084 20085 20086 20087 20088 20089 20090 20091 20092 20093 20094 20095 20096 20097 20098 20099 20100 20101 20102 20103 20104 20105 20106 20107 20108 20109 20110 20111 20112 20113 20114 20115 20116 20117 20118 20119 20120 20121 20122 20123 20124 20125 20126 20127 20128 20129 20130 20131 20132 20133 20134 20135 20136 20137 20138 20139 20140 20141 20142 20143 20144 20145 20146 20147 20148 20149 20150 20151 20152 20153 20154 20155 20156 20157 20158 20159 20160 20161 20162 20163 20164 20165 20166 20167 20168 20169 20170 20171 20172 20173 20174 20175 20176 20177 20178 20179 20180 20181 20182 20183 20184 20185 20186 20187 20188 20189 20190 20191 20192 20193 20194 20195 20196 20197 20198 20199 20200 20201 20202 20203 20204 20205 20206 20207 20208 20209 20210 20211 20212 20213 20214 20215 20216 20217 20218 20219 20220 20221 20222 20223 20224 20225 20226 20227 20228 20229 20230 20231 20232 20233 20234 20235 20236 20237 20238 20239 20240 20241 20242 20243 20244 20245 20246 20247 20248 20249 20250 20251 20252 20253 20254 20255 20256 20257 20258 20259 20260 20261 20262 20263 20264 20265 20266 20267 20268 20269 20270 20271 20272 20273 20274 20275 20276 20277 20278 20279 20280 20281 20282 20283 20284 20285 20286 20287 20288 20289 20290 20291 20292 20293 20294 20295 20296 20297 20298 20299 20300 20301 20302 20303 20304 20305 20306 20307 20308 20309 20310 20311 20312 20313 20314 20315 20316 20317 20318 20319 20320 20321 20322 20323 20324 20325 20326 20327 20328 20329 20330 20331 20332 20333 20334 20335 20336 20337 20338 20339 20340 20341 20342 20343 20344 20345 20346 20347 20348 20349 20350 20351 20352 20353 20354 20355 20356 20357 20358 20359 20360 20361 20362 20363 20364 20365 20366 20367 20368 20369 20370 20371 20372 20373 20374 20375 20376 20377 20378 20379 20380 20381 20382 20383 20384 20385 20386 20387 20388 20389 20390 20391 20392 20393 20394 20395 20396 20397 20398 20399 20400 20401 20402 20403 20404 20405 20406 20407 20408 20409 20410 20411 20412 20413 20414 20415 20416 20417 20418 20419 20420 20421 20422 20423 20424 20425 20426 20427 20428 20429 20430 20431 20432 20433 20434 20435 20436 20437 20438 20439 20440 20441 20442 20443 20444 20445 20446 20447 20448 20449 20450 20451 20452 20453 20454 20455 20456 20457 20458 20459 20460 20461 20462 20463 20464 20465 20466 20467 20468 20469 20470 20471 20472 20473 20474 20475 20476 20477 20478 20479 20480 20481 20482 20483 20484 20485 20486 20487 20488 20489 20490 20491 20492 20493 20494 20495 20496 20497 20498 20499 20500 20501 20502 20503 20504 20505 20506 20507 20508 20509 20510 20511 20512 20513 20514 20515 20516 20517 20518 20519 20520 20521 20522 20523 20524 20525 20526 20527 20528 20529 20530 20531 20532 20533 20534 20535 20536 20537 20538 20539 20540 20541 20542 20543 20544 20545 20546 20547 20548 20549 20550 20551 20552 20553 20554 20555 20556 20557 20558 20559 20560 20561 20562 20563 20564 20565 20566 20567 20568 20569 20570 20571 20572 20573 20574 20575 20576 20577 20578 20579 20580 20581 20582 20583 20584 20585 20586 20587 20588 20589 20590 20591 20592 20593 20594 20595 20596 20597 20598 20599 20600 20601 20602 20603 20604 20605 20606 20607 20608 20609 20610 20611 20612 20613 20614 20615 20616 20617 20618 20619 20620 20621 20622 20623 20624 20625 20626 20627 20628 20629 20630 20631 20632 20633 20634 20635 20636 20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649 20650 20651 20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692 20693 20694 20695 20696 20697 20698 20699 20700 20701 20702 20703 20704 20705 20706 20707 20708 20709 20710 20711 20712 20713 20714 20715 20716 20717 20718 20719 20720 20721 20722 20723 20724 20725 20726 20727 20728 20729 20730 20731 20732 20733 20734 20735 20736 20737 20738 20739 20740 20741 20742 20743 20744 20745 20746 20747 20748 20749 20750 20751 20752 20753 20754 20755 20756 20757 20758 20759 20760 20761 20762 20763 20764 20765 20766 20767 20768 20769 20770 20771 20772 20773 20774 20775 20776 20777 20778 20779 20780 20781 20782 20783 20784 20785 20786 20787 20788 20789 20790 20791 20792 20793 20794 20795 20796 20797 20798 20799 20800 20801 20802 20803 20804 20805 20806 20807 20808 20809 20810 20811 20812 20813 20814 20815 20816 20817 20818 20819 20820 20821 20822 20823 20824 20825 20826 20827 20828 20829 20830 20831 20832 20833 20834 20835 20836 20837 20838 20839 20840 20841 20842 20843 20844 20845 20846 20847 20848 20849 20850 20851 20852 20853 20854 20855 20856 20857 20858 20859 20860 20861 20862 20863 20864 20865 20866 20867 20868 20869 20870 20871 20872 20873 20874 20875 20876 20877 20878 20879 20880 20881 20882 20883 20884 20885 20886 20887 20888 20889 20890 20891 20892 20893 20894 20895 20896 20897 20898 20899 20900 20901 20902 20903 20904 20905 20906 20907 20908 20909 20910 20911 20912 20913 20914 20915 20916 20917 20918 20919 20920 20921 20922 20923 20924 20925 20926 20927 20928 20929 20930 20931 20932 20933 20934 20935 20936 20937 20938 20939 20940 20941 20942 20943 20944 20945 20946 20947 20948 20949 20950 20951 20952 20953 20954 20955 20956 20957 20958 20959 20960 20961 20962 20963 20964 20965 20966 20967 20968 20969 20970 20971 20972 20973 20974 20975 20976 20977 20978 20979 20980 20981 20982 20983 20984 20985 20986 20987 20988 20989 20990 20991 20992 20993 20994 20995 20996 20997 20998 20999 21000 21001 21002 21003 21004 21005 21006 21007 21008 21009 21010 21011 21012 21013 21014 21015 21016 21017 21018 21019 21020 21021 21022 21023 21024 21025 21026 21027 21028 21029 21030 21031 21032 21033 21034 21035 21036 21037 21038 21039 21040 21041 21042 21043 21044 21045 21046 21047 21048 21049 21050 21051 21052 21053 21054 21055 21056 21057 21058 21059 21060 21061 21062 21063 21064 21065 21066 21067 21068 21069 21070 21071 21072 21073 21074 21075 21076 21077 21078 21079 21080 21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091 21092 21093 21094 21095 21096 21097 21098 21099 21100 21101 21102 21103 21104 21105 21106 21107 21108 21109 21110 21111 21112 21113 21114 21115 21116 21117 21118 21119 21120 21121 21122 21123 21124 21125 21126 21127 21128 21129 21130 21131 21132 21133 21134 21135 21136 21137 21138 21139 21140 21141 21142 21143 21144 21145 21146 21147 21148 21149 21150 21151 21152 21153 21154 21155 21156 21157 21158 21159 21160 21161 21162 21163 21164 21165 21166 21167 21168 21169 21170 21171 21172 21173 21174 21175 21176 21177 21178 21179 21180 21181 21182 21183 21184 21185 21186 21187 21188 21189 21190 21191 21192 21193 21194 21195 21196 21197 21198 21199 21200 21201 21202 21203 21204 21205 21206 21207 21208 21209 21210 21211 21212 21213 21214 21215 21216 21217 21218 21219 21220 21221 21222 21223 21224 21225 21226 21227 21228 21229 21230 21231 21232 21233 21234 21235 21236 21237 21238 21239 21240 21241 21242 21243 21244 21245 21246 21247 21248 21249 21250 21251 21252 21253 21254 21255 21256 21257 21258 21259 21260 21261 21262 21263 21264 21265 21266 21267 21268 21269 21270 21271 21272 21273 21274 21275 21276 21277 21278 21279 21280 21281 21282 21283 21284 21285 21286 21287 21288 21289 21290 21291 21292 21293 21294 21295 21296 21297 21298 21299 21300 21301 21302 21303 21304 21305 21306 21307 21308 21309 21310 21311 21312 21313 21314 21315 21316 21317 21318 21319 21320 21321 21322 21323 21324 21325 21326 21327 21328 21329 21330 21331 21332 21333 21334 21335 21336 21337 21338 21339 21340 21341 21342 21343 21344 21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355 21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379 21380 21381 21382 21383 21384 21385 21386 21387 21388 21389 21390 21391 21392 21393 21394 21395 21396 21397 21398 21399 21400 21401 21402 21403
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "ActorsParent.h"
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <cstdint>
#include <functional>
#include <iterator>
#include <new>
#include <numeric>
#include <tuple>
#include <type_traits>
#include <utility>
#include "ActorsParentCommon.h"
#include "CrashAnnotations.h"
#include "DBSchema.h"
#include "DatabaseFileInfo.h"
#include "DatabaseFileManager.h"
#include "DatabaseFileManagerImpl.h"
#include "ErrorList.h"
#include "IDBCursorType.h"
#include "IDBObjectStore.h"
#include "IDBTransaction.h"
#include "IndexedDBCipherKeyManager.h"
#include "IndexedDBCommon.h"
#include "IndexedDatabaseInlines.h"
#include "IndexedDatabaseManager.h"
#include "KeyPath.h"
#include "MainThreadUtils.h"
#include "NotifyUtils.h"
#include "ProfilerHelpers.h"
#include "ReportInternalError.h"
#include "SafeRefPtr.h"
#include "SchemaUpgrades.h"
#include "chrome/common/ipc_channel.h"
#include "ipc/IPCMessageUtils.h"
#include "js/RootingAPI.h"
#include "js/StructuredClone.h"
#include "js/Value.h"
#include "jsapi.h"
#include "mozIStorageAsyncConnection.h"
#include "mozIStorageConnection.h"
#include "mozIStorageFunction.h"
#include "mozIStorageProgressHandler.h"
#include "mozIStorageService.h"
#include "mozIStorageStatement.h"
#include "mozIStorageValueArray.h"
#include "mozStorageCID.h"
#include "mozStorageHelper.h"
#include "mozilla/Algorithm.h"
#include "mozilla/ArrayAlgorithm.h"
#include "mozilla/ArrayIterator.h"
#include "mozilla/Assertions.h"
#include "mozilla/Atomics.h"
#include "mozilla/Attributes.h"
#include "mozilla/Casting.h"
#include "mozilla/CondVar.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/EndianUtils.h"
#include "mozilla/ErrorNames.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/InitializedOnce.h"
#include "mozilla/Logging.h"
#include "mozilla/MacroForEach.h"
#include "mozilla/Maybe.h"
#include "mozilla/Monitor.h"
#include "mozilla/Mutex.h"
#include "mozilla/NotNull.h"
#include "mozilla/Preferences.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/RefCountType.h"
#include "mozilla/RefCounted.h"
#include "mozilla/RemoteLazyInputStreamParent.h"
#include "mozilla/RemoteLazyInputStreamStorage.h"
#include "mozilla/Result.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/SchedulerGroup.h"
#include "mozilla/SnappyCompressOutputStream.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/Variant.h"
#include "mozilla/dom/BlobImpl.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/FileBlobImpl.h"
#include "mozilla/dom/FlippedOnce.h"
#include "mozilla/dom/IDBCursorBinding.h"
#include "mozilla/dom/IDBFactory.h"
#include "mozilla/dom/IPCBlob.h"
#include "mozilla/dom/IPCBlobUtils.h"
#include "mozilla/dom/IndexedDatabase.h"
#include "mozilla/dom/Nullable.h"
#include "mozilla/dom/PContentParent.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/indexedDB/IDBResult.h"
#include "mozilla/dom/indexedDB/Key.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBCursor.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBCursorParent.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBDatabase.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBDatabaseFileParent.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBDatabaseParent.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBFactory.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBFactoryParent.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBFactoryRequestParent.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBRequest.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBRequestParent.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBSharedTypes.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBTransactionParent.h"
#include "mozilla/dom/indexedDB/PBackgroundIDBVersionChangeTransactionParent.h"
#include "mozilla/dom/indexedDB/PBackgroundIndexedDBUtilsParent.h"
#include "mozilla/dom/ipc/IdType.h"
#include "mozilla/dom/quota/Assertions.h"
#include "mozilla/dom/quota/CachingDatabaseConnection.h"
#include "mozilla/dom/quota/Client.h"
#include "mozilla/dom/quota/ClientDirectoryLock.h"
#include "mozilla/dom/quota/ClientDirectoryLockHandle.h"
#include "mozilla/dom/quota/ClientImpl.h"
#include "mozilla/dom/quota/ConditionalCompilation.h"
#include "mozilla/dom/quota/Date.h"
#include "mozilla/dom/quota/DecryptingInputStream_impl.h"
#include "mozilla/dom/quota/DirectoryLock.h"
#include "mozilla/dom/quota/DirectoryLockInlines.h"
#include "mozilla/dom/quota/DirectoryMetadata.h"
#include "mozilla/dom/quota/EncryptingOutputStream_impl.h"
#include "mozilla/dom/quota/ErrorHandling.h"
#include "mozilla/dom/quota/FileStreams.h"
#include "mozilla/dom/quota/OriginScope.h"
#include "mozilla/dom/quota/PersistenceScope.h"
#include "mozilla/dom/quota/PersistenceType.h"
#include "mozilla/dom/quota/PrincipalUtils.h"
#include "mozilla/dom/quota/QuotaCommon.h"
#include "mozilla/dom/quota/QuotaManager.h"
#include "mozilla/dom/quota/QuotaObject.h"
#include "mozilla/dom/quota/ResultExtensions.h"
#include "mozilla/dom/quota/ThreadUtils.h"
#include "mozilla/dom/quota/UniversalDirectoryLock.h"
#include "mozilla/dom/quota/UsageInfo.h"
#include "mozilla/fallible.h"
#include "mozilla/glean/DomIndexedDBMetrics.h"
#include "mozilla/ipc/BackgroundParent.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/ipc/InputStreamParams.h"
#include "mozilla/ipc/PBackgroundParent.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/ipc/ProtocolUtils.h"
#include "mozilla/mozalloc.h"
#include "mozilla/storage/Variant.h"
#include "nsBaseHashtable.h"
#include "nsCOMPtr.h"
#include "nsClassHashtable.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsEscape.h"
#include "nsHashKeys.h"
#include "nsIAsyncInputStream.h"
#include "nsID.h"
#include "nsIDUtils.h"
#include "nsIDirectoryEnumerator.h"
#include "nsIEventTarget.h"
#include "nsIFile.h"
#include "nsIFileProtocolHandler.h"
#include "nsIFileStreams.h"
#include "nsIFileURL.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsIProtocolHandler.h"
#include "nsIRunnable.h"
#include "nsISupports.h"
#include "nsISupportsPriority.h"
#include "nsISupportsUtils.h"
#include "nsIThread.h"
#include "nsIThreadInternal.h"
#include "nsITimer.h"
#include "nsIURIMutator.h"
#include "nsIVariant.h"
#include "nsLiteralString.h"
#include "nsNetCID.h"
#include "nsPrintfCString.h"
#include "nsProxyRelease.h"
#include "nsServiceManagerUtils.h"
#include "nsStreamUtils.h"
#include "nsString.h"
#include "nsStringFlags.h"
#include "nsStringFwd.h"
#include "nsTArray.h"
#include "nsTHashMap.h"
#include "nsTHashSet.h"
#include "nsTHashtable.h"
#include "nsTLiteralString.h"
#include "nsTStringRepr.h"
#include "nsThreadPool.h"
#include "nsThreadUtils.h"
#include "nscore.h"
#include "prinrval.h"
#include "prio.h"
#include "prsystem.h"
#include "prthread.h"
#include "prtime.h"
#include "prtypes.h"
#include "snappy/snappy.h"
struct JSContext;
class JSObject;
template <class T>
class nsPtrHashKey;
#define IDB_DEBUG_LOG(_args) \
MOZ_LOG(IndexedDatabaseManager::GetLoggingModule(), LogLevel::Debug, _args)
#if defined(MOZ_WIDGET_ANDROID)
# define IDB_MOBILE
#endif
// Helper macros to reduce assertion verbosity
// AUUF == ASSERT_UNREACHABLE_UNLESS_FUZZING
#ifdef DEBUG
# ifdef FUZZING
# define NS_AUUF_OR_WARN(...) NS_WARNING(__VA_ARGS__)
# else
# define NS_AUUF_OR_WARN(...) MOZ_ASSERT(false, __VA_ARGS__)
# endif
# define NS_AUUF_OR_WARN_IF(cond) \
[](bool aCond) { \
if (MOZ_UNLIKELY(aCond)) { \
NS_AUUF_OR_WARN(#cond); \
} \
return aCond; \
}((cond))
#else
# define NS_AUUF_OR_WARN(...) \
do { \
} while (false)
# define NS_AUUF_OR_WARN_IF(cond) static_cast<bool>(cond)
#endif
namespace mozilla {
namespace dom::indexedDB {
using namespace mozilla::dom::quota;
using namespace mozilla::ipc;
using mozilla::dom::quota::Client;
namespace {
class ConnectionPool;
class Database;
struct DatabaseActorInfo;
class DatabaseFile;
class DatabaseLoggingInfo;
class DatabaseMaintenance;
class Factory;
class Maintenance;
class OpenDatabaseOp;
class TransactionBase;
class TransactionDatabaseOperationBase;
class VersionChangeTransaction;
template <bool StatementHasIndexKeyBindings>
struct ValuePopulateResponseHelper;
/*******************************************************************************
* Constants
******************************************************************************/
const int32_t kStorageProgressGranularity = 1000;
// Changing the value here will override the page size of new databases only.
// A journal mode change and VACUUM are needed to change existing databases, so
// the best way to do that is to use the schema version upgrade mechanism.
const uint32_t kSQLitePageSizeOverride =
#ifdef IDB_MOBILE
2048;
#else
4096;
#endif
static_assert(kSQLitePageSizeOverride == /* mozStorage default */ 0 ||
(kSQLitePageSizeOverride % 2 == 0 &&
kSQLitePageSizeOverride >= 512 &&
kSQLitePageSizeOverride <= 65536),
"Must be 0 (disabled) or a power of 2 between 512 and 65536!");
// Set to -1 to use SQLite's default, 0 to disable, or some positive number to
// enforce a custom limit.
const int32_t kMaxWALPages = 5000; // 20MB on desktop, 10MB on mobile.
// Set to some multiple of the page size to grow the database in larger chunks.
const uint32_t kSQLiteGrowthIncrement = kSQLitePageSizeOverride * 2;
static_assert(kSQLiteGrowthIncrement >= 0 &&
kSQLiteGrowthIncrement % kSQLitePageSizeOverride == 0 &&
kSQLiteGrowthIncrement < uint32_t(INT32_MAX),
"Must be 0 (disabled) or a positive multiple of the page size!");
// The maximum number of threads that can be used for database activity at a
// single time. Please keep in sync with the constants in
// test_connection_idle_maintenance*.js tests
const uint32_t kMaxConnectionThreadCount = 20;
static_assert(kMaxConnectionThreadCount, "Must have at least one thread!");
// The maximum number of threads to keep when idle. Until we switch to the STS
// pool, we can reduce the number of idle threads kept around thanks to the
// grace timeout.
const uint32_t kMaxIdleConnectionThreadCount = 1;
static_assert(kMaxConnectionThreadCount >= kMaxIdleConnectionThreadCount,
"Idle thread limit must be less than total thread limit!");
// The length of time that wanted idle threads will stay alive before being shut
// down.
const uint32_t kConnectionThreadMaxIdleMS = 30 * 1000; // 30 seconds
// The length of time that excess idle threads will stay alive before being shut
// down.
const uint32_t kConnectionThreadGraceIdleMS = 500; // 0.5 seconds
// The length of time that database connections will be held open after all
// transactions have completed before doing idle maintenance. Please keep in
// sync with the timeouts in test_connection_idle_maintenance*.js tests
const uint32_t kConnectionIdleMaintenanceMS = 2 * 1000; // 2 seconds
// The length of time that database connections will be held open after all
// transactions and maintenance have completed.
const uint32_t kConnectionIdleCloseMS = 10 * 1000; // 10 seconds
#define SAVEPOINT_CLAUSE "SAVEPOINT sp;"_ns
// For efficiency reasons, kEncryptedStreamBlockSize must be a multiple of large
// 4k disk sectors.
static_assert(kEncryptedStreamBlockSize % 4096 == 0);
// Similarly, the file copy buffer size must be a multiple of the encrypted
// block size.
static_assert(kFileCopyBufferSize % kEncryptedStreamBlockSize == 0);
constexpr auto kFileManagerDirectoryNameSuffix = u".files"_ns;
constexpr auto kSQLiteSuffix = u".sqlite"_ns;
constexpr auto kSQLiteJournalSuffix = u".sqlite-journal"_ns;
constexpr auto kSQLiteSHMSuffix = u".sqlite-shm"_ns;
constexpr auto kSQLiteWALSuffix = u".sqlite-wal"_ns;
// The following constants define all names of binding parameters in statements,
// where they are bound by name. This should include all parameter names which
// are bound by name. Binding may be done by index when the statement definition
// and binding are done in the same local scope, and no other reasons prevent
// using the indexes (e.g. multiple statement variants with differing number or
// order of parameters). Neither the styles of specifying parameter names
// (literally vs. via these constants) nor the binding styles (by index vs. by
// name) should not be mixed for the same statement. The decision must be made
// for each statement based on the proximity of statement and binding calls.
constexpr auto kStmtParamNameCurrentKey = "current_key"_ns;
constexpr auto kStmtParamNameRangeBound = "range_bound"_ns;
constexpr auto kStmtParamNameObjectStorePosition = "object_store_position"_ns;
constexpr auto kStmtParamNameLowerKey = "lower_key"_ns;
constexpr auto kStmtParamNameUpperKey = "upper_key"_ns;
constexpr auto kStmtParamNameKey = "key"_ns;
constexpr auto kStmtParamNameObjectStoreId = "object_store_id"_ns;
constexpr auto kStmtParamNameIndexId = "index_id"_ns;
// TODO: Maybe the uses of kStmtParamNameId should be replaced by more
// specific constants such as kStmtParamNameObjectStoreId.
constexpr auto kStmtParamNameId = "id"_ns;
constexpr auto kStmtParamNameValue = "value"_ns;
constexpr auto kStmtParamNameObjectDataKey = "object_data_key"_ns;
constexpr auto kStmtParamNameIndexDataValues = "index_data_values"_ns;
constexpr auto kStmtParamNameData = "data"_ns;
constexpr auto kStmtParamNameFileIds = "file_ids"_ns;
constexpr auto kStmtParamNameValueLocale = "value_locale"_ns;
constexpr auto kStmtParamNameLimit = "limit"_ns;
// The following constants define some names of columns in tables, which are
// referred to in remote locations, e.g. in calls to
// GetBindingClauseForKeyRange.
constexpr auto kColumnNameKey = "key"_ns;
constexpr auto kColumnNameValue = "value"_ns;
constexpr auto kColumnNameAliasSortKey = "sort_column"_ns;
// SQL fragments used at multiple locations.
constexpr auto kOpenLimit = " LIMIT "_ns;
// The deletion marker file is created before RemoveDatabaseFilesAndDirectory
// begins deleting a database. It is removed as the last step of deletion. If a
// deletion marker file is found when initializing the origin, the deletion
// routine is run again to ensure that the database and all of its related files
// are removed. The primary goal of this mechanism is to avoid situations where
// a database has been partially deleted, leading to inconsistent state for the
// origin.
constexpr auto kIdbDeletionMarkerFilePrefix = u"idb-deleting-"_ns;
const uint32_t kDeleteTimeoutMs = 1000;
#ifdef DEBUG
const int32_t kDEBUGThreadPriority = nsISupportsPriority::PRIORITY_NORMAL;
const uint32_t kDEBUGThreadSleepMS = 0;
// Set to a non-zero number to enable debugging of transaction event targets.
// It will cause sleeping after every transaction runnable!
//
// This can be useful for discovering race conditions related to switching to
// another thread. Such races are usually avoided by using MozPromise or
// RunAfterProcessingCurrentEvent. Chaos mode doesn't always help with
// uncovering these issues, and only a precisely targeted sleep call can
// simulate the problem.
const uint32_t kDEBUGTransactionThreadSleepMS = 0;
// Make sure that we notice if we ever accidentally check in a non-zero value.
# ifdef MOZILLA_OFFICIAL
static_assert(kDEBUGTransactionThreadSleepMS == 0);
# endif
#endif
/*******************************************************************************
* Metadata classes
******************************************************************************/
// Can be instantiated either on the QuotaManager IO thread or on a
// versionchange transaction thread. These threads can never race so this is
// totally safe.
struct FullIndexMetadata {
IndexMetadata mCommonMetadata = {0, nsString(), KeyPath(0), nsCString(),
false, false, false};
FlippedOnce<false> mDeleted;
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(FullIndexMetadata)
private:
~FullIndexMetadata() = default;
};
using IndexTable = nsTHashMap<nsUint64HashKey, SafeRefPtr<FullIndexMetadata>>;
// Can be instantiated either on the QuotaManager IO thread or on a
// versionchange transaction thread. These threads can never race so this is
// totally safe.
struct FullObjectStoreMetadata {
ObjectStoreMetadata mCommonMetadata;
IndexTable mIndexes;
// The auto increment ids are touched on both the background thread and the
// transaction I/O thread, and they must be kept in sync, so we need a mutex
// to protect them.
struct AutoIncrementIds {
int64_t next;
int64_t committed;
};
DataMutex<AutoIncrementIds> mAutoIncrementIds;
FlippedOnce<false> mDeleted;
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(FullObjectStoreMetadata);
bool HasLiveIndexes() const;
FullObjectStoreMetadata(ObjectStoreMetadata aCommonMetadata,
const AutoIncrementIds& aAutoIncrementIds)
: mCommonMetadata{std::move(aCommonMetadata)},
mAutoIncrementIds{AutoIncrementIds{aAutoIncrementIds},
"FullObjectStoreMetadata"} {}
private:
~FullObjectStoreMetadata() = default;
};
using ObjectStoreTable =
nsTHashMap<nsUint64HashKey, SafeRefPtr<FullObjectStoreMetadata>>;
static_assert(
std::is_same_v<IndexOrObjectStoreId,
std::remove_cv_t<std::remove_reference_t<
decltype(std::declval<const ObjectStoreGetParams&>()
.objectStoreId())>>>);
static_assert(
std::is_same_v<
IndexOrObjectStoreId,
std::remove_cv_t<std::remove_reference_t<
decltype(std::declval<const IndexGetParams&>().objectStoreId())>>>);
struct FullDatabaseMetadata final : AtomicSafeRefCounted<FullDatabaseMetadata> {
DatabaseMetadata mCommonMetadata;
nsCString mDatabaseId;
nsString mFilePath;
ObjectStoreTable mObjectStores;
IndexOrObjectStoreId mNextObjectStoreId = 0;
IndexOrObjectStoreId mNextIndexId = 0;
public:
explicit FullDatabaseMetadata(const DatabaseMetadata& aCommonMetadata)
: mCommonMetadata(aCommonMetadata) {
AssertIsOnBackgroundThread();
}
[[nodiscard]] SafeRefPtr<FullDatabaseMetadata> Duplicate() const;
MOZ_DECLARE_REFCOUNTED_TYPENAME(FullDatabaseMetadata)
};
template <class Enumerable>
auto MatchMetadataNameOrId(const Enumerable& aEnumerable,
IndexOrObjectStoreId aId,
Maybe<const nsAString&> aName = Nothing()) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aId);
const auto it = std::find_if(
aEnumerable.cbegin(), aEnumerable.cend(),
[aId, aName](const auto& entry) {
MOZ_ASSERT(entry.GetKey() != 0);
const auto& value = entry.GetData();
MOZ_ASSERT(value);
return !value->mDeleted &&
(aId == value->mCommonMetadata.id() ||
(aName && *aName == value->mCommonMetadata.name()));
});
return ToMaybeRef(it != aEnumerable.cend() ? it->GetData().unsafeGetRawPtr()
: nullptr);
}
/*******************************************************************************
* SQLite functions
******************************************************************************/
// WARNING: the hash function used for the database name must not change.
// That's why this function exists separately from mozilla::HashString(), even
// though it is (at the time of writing) equivalent. See bug 780408 and bug
// 940315 for details.
uint32_t HashName(const nsAString& aName) {
struct Helper {
static uint32_t RotateBitsLeft32(uint32_t aValue, uint8_t aBits) {
MOZ_ASSERT(aBits < 32);
return (aValue << aBits) | (aValue >> (32 - aBits));
}
};
static const uint32_t kGoldenRatioU32 = 0x9e3779b9u;
return std::accumulate(aName.BeginReading(), aName.EndReading(), uint32_t(0),
[](uint32_t hash, char16_t ch) {
return kGoldenRatioU32 *
(Helper::RotateBitsLeft32(hash, 5) ^ ch);
});
}
nsresult ClampResultCode(nsresult aResultCode) {
if (NS_SUCCEEDED(aResultCode) ||
NS_ERROR_GET_MODULE(aResultCode) == NS_ERROR_MODULE_DOM_INDEXEDDB) {
return aResultCode;
}
switch (aResultCode) {
case NS_ERROR_FILE_NO_DEVICE_SPACE:
return NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR;
case NS_ERROR_STORAGE_CONSTRAINT:
return NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR;
default:
#ifdef DEBUG
nsPrintfCString message("Converting non-IndexedDB error code (0x%" PRIX32
") to "
"NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR",
static_cast<uint32_t>(aResultCode));
NS_WARNING(message.get());
#else
;
#endif
}
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
Result<nsCOMPtr<nsIFileURL>, nsresult> GetDatabaseFileURL(
nsIFile& aDatabaseFile, const int64_t aDirectoryLockId,
const Maybe<CipherKey>& aMaybeKey) {
MOZ_ASSERT(aDirectoryLockId >= -1);
QM_TRY_INSPECT(
const auto& protocolHandler,
MOZ_TO_RESULT_GET_TYPED(nsCOMPtr<nsIProtocolHandler>,
MOZ_SELECT_OVERLOAD(do_GetService),
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "file"));
QM_TRY_INSPECT(const auto& fileHandler,
MOZ_TO_RESULT_GET_TYPED(nsCOMPtr<nsIFileProtocolHandler>,
MOZ_SELECT_OVERLOAD(do_QueryInterface),
protocolHandler));
QM_TRY_INSPECT(const auto& mutator, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<nsIURIMutator>, fileHandler,
NewFileURIMutator, &aDatabaseFile));
// aDirectoryLockId should only be -1 when we are called
// - from DatabaseFileManager::InitDirectory when the temporary storage
// hasn't been initialized yet. At that time, the in-memory objects (e.g.
// OriginInfo) are only being created so it doesn't make sense to tunnel
// quota information to QuotaVFS to get corresponding QuotaObject instances
// for SQLite files.
// - from DeleteDatabaseOp::LoadPreviousVersion, since this might require
// temporarily exceeding the quota limit before the database can be
// deleted.
const nsCString directoryLockIdClause =
"&directoryLockId="_ns + IntToCString(aDirectoryLockId);
const auto keyClause = [&aMaybeKey] {
nsAutoCString keyClause;
if (aMaybeKey) {
keyClause.AssignLiteral("&key=");
for (uint8_t byte : IndexedDBCipherStrategy::SerializeKey(*aMaybeKey)) {
keyClause.AppendPrintf("%02x", byte);
}
}
return keyClause;
}();
QM_TRY_UNWRAP(auto result, ([&mutator, &directoryLockIdClause, &keyClause] {
nsCOMPtr<nsIFileURL> result;
nsresult rv = NS_MutateURI(mutator)
.SetQuery("cache=private"_ns +
directoryLockIdClause + keyClause)
.Finalize(result);
return NS_SUCCEEDED(rv)
? Result<nsCOMPtr<nsIFileURL>, nsresult>{result}
: Err(rv);
}()));
return result;
}
nsLiteralCString GetDefaultSynchronousMode() {
return IndexedDatabaseManager::FullSynchronous() ? "FULL"_ns : "NORMAL"_ns;
}
nsresult SetDefaultPragmas(mozIStorageConnection& aConnection) {
MOZ_ASSERT(!NS_IsMainThread());
static constexpr auto kBuiltInPragmas =
// We use foreign keys in DEBUG builds only because there is a performance
// cost to using them.
"PRAGMA foreign_keys = "
#ifdef DEBUG
"ON"
#else
"OFF"
#endif
";"
// The "INSERT OR REPLACE" statement doesn't fire the update trigger,
// instead it fires only the insert trigger. This confuses the update
// refcount function. This behavior changes with enabled recursive
// triggers, so the statement fires the delete trigger first and then the
// insert trigger.
"PRAGMA recursive_triggers = ON;"
// We aggressively truncate the database file when idle so don't bother
// overwriting the WAL with 0 during active periods.
"PRAGMA secure_delete = OFF;"_ns;
QM_TRY(MOZ_TO_RESULT(aConnection.ExecuteSimpleSQL(kBuiltInPragmas)));
QM_TRY(MOZ_TO_RESULT(aConnection.ExecuteSimpleSQL(nsAutoCString{
"PRAGMA synchronous = "_ns + GetDefaultSynchronousMode() + ";"_ns})));
#ifndef IDB_MOBILE
if (kSQLiteGrowthIncrement) {
// This is just an optimization so ignore the failure if the disk is
// currently too full.
QM_TRY(QM_OR_ELSE_WARN_IF(
// Expression.
MOZ_TO_RESULT(
aConnection.SetGrowthIncrement(kSQLiteGrowthIncrement, ""_ns)),
// Predicate.
IsSpecificError<NS_ERROR_FILE_TOO_BIG>,
// Fallback.
ErrToDefaultOk<>));
}
#endif // IDB_MOBILE
return NS_OK;
}
nsresult SetJournalMode(mozIStorageConnection& aConnection) {
MOZ_ASSERT(!NS_IsMainThread());
// Try enabling WAL mode. This can fail in various circumstances so we have to
// check the results here.
constexpr auto journalModeQueryStart = "PRAGMA journal_mode = "_ns;
constexpr auto journalModeWAL = "wal"_ns;
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement(
aConnection, journalModeQueryStart + journalModeWAL));
QM_TRY_INSPECT(
const auto& journalMode,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsCString, *stmt, GetUTF8String, 0));
if (journalMode.Equals(journalModeWAL)) {
// WAL mode successfully enabled. Maybe set limits on its size here.
if (kMaxWALPages >= 0) {
QM_TRY(MOZ_TO_RESULT(aConnection.ExecuteSimpleSQL(
"PRAGMA wal_autocheckpoint = "_ns + IntToCString(kMaxWALPages))));
}
} else {
NS_WARNING("Failed to set WAL mode, falling back to normal journal mode.");
#ifdef IDB_MOBILE
QM_TRY(MOZ_TO_RESULT(
aConnection.ExecuteSimpleSQL(journalModeQueryStart + "truncate"_ns)));
#endif
}
return NS_OK;
}
Result<MovingNotNull<nsCOMPtr<mozIStorageConnection>>, nsresult> OpenDatabase(
mozIStorageService& aStorageService, nsIFileURL& aFileURL,
const uint32_t aTelemetryId = 0) {
const nsAutoCString telemetryFilename =
aTelemetryId ? "indexedDB-"_ns + IntToCString(aTelemetryId) +
NS_ConvertUTF16toUTF8(kSQLiteSuffix)
: nsAutoCString();
QM_TRY_UNWRAP(auto connection,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageConnection>, aStorageService,
OpenDatabaseWithFileURL, &aFileURL, telemetryFilename,
mozIStorageService::CONNECTION_INTERRUPTIBLE));
return WrapMovingNotNull(std::move(connection));
}
Result<MovingNotNull<nsCOMPtr<mozIStorageConnection>>, nsresult>
OpenDatabaseAndHandleBusy(mozIStorageService& aStorageService,
nsIFileURL& aFileURL,
const uint32_t aTelemetryId = 0) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
using ConnectionType = Maybe<MovingNotNull<nsCOMPtr<mozIStorageConnection>>>;
QM_TRY_UNWRAP(auto connection,
QM_OR_ELSE_WARN_IF(
// Expression
OpenDatabase(aStorageService, aFileURL, aTelemetryId)
.map([](auto connection) -> ConnectionType {
return Some(std::move(connection));
}),
// Predicate.
IsSpecificError<NS_ERROR_STORAGE_BUSY>,
// Fallback.
ErrToDefaultOk<ConnectionType>));
if (connection.isNothing()) {
#ifdef DEBUG
{
nsCString path;
MOZ_ALWAYS_SUCCEEDS(aFileURL.GetFileName(path));
nsPrintfCString message(
"Received NS_ERROR_STORAGE_BUSY when attempting to open database "
"'%s', retrying for up to 10 seconds",
path.get());
NS_WARNING(message.get());
}
#endif
// Another thread must be checkpointing the WAL. Wait up to 10 seconds for
// that to complete.
const TimeStamp start = TimeStamp::NowLoRes();
do {
PR_Sleep(PR_MillisecondsToInterval(100));
QM_TRY_UNWRAP(connection,
QM_OR_ELSE_WARN_IF(
// Expression.
OpenDatabase(aStorageService, aFileURL, aTelemetryId)
.map([](auto connection) -> ConnectionType {
return Some(std::move(connection));
}),
// Predicate.
([&start](nsresult aValue) {
return aValue == NS_ERROR_STORAGE_BUSY &&
TimeStamp::NowLoRes() - start <=
TimeDuration::FromSeconds(10);
}),
// Fallback.
ErrToDefaultOk<ConnectionType>));
} while (connection.isNothing());
}
return connection.extract();
}
// Returns true if a given nsIFile exists and is a directory. Returns false if
// it doesn't exist. Returns an error if it exists, but is not a directory, or
// any other error occurs.
Result<bool, nsresult> ExistsAsDirectory(nsIFile& aDirectory) {
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(aDirectory, Exists));
if (exists) {
QM_TRY_INSPECT(const bool& isDirectory,
MOZ_TO_RESULT_INVOKE_MEMBER(aDirectory, IsDirectory));
QM_TRY(OkIf(isDirectory), Err(NS_ERROR_FAILURE));
}
return exists;
}
constexpr nsresult mapNoDeviceSpaceError(nsresult aRv) {
if (aRv == NS_ERROR_FILE_NO_DEVICE_SPACE) {
// mozstorage translates SQLITE_FULL to
// NS_ERROR_FILE_NO_DEVICE_SPACE, which we know better as
// NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR.
return NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR;
}
return aRv;
}
Result<MovingNotNull<nsCOMPtr<mozIStorageConnection>>, nsresult>
CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory,
const nsAString& aName, const nsACString& aOrigin,
const int64_t aDirectoryLockId,
const uint32_t aTelemetryId,
const Maybe<CipherKey>& aMaybeKey) {
AssertIsOnIOThread();
MOZ_ASSERT(aDirectoryLockId >= -1);
AUTO_PROFILER_LABEL("CreateStorageConnection", DOM);
QM_TRY_INSPECT(const auto& dbFileUrl,
GetDatabaseFileURL(aDBFile, aDirectoryLockId, aMaybeKey));
QM_TRY_INSPECT(const auto& storageService,
MOZ_TO_RESULT_GET_TYPED(nsCOMPtr<mozIStorageService>,
MOZ_SELECT_OVERLOAD(do_GetService),
MOZ_STORAGE_SERVICE_CONTRACTID));
QM_TRY_UNWRAP(
auto connection,
QM_OR_ELSE_WARN_IF(
// Expression.
OpenDatabaseAndHandleBusy(*storageService, *dbFileUrl, aTelemetryId)
.map([](auto connection) -> nsCOMPtr<mozIStorageConnection> {
return std::move(connection).unwrapBasePtr();
}),
// Predicate.
([&aName](nsresult aValue) {
// If we're just opening the database during origin initialization,
// then we don't want to erase any files. The failure here will fail
// origin initialization too.
return IsDatabaseCorruptionError(aValue) && !aName.IsVoid();
}),
// Fallback.
ErrToDefaultOk<nsCOMPtr<mozIStorageConnection>>));
if (!connection) {
// XXX Shouldn't we also update quota usage?
// Nuke the database file.
QM_TRY(MOZ_TO_RESULT(aDBFile.Remove(false)));
QM_TRY_INSPECT(const bool& existsAsDirectory,
ExistsAsDirectory(aFMDirectory));
if (existsAsDirectory) {
QM_TRY(MOZ_TO_RESULT(aFMDirectory.Remove(true)));
}
QM_TRY_UNWRAP(connection, OpenDatabaseAndHandleBusy(
*storageService, *dbFileUrl, aTelemetryId));
}
QM_TRY(MOZ_TO_RESULT(SetDefaultPragmas(*connection)));
QM_TRY(MOZ_TO_RESULT(connection->EnableModule("filesystem"_ns)));
// Check to make sure that the database schema is correct.
QM_TRY_INSPECT(const int32_t& schemaVersion,
MOZ_TO_RESULT_INVOKE_MEMBER(connection, GetSchemaVersion));
// Unknown schema will fail origin initialization too.
QM_TRY(OkIf(schemaVersion || !aName.IsVoid()),
Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR), [](const auto&) {
IDB_WARNING("Unable to open IndexedDB database, schema is not set!");
});
QM_TRY(
OkIf(schemaVersion <= kSQLiteSchemaVersion),
Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR), [](const auto&) {
IDB_WARNING("Unable to open IndexedDB database, schema is too high!");
});
bool journalModeSet = false;
if (schemaVersion != kSQLiteSchemaVersion) {
const bool newDatabase = !schemaVersion;
if (newDatabase) {
// Set the page size first.
const auto sqlitePageSizeOverride =
aMaybeKey ? 8192 : kSQLitePageSizeOverride;
if (sqlitePageSizeOverride) {
QM_TRY(MOZ_TO_RESULT(connection->ExecuteSimpleSQL(nsPrintfCString(
"PRAGMA page_size = %" PRIu32 ";", sqlitePageSizeOverride))));
}
// We have to set the auto_vacuum mode before opening a transaction.
QM_TRY((MOZ_TO_RESULT_INVOKE_MEMBER(
connection, ExecuteSimpleSQL,
#ifdef IDB_MOBILE
// Turn on full auto_vacuum mode to reclaim disk space on
// mobile devices (at the cost of some COMMIT speed).
"PRAGMA auto_vacuum = FULL;"_ns
#else
// Turn on incremental auto_vacuum mode on desktop builds.
"PRAGMA auto_vacuum = INCREMENTAL;"_ns
#endif
)
.mapErr(mapNoDeviceSpaceError)));
QM_TRY(MOZ_TO_RESULT(SetJournalMode(*connection)));
journalModeSet = true;
} else {
#ifdef DEBUG
// Disable foreign key support while upgrading. This has to be done before
// starting a transaction.
MOZ_ALWAYS_SUCCEEDS(
connection->ExecuteSimpleSQL("PRAGMA foreign_keys = OFF;"_ns));
#endif
}
bool vacuumNeeded = false;
mozStorageTransaction transaction(
connection.get(), false, mozIStorageConnection::TRANSACTION_IMMEDIATE);
QM_TRY(MOZ_TO_RESULT(transaction.Start()));
if (newDatabase) {
QM_TRY(MOZ_TO_RESULT(CreateTables(*connection)));
#ifdef DEBUG
{
QM_TRY_INSPECT(
const int32_t& schemaVersion,
MOZ_TO_RESULT_INVOKE_MEMBER(connection, GetSchemaVersion),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(schemaVersion == kSQLiteSchemaVersion);
}
#endif
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(
const auto& stmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>, connection, CreateStatement,
"INSERT INTO database (name, origin) "
"VALUES (:name, :origin)"_ns));
QM_TRY(MOZ_TO_RESULT(stmt->BindStringByIndex(0, aName)));
QM_TRY(MOZ_TO_RESULT(stmt->BindUTF8StringByIndex(1, aOrigin)));
QM_TRY(MOZ_TO_RESULT(stmt->Execute()));
} else {
QM_TRY_UNWRAP(vacuumNeeded, MaybeUpgradeSchema(*connection, schemaVersion,
aFMDirectory, aOrigin));
}
QM_TRY(MOZ_TO_RESULT_INVOKE_MEMBER(transaction, Commit)
.mapErr(mapNoDeviceSpaceError));
#ifdef DEBUG
if (!newDatabase) {
// Re-enable foreign key support after doing a foreign key check.
QM_TRY_INSPECT(const bool& foreignKeyError,
CreateAndExecuteSingleStepStatement<
SingleStepResult::ReturnNullIfNoResult>(
*connection, "PRAGMA foreign_key_check;"_ns),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(!foreignKeyError, "Database has inconsisistent foreign keys!");
MOZ_ALWAYS_SUCCEEDS(
connection->ExecuteSimpleSQL("PRAGMA foreign_keys = OFF;"_ns));
}
#endif
if (kSQLitePageSizeOverride && !newDatabase) {
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement(
*connection, "PRAGMA page_size;"_ns));
QM_TRY_INSPECT(const int32_t& pageSize,
MOZ_TO_RESULT_INVOKE_MEMBER(*stmt, GetInt32, 0));
MOZ_ASSERT(pageSize >= 512 && pageSize <= 65536);
if (kSQLitePageSizeOverride != uint32_t(pageSize)) {
// We must not be in WAL journal mode to change the page size.
QM_TRY(MOZ_TO_RESULT(
connection->ExecuteSimpleSQL("PRAGMA journal_mode = DELETE;"_ns)));
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement(
*connection, "PRAGMA journal_mode;"_ns));
QM_TRY_INSPECT(const auto& journalMode,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsCString, *stmt,
GetUTF8String, 0));
if (journalMode.EqualsLiteral("delete")) {
// Successfully set to rollback journal mode so changing the page size
// is possible with a VACUUM.
QM_TRY(MOZ_TO_RESULT(connection->ExecuteSimpleSQL(nsPrintfCString(
"PRAGMA page_size = %" PRIu32 ";", kSQLitePageSizeOverride))));
// We will need to VACUUM in order to change the page size.
vacuumNeeded = true;
} else {
NS_WARNING(
"Failed to set journal_mode for database, unable to "
"change the page size!");
}
}
}
if (vacuumNeeded) {
QM_TRY(MOZ_TO_RESULT(connection->ExecuteSimpleSQL("VACUUM;"_ns)));
}
if (newDatabase || vacuumNeeded) {
if (journalModeSet) {
// Make sure we checkpoint to get an accurate file size.
QM_TRY(MOZ_TO_RESULT(
connection->ExecuteSimpleSQL("PRAGMA wal_checkpoint(FULL);"_ns)));
}
QM_TRY_INSPECT(const int64_t& fileSize,
MOZ_TO_RESULT_INVOKE_MEMBER(aDBFile, GetFileSize));
MOZ_ASSERT(fileSize > 0);
PRTime vacuumTime = PR_Now();
MOZ_ASSERT(vacuumTime);
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(
const auto& vacuumTimeStmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsCOMPtr<mozIStorageStatement>,
connection, CreateStatement,
"UPDATE database "
"SET last_vacuum_time = :time"
", last_vacuum_size = :size;"_ns));
QM_TRY(MOZ_TO_RESULT(vacuumTimeStmt->BindInt64ByIndex(0, vacuumTime)));
QM_TRY(MOZ_TO_RESULT(vacuumTimeStmt->BindInt64ByIndex(1, fileSize)));
QM_TRY(MOZ_TO_RESULT(vacuumTimeStmt->Execute()));
}
}
if (!journalModeSet) {
QM_TRY(MOZ_TO_RESULT(SetJournalMode(*connection)));
}
return WrapMovingNotNullUnchecked(std::move(connection));
}
nsCOMPtr<nsIFile> GetFileForPath(const nsAString& aPath) {
MOZ_ASSERT(!aPath.IsEmpty());
QM_TRY_RETURN(QM_NewLocalFile(aPath), nullptr);
}
Result<MovingNotNull<nsCOMPtr<mozIStorageConnection>>, nsresult>
GetStorageConnection(nsIFile& aDatabaseFile, const int64_t aDirectoryLockId,
const uint32_t aTelemetryId,
const Maybe<CipherKey>& aMaybeKey) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aDirectoryLockId >= 0);
AUTO_PROFILER_LABEL("GetStorageConnection", DOM);
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(aDatabaseFile, Exists));
QM_TRY(OkIf(exists), Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR),
IDB_REPORT_INTERNAL_ERR_LAMBDA);
QM_TRY_INSPECT(
const auto& dbFileUrl,
GetDatabaseFileURL(aDatabaseFile, aDirectoryLockId, aMaybeKey));
QM_TRY_INSPECT(const auto& storageService,
MOZ_TO_RESULT_GET_TYPED(nsCOMPtr<mozIStorageService>,
MOZ_SELECT_OVERLOAD(do_GetService),
MOZ_STORAGE_SERVICE_CONTRACTID));
QM_TRY_UNWRAP(
nsCOMPtr<mozIStorageConnection> connection,
OpenDatabaseAndHandleBusy(*storageService, *dbFileUrl, aTelemetryId));
QM_TRY(MOZ_TO_RESULT(SetDefaultPragmas(*connection)));
QM_TRY(MOZ_TO_RESULT(SetJournalMode(*connection)));
return WrapMovingNotNullUnchecked(std::move(connection));
}
Result<MovingNotNull<nsCOMPtr<mozIStorageConnection>>, nsresult>
GetStorageConnection(const nsAString& aDatabaseFilePath,
const int64_t aDirectoryLockId,
const uint32_t aTelemetryId,
const Maybe<CipherKey>& aMaybeKey) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(!aDatabaseFilePath.IsEmpty());
MOZ_ASSERT(StringEndsWith(aDatabaseFilePath, kSQLiteSuffix));
MOZ_ASSERT(aDirectoryLockId >= 0);
nsCOMPtr<nsIFile> dbFile = GetFileForPath(aDatabaseFilePath);
QM_TRY(OkIf(dbFile), Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR),
IDB_REPORT_INTERNAL_ERR_LAMBDA);
return GetStorageConnection(*dbFile, aDirectoryLockId, aTelemetryId,
aMaybeKey);
}
/*******************************************************************************
* ConnectionPool declarations
******************************************************************************/
class DatabaseConnection final : public CachingDatabaseConnection {
friend class ConnectionPool;
enum class CheckpointMode { Full, Restart, Truncate };
public:
class AutoSavepoint;
class UpdateRefcountFunction;
private:
InitializedOnce<const NotNull<SafeRefPtr<DatabaseFileManager>>> mFileManager;
RefPtr<UpdateRefcountFunction> mUpdateRefcountFunction;
RefPtr<QuotaObject> mQuotaObject;
RefPtr<QuotaObject> mJournalQuotaObject;
IDBTransaction::Durability mLastDurability;
bool mInReadTransaction;
bool mInWriteTransaction;
#ifdef DEBUG
uint32_t mDEBUGSavepointCount;
#endif
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(DatabaseConnection)
UpdateRefcountFunction* GetUpdateRefcountFunction() const {
AssertIsOnConnectionThread();
return mUpdateRefcountFunction;
}
nsresult BeginWriteTransaction(const IDBTransaction::Durability aDurability);
nsresult CommitWriteTransaction();
void RollbackWriteTransaction();
void FinishWriteTransaction();
nsresult StartSavepoint();
nsresult ReleaseSavepoint();
nsresult RollbackSavepoint();
nsresult Checkpoint() {
AssertIsOnConnectionThread();
return CheckpointInternal(CheckpointMode::Full);
}
void DoIdleProcessing(bool aNeedsCheckpoint,
const Atomic<bool>& aInterrupted);
void Close();
nsresult DisableQuotaChecks();
void EnableQuotaChecks();
private:
DatabaseConnection(
MovingNotNull<nsCOMPtr<mozIStorageConnection>> aStorageConnection,
MovingNotNull<SafeRefPtr<DatabaseFileManager>> aFileManager);
~DatabaseConnection();
nsresult Init();
nsresult CheckpointInternal(CheckpointMode aMode);
Result<uint32_t, nsresult> GetFreelistCount(
CachedStatement& aCachedStatement);
/**
* On success, returns whether some pages were freed.
*/
Result<bool, nsresult> ReclaimFreePagesWhileIdle(
CachedStatement& aFreelistStatement, CachedStatement& aRollbackStatement,
uint32_t aFreelistCount, bool aNeedsCheckpoint,
const Atomic<bool>& aInterrupted);
Result<int64_t, nsresult> GetFileSize(const nsAString& aPath);
};
class MOZ_STACK_CLASS DatabaseConnection::AutoSavepoint final {
DatabaseConnection* mConnection;
#ifdef DEBUG
const TransactionBase* mDEBUGTransaction;
#endif
public:
AutoSavepoint();
~AutoSavepoint();
nsresult Start(const TransactionBase& aTransaction);
nsresult Commit();
};
class DatabaseConnection::UpdateRefcountFunction final
: public mozIStorageFunction {
class FileInfoEntry;
enum class UpdateType { Increment, Decrement };
DatabaseConnection* const mConnection;
DatabaseFileManager& mFileManager;
nsClassHashtable<nsUint64HashKey, FileInfoEntry> mFileInfoEntries;
nsTHashMap<nsUint64HashKey, NotNull<FileInfoEntry*>> mSavepointEntriesIndex;
nsTArray<int64_t> mJournalsToCreateBeforeCommit;
nsTArray<int64_t> mJournalsToRemoveAfterCommit;
nsTArray<int64_t> mJournalsToRemoveAfterAbort;
bool mInSavepoint;
public:
NS_DECL_ISUPPORTS_ONEVENTTARGET
NS_DECL_MOZISTORAGEFUNCTION
UpdateRefcountFunction(DatabaseConnection* aConnection,
DatabaseFileManager& aFileManager);
nsresult WillCommit();
void DidCommit();
void DidAbort();
void StartSavepoint();
void ReleaseSavepoint();
void RollbackSavepoint();
void Reset();
private:
~UpdateRefcountFunction() = default;
nsresult ProcessValue(mozIStorageValueArray* aValues, int32_t aIndex,
UpdateType aUpdateType);
nsresult CreateJournals();
nsresult RemoveJournals(const nsTArray<int64_t>& aJournals);
};
class DatabaseConnection::UpdateRefcountFunction::FileInfoEntry final {
SafeRefPtr<DatabaseFileInfo> mFileInfo;
int32_t mDelta;
int32_t mSavepointDelta;
public:
explicit FileInfoEntry(SafeRefPtr<DatabaseFileInfo> aFileInfo)
: mFileInfo(std::move(aFileInfo)), mDelta(0), mSavepointDelta(0) {
MOZ_COUNT_CTOR(DatabaseConnection::UpdateRefcountFunction::FileInfoEntry);
}
void IncDeltas(bool aUpdateSavepointDelta) {
++mDelta;
if (aUpdateSavepointDelta) {
++mSavepointDelta;
}
}
void DecDeltas(bool aUpdateSavepointDelta) {
--mDelta;
if (aUpdateSavepointDelta) {
--mSavepointDelta;
}
}
void DecBySavepointDelta() { mDelta -= mSavepointDelta; }
SafeRefPtr<DatabaseFileInfo> ReleaseFileInfo() {
return std::move(mFileInfo);
}
void MaybeUpdateDBRefs() {
if (mDelta) {
mFileInfo->UpdateDBRefs(mDelta);
}
}
int32_t Delta() const { return mDelta; }
int32_t SavepointDelta() const { return mSavepointDelta; }
~FileInfoEntry() {
MOZ_COUNT_DTOR(DatabaseConnection::UpdateRefcountFunction::FileInfoEntry);
}
};
class ConnectionPool final {
public:
class FinishCallback;
private:
class ConnectionRunnable;
class CloseConnectionRunnable;
struct DatabaseInfo;
struct DatabaseCompleteCallback;
class FinishCallbackWrapper;
class IdleConnectionRunnable;
#ifdef DEBUG
class TransactionRunnable;
#endif
class TransactionInfo;
struct TransactionInfoPair;
struct IdleResource {
TimeStamp mIdleTime;
IdleResource(const IdleResource& aOther) = delete;
IdleResource(IdleResource&& aOther) noexcept
: IdleResource(aOther.mIdleTime) {}
IdleResource& operator=(const IdleResource& aOther) = delete;
IdleResource& operator=(IdleResource&& aOther) = delete;
protected:
explicit IdleResource(const TimeStamp& aIdleTime);
~IdleResource();
};
struct IdleDatabaseInfo final : public IdleResource {
InitializedOnce<const NotNull<DatabaseInfo*>> mDatabaseInfo;
public:
explicit IdleDatabaseInfo(DatabaseInfo& aDatabaseInfo);
IdleDatabaseInfo(const IdleDatabaseInfo& aOther) = delete;
IdleDatabaseInfo(IdleDatabaseInfo&& aOther) noexcept
: IdleResource(std::move(aOther)),
mDatabaseInfo{std::move(aOther.mDatabaseInfo)} {
MOZ_ASSERT(mDatabaseInfo);
MOZ_COUNT_CTOR(ConnectionPool::IdleDatabaseInfo);
}
IdleDatabaseInfo& operator=(const IdleDatabaseInfo& aOther) = delete;
IdleDatabaseInfo& operator=(IdleDatabaseInfo&& aOther) = delete;
~IdleDatabaseInfo();
bool operator==(const IdleDatabaseInfo& aOther) const {
return *mDatabaseInfo == *aOther.mDatabaseInfo;
}
bool operator==(const DatabaseInfo* aDatabaseInfo) const {
return *mDatabaseInfo == aDatabaseInfo;
}
bool operator<(const IdleDatabaseInfo& aOther) const {
return mIdleTime < aOther.mIdleTime;
}
};
struct PerformingIdleMaintenanceDatabaseInfo {
const NotNull<DatabaseInfo*> mDatabaseInfo;
RefPtr<IdleConnectionRunnable> mIdleConnectionRunnable;
PerformingIdleMaintenanceDatabaseInfo(
DatabaseInfo& aDatabaseInfo,
RefPtr<IdleConnectionRunnable> aIdleConnectionRunnable);
PerformingIdleMaintenanceDatabaseInfo(
const PerformingIdleMaintenanceDatabaseInfo& aOther) = delete;
PerformingIdleMaintenanceDatabaseInfo(
PerformingIdleMaintenanceDatabaseInfo&& aOther) noexcept
: mDatabaseInfo{aOther.mDatabaseInfo},
mIdleConnectionRunnable{std::move(aOther.mIdleConnectionRunnable)} {
MOZ_COUNT_CTOR(ConnectionPool::PerformingIdleMaintenanceDatabaseInfo);
}
PerformingIdleMaintenanceDatabaseInfo& operator=(
const PerformingIdleMaintenanceDatabaseInfo& aOther) = delete;
PerformingIdleMaintenanceDatabaseInfo& operator=(
PerformingIdleMaintenanceDatabaseInfo&& aOther) = delete;
~PerformingIdleMaintenanceDatabaseInfo();
bool operator==(const DatabaseInfo* aDatabaseInfo) const {
return mDatabaseInfo == aDatabaseInfo;
}
};
// This mutex guards mDatabases, see below.
Mutex mDatabasesMutex MOZ_UNANNOTATED;
nsCOMPtr<nsIThreadPool> mIOTarget;
nsTArray<IdleDatabaseInfo> mIdleDatabases;
nsTArray<PerformingIdleMaintenanceDatabaseInfo>
mDatabasesPerformingIdleMaintenance;
nsCOMPtr<nsITimer> mIdleTimer;
TimeStamp mTargetIdleTime;
// Only modifed on the owning thread, but read on multiple threads. Therefore
// all modifications and all reads off the owning thread must be protected by
// mDatabasesMutex.
nsClassHashtable<nsCStringHashKey, DatabaseInfo> mDatabases;
nsClassHashtable<nsUint64HashKey, TransactionInfo> mTransactions;
nsTArray<NotNull<TransactionInfo*>> mQueuedTransactions;
nsTArray<UniquePtr<DatabaseCompleteCallback>> mCompleteCallbacks;
uint64_t mNextTransactionId;
FlippedOnce<false> mShutdownRequested;
FlippedOnce<false> mShutdownComplete;
public:
ConnectionPool();
void AssertIsOnOwningThread() const {
NS_ASSERT_OWNINGTHREAD(ConnectionPool);
}
Result<RefPtr<DatabaseConnection>, nsresult> GetOrCreateConnection(
const Database& aDatabase);
uint64_t Start(const nsID& aBackgroundChildLoggingId,
const nsACString& aDatabaseId, int64_t aLoggingSerialNumber,
const nsTArray<nsString>& aObjectStoreNames,
bool aIsWriteTransaction,
TransactionDatabaseOperationBase* aTransactionOp);
/**
* Starts a new operation associated with the given transaction.
*
* This method initiates an operation by:
* 1. Dispatching the provided runnable to the task queue created on top of
* the I/O thread pool if the transaction is currently running.
* 2. Queuing the runnable for later execution if the transaction is not yet
* running.
*
* It is mandatory for all operations to call StartOp to ensure proper
* handling and sequencing within the transaction context.
*
* Note:
* - For more complex operations that involve work on other threads or require
* communication with content processes, StartOp should not be called again
* to dispatch to the task queue, as this could disrupt proper queuing and
* execution.
*/
void StartOp(uint64_t aTransactionId, nsCOMPtr<nsIRunnable> aRunnable);
/**
* Marks the completion of an operation associated with the given transaction.
*
* This method signals that the current operation has finished, allowing the
* next queued operation (if any) for the transaction to start.
*/
void FinishOp(uint64_t aTransactionId);
void Finish(uint64_t aTransactionId, FinishCallback* aCallback);
void CloseDatabaseWhenIdle(const nsACString& aDatabaseId) {
Unused << CloseDatabaseWhenIdleInternal(aDatabaseId);
}
void WaitForDatabaseToComplete(const nsCString& aDatabaseId,
nsIRunnable* aCallback);
void Shutdown();
NS_INLINE_DECL_REFCOUNTING(ConnectionPool)
private:
~ConnectionPool();
static void IdleTimerCallback(nsITimer* aTimer, void* aClosure);
static uint32_t SerialNumber() { return ++sSerialNumber; }
static uint32_t sSerialNumber;
void Cleanup();
void AdjustIdleTimer();
void CancelIdleTimer();
void CloseIdleDatabases();
bool ScheduleTransaction(TransactionInfo& aTransactionInfo,
bool aFromQueuedTransactions);
void NoteFinishedTransaction(uint64_t aTransactionId);
void ScheduleQueuedTransactions();
void NoteIdleDatabase(DatabaseInfo& aDatabaseInfo);
void NoteClosedDatabase(DatabaseInfo& aDatabaseInfo);
bool MaybeFireCallback(DatabaseCompleteCallback* aCallback);
void PerformIdleDatabaseMaintenance(DatabaseInfo& aDatabaseInfo);
void CloseDatabase(DatabaseInfo& aDatabaseInfo) const;
bool CloseDatabaseWhenIdleInternal(const nsACString& aDatabaseId);
};
class ConnectionPool::ConnectionRunnable : public Runnable {
protected:
DatabaseInfo& mDatabaseInfo;
nsCOMPtr<nsIEventTarget> mOwningEventTarget;
explicit ConnectionRunnable(DatabaseInfo& aDatabaseInfo);
~ConnectionRunnable() override = default;
};
class ConnectionPool::IdleConnectionRunnable final : public ConnectionRunnable {
const bool mNeedsCheckpoint;
Atomic<bool> mInterrupted;
public:
IdleConnectionRunnable(DatabaseInfo& aDatabaseInfo, bool aNeedsCheckpoint)
: ConnectionRunnable(aDatabaseInfo), mNeedsCheckpoint(aNeedsCheckpoint) {}
NS_INLINE_DECL_REFCOUNTING_INHERITED(IdleConnectionRunnable,
ConnectionRunnable)
void Interrupt() { mInterrupted = true; }
private:
~IdleConnectionRunnable() override = default;
NS_DECL_NSIRUNNABLE
};
class ConnectionPool::CloseConnectionRunnable final
: public ConnectionRunnable {
public:
explicit CloseConnectionRunnable(DatabaseInfo& aDatabaseInfo)
: ConnectionRunnable(aDatabaseInfo) {}
NS_INLINE_DECL_REFCOUNTING_INHERITED(CloseConnectionRunnable,
ConnectionRunnable)
private:
~CloseConnectionRunnable() override = default;
NS_DECL_NSIRUNNABLE
};
struct ConnectionPool::DatabaseInfo final {
friend class mozilla::DefaultDelete<DatabaseInfo>;
RefPtr<ConnectionPool> mConnectionPool;
const nsCString mDatabaseId;
RefPtr<DatabaseConnection> mConnection;
nsClassHashtable<nsStringHashKey, TransactionInfoPair> mBlockingTransactions;
nsTArray<NotNull<TransactionInfo*>> mTransactionsScheduledDuringClose;
nsTArray<NotNull<TransactionInfo*>> mScheduledWriteTransactions;
Maybe<TransactionInfo&> mRunningWriteTransaction;
RefPtr<TaskQueue> mEventTarget;
uint32_t mReadTransactionCount;
uint32_t mWriteTransactionCount;
bool mNeedsCheckpoint;
bool mIdle;
FlippedOnce<false> mCloseOnIdle;
bool mClosing;
#ifdef DEBUG
nsISerialEventTarget* mDEBUGConnectionEventTarget;
#endif
DatabaseInfo(ConnectionPool* aConnectionPool, const nsACString& aDatabaseId);
void AssertIsOnConnectionThread() const {
MOZ_ASSERT(mDEBUGConnectionEventTarget);
MOZ_ASSERT(GetCurrentSerialEventTarget() == mDEBUGConnectionEventTarget);
}
uint64_t TotalTransactionCount() const {
return mReadTransactionCount + mWriteTransactionCount;
}
nsresult Dispatch(already_AddRefed<nsIRunnable> aRunnable);
private:
~DatabaseInfo();
DatabaseInfo(const DatabaseInfo&) = delete;
DatabaseInfo& operator=(const DatabaseInfo&) = delete;
};
struct ConnectionPool::DatabaseCompleteCallback final {
friend class DefaultDelete<DatabaseCompleteCallback>;
nsCString mDatabaseId;
nsCOMPtr<nsIRunnable> mCallback;
DatabaseCompleteCallback(const nsCString& aDatabaseIds,
nsIRunnable* aCallback);
private:
~DatabaseCompleteCallback();
};
class NS_NO_VTABLE ConnectionPool::FinishCallback : public nsIRunnable {
public:
// Called on the owning thread before any additional transactions are
// unblocked.
virtual void TransactionFinishedBeforeUnblock() = 0;
// Called on the owning thread after additional transactions may have been
// unblocked.
virtual void TransactionFinishedAfterUnblock() = 0;
protected:
FinishCallback() = default;
virtual ~FinishCallback() = default;
};
class ConnectionPool::FinishCallbackWrapper final : public Runnable {
RefPtr<ConnectionPool> mConnectionPool;
RefPtr<FinishCallback> mCallback;
nsCOMPtr<nsIEventTarget> mOwningEventTarget;
uint64_t mTransactionId;
bool mHasRunOnce;
public:
FinishCallbackWrapper(ConnectionPool* aConnectionPool,
uint64_t aTransactionId, FinishCallback* aCallback);
NS_INLINE_DECL_REFCOUNTING_INHERITED(FinishCallbackWrapper, Runnable)
private:
~FinishCallbackWrapper() override;
NS_DECL_NSIRUNNABLE
};
#ifdef DEBUG
class ConnectionPool::TransactionRunnable final : public Runnable {
public:
explicit TransactionRunnable(nsCOMPtr<nsIRunnable> aRunnable);
private:
NS_DECL_NSIRUNNABLE
nsCOMPtr<nsIRunnable> mRunnable;
};
#endif
class ConnectionPool::TransactionInfo final {
friend class mozilla::DefaultDelete<TransactionInfo>;
nsTHashSet<TransactionInfo*> mBlocking;
nsTArray<NotNull<TransactionInfo*>> mBlockingOrdered;
public:
DatabaseInfo& mDatabaseInfo;
const nsID mBackgroundChildLoggingId;
const nsCString mDatabaseId;
const uint64_t mTransactionId;
const int64_t mLoggingSerialNumber;
const nsTArray<nsString> mObjectStoreNames;
nsTHashSet<TransactionInfo*> mBlockedOn;
mozilla::Queue<nsCOMPtr<nsIRunnable>, 16> mQueuedOps;
const bool mIsWriteTransaction;
bool mRunning;
bool mRunningOp;
#ifdef DEBUG
FlippedOnce<false> mFinished;
#endif
TransactionInfo(DatabaseInfo& aDatabaseInfo,
const nsID& aBackgroundChildLoggingId,
const nsACString& aDatabaseId, uint64_t aTransactionId,
int64_t aLoggingSerialNumber,
const nsTArray<nsString>& aObjectStoreNames,
bool aIsWriteTransaction,
TransactionDatabaseOperationBase* aTransactionOp);
void AddBlockingTransaction(TransactionInfo& aTransactionInfo);
void RemoveBlockingTransactions();
void SetRunning();
void StartOp(nsCOMPtr<nsIRunnable> aRunnable);
void FinishOp();
private:
~TransactionInfo();
void MaybeUnblock(TransactionInfo& aTransactionInfo);
};
struct ConnectionPool::TransactionInfoPair final {
// Multiple reading transactions can block future writes.
nsTArray<NotNull<TransactionInfo*>> mLastBlockingWrites;
// But only a single writing transaction can block future reads.
Maybe<TransactionInfo&> mLastBlockingReads;
#if defined(DEBUG) || defined(NS_BUILD_REFCNT_LOGGING)
TransactionInfoPair();
~TransactionInfoPair();
#endif
};
/*******************************************************************************
* Actor class declarations
******************************************************************************/
template <IDBCursorType CursorType>
class CommonOpenOpHelper;
template <IDBCursorType CursorType>
class IndexOpenOpHelper;
template <IDBCursorType CursorType>
class ObjectStoreOpenOpHelper;
template <IDBCursorType CursorType>
class OpenOpHelper;
class DatabaseOperationBase : public Runnable,
public mozIStorageProgressHandler {
template <IDBCursorType CursorType>
friend class OpenOpHelper;
protected:
class AutoSetProgressHandler;
using UniqueIndexTable = nsTHashMap<nsUint64HashKey, bool>;
const nsCOMPtr<nsIEventTarget> mOwningEventTarget;
const nsID mBackgroundChildLoggingId;
const uint64_t mLoggingSerialNumber;
private:
nsresult mResultCode = NS_OK;
Atomic<bool> mOperationMayProceed;
FlippedOnce<false> mActorDestroyed;
public:
NS_DECL_ISUPPORTS_INHERITED
bool IsOnOwningThread() const {
MOZ_ASSERT(mOwningEventTarget);
bool current;
return NS_SUCCEEDED(mOwningEventTarget->IsOnCurrentThread(¤t)) &&
current;
}
void AssertIsOnOwningThread() const {
MOZ_ASSERT(IsOnBackgroundThread());
MOZ_ASSERT(IsOnOwningThread());
}
void NoteActorDestroyed() {
AssertIsOnOwningThread();
mActorDestroyed.EnsureFlipped();
mOperationMayProceed = false;
}
bool IsActorDestroyed() const {
AssertIsOnOwningThread();
return mActorDestroyed;
}
// May be called on any thread, but you should call IsActorDestroyed() if
// you know you're on the background thread because it is slightly faster.
bool OperationMayProceed() const { return mOperationMayProceed; }
const nsID& BackgroundChildLoggingId() const {
return mBackgroundChildLoggingId;
}
uint64_t LoggingSerialNumber() const { return mLoggingSerialNumber; }
nsresult ResultCode() const { return mResultCode; }
void SetFailureCode(nsresult aFailureCode) {
MOZ_ASSERT(NS_SUCCEEDED(mResultCode));
OverrideFailureCode(aFailureCode);
}
void SetFailureCodeIfUnset(nsresult aFailureCode) {
if (NS_SUCCEEDED(mResultCode)) {
OverrideFailureCode(aFailureCode);
}
}
bool HasFailed() const { return NS_FAILED(mResultCode); }
protected:
DatabaseOperationBase(const nsID& aBackgroundChildLoggingId,
uint64_t aLoggingSerialNumber)
: Runnable("dom::indexedDB::DatabaseOperationBase"),
mOwningEventTarget(GetCurrentSerialEventTarget()),
mBackgroundChildLoggingId(aBackgroundChildLoggingId),
mLoggingSerialNumber(aLoggingSerialNumber),
mOperationMayProceed(true) {
AssertIsOnOwningThread();
}
~DatabaseOperationBase() override { MOZ_ASSERT(mActorDestroyed); }
void OverrideFailureCode(nsresult aFailureCode) {
MOZ_ASSERT(NS_FAILED(aFailureCode));
mResultCode = aFailureCode;
}
static nsAutoCString MaybeGetBindingClauseForKeyRange(
const Maybe<SerializedKeyRange>& aOptionalKeyRange,
const nsACString& aKeyColumnName);
static nsAutoCString GetBindingClauseForKeyRange(
const SerializedKeyRange& aKeyRange, const nsACString& aKeyColumnName);
static uint64_t ReinterpretDoubleAsUInt64(double aDouble);
static nsresult BindKeyRangeToStatement(const SerializedKeyRange& aKeyRange,
mozIStorageStatement* aStatement);
static nsresult BindKeyRangeToStatement(const SerializedKeyRange& aKeyRange,
mozIStorageStatement* aStatement,
const nsCString& aLocale);
static Result<IndexDataValuesAutoArray, nsresult>
IndexDataValuesFromUpdateInfos(const nsTArray<IndexUpdateInfo>& aUpdateInfos,
const UniqueIndexTable& aUniqueIndexTable);
static nsresult InsertIndexTableRows(
DatabaseConnection* aConnection, IndexOrObjectStoreId aObjectStoreId,
const Key& aObjectStoreKey, const nsTArray<IndexDataValue>& aIndexValues);
static nsresult DeleteIndexDataTableRows(
DatabaseConnection* aConnection, const Key& aObjectStoreKey,
const nsTArray<IndexDataValue>& aIndexValues);
static nsresult DeleteObjectStoreDataTableRowsWithIndexes(
DatabaseConnection* aConnection, IndexOrObjectStoreId aObjectStoreId,
const Maybe<SerializedKeyRange>& aKeyRange);
static nsresult UpdateIndexValues(
DatabaseConnection* aConnection, IndexOrObjectStoreId aObjectStoreId,
const Key& aObjectStoreKey, const nsTArray<IndexDataValue>& aIndexValues);
static Result<bool, nsresult> ObjectStoreHasIndexes(
DatabaseConnection& aConnection, IndexOrObjectStoreId aObjectStoreId);
private:
template <typename KeyTransformation>
static nsresult MaybeBindKeyToStatement(
const Key& aKey, mozIStorageStatement* aStatement,
const nsACString& aParameterName,
const KeyTransformation& aKeyTransformation);
template <typename KeyTransformation>
static nsresult BindTransformedKeyRangeToStatement(
const SerializedKeyRange& aKeyRange, mozIStorageStatement* aStatement,
const KeyTransformation& aKeyTransformation);
// Not to be overridden by subclasses.
NS_DECL_MOZISTORAGEPROGRESSHANDLER
};
class MOZ_STACK_CLASS DatabaseOperationBase::AutoSetProgressHandler final {
Maybe<mozIStorageConnection&> mConnection;
#ifdef DEBUG
DatabaseOperationBase* mDEBUGDatabaseOp;
#endif
public:
AutoSetProgressHandler();
~AutoSetProgressHandler();
nsresult Register(mozIStorageConnection& aConnection,
DatabaseOperationBase* aDatabaseOp);
void Unregister();
};
class TransactionDatabaseOperationBase : public DatabaseOperationBase {
enum class InternalState {
Initial,
DatabaseWork,
SendingPreprocess,
WaitingForContinue,
SendingResults,
Completed
};
InitializedOnce<const NotNull<SafeRefPtr<TransactionBase>>> mTransaction;
// Unique request id within the context of the transaction, allocated by the
// transaction in the content process starting from 0. Values less than 0 are
// impossible and forbidden. Used to support the explicit commit() request.
const int64_t mRequestId;
InternalState mInternalState = InternalState::Initial;
bool mWaitingForContinue = false;
const bool mTransactionIsAborted;
protected:
const int64_t mTransactionLoggingSerialNumber;
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
protected:
// A check only enables when the diagnostic assert turns on. It assumes the
// mUpdateRefcountFunction is a nullptr because the previous
// StartTransactionOp failed on the connection thread and the next write
// operation (e.g. ObjectstoreAddOrPutRequestOp) doesn't have enough time to
// catch up the failure information.
bool mAssumingPreviousOperationFail = false;
#endif
public:
void AssertIsOnConnectionThread() const
#ifdef DEBUG
;
#else
{
}
#endif
uint64_t StartOnConnectionPool(const nsID& aBackgroundChildLoggingId,
const nsACString& aDatabaseId,
int64_t aLoggingSerialNumber,
const nsTArray<nsString>& aObjectStoreNames,
bool aIsWriteTransaction);
void DispatchToConnectionPool();
TransactionBase& Transaction() { return **mTransaction; }
const TransactionBase& Transaction() const { return **mTransaction; }
bool IsWaitingForContinue() const {
AssertIsOnOwningThread();
return mWaitingForContinue;
}
void NoteContinueReceived();
int64_t TransactionLoggingSerialNumber() const {
return mTransactionLoggingSerialNumber;
}
// May be overridden by subclasses if they need to perform work on the
// background thread before being dispatched. Returning false will kill the
// child actors and prevent dispatch.
virtual bool Init(TransactionBase& aTransaction);
// This callback will be called on the background thread before releasing the
// final reference to this request object. Subclasses may perform any
// additional cleanup here but must always call the base class implementation.
virtual void Cleanup();
protected:
TransactionDatabaseOperationBase(SafeRefPtr<TransactionBase> aTransaction,
int64_t aRequestId);
TransactionDatabaseOperationBase(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId,
uint64_t aLoggingSerialNumber);
~TransactionDatabaseOperationBase() override;
virtual void RunOnConnectionThread();
// Must be overridden in subclasses. Called on the target thread to allow the
// subclass to perform necessary database or file operations. A successful
// return value will trigger a SendSuccessResult callback on the background
// thread while a failure value will trigger a SendFailureResult callback.
virtual nsresult DoDatabaseWork(DatabaseConnection* aConnection) = 0;
// May be overriden in subclasses. Called on the background thread to decide
// if the subclass needs to send any preprocess info to the child actor.
virtual bool HasPreprocessInfo();
// May be overriden in subclasses. Called on the background thread to allow
// the subclass to serialize its preprocess info and send it to the child
// actor. A successful return value will trigger a wait for a
// NoteContinueReceived callback on the background thread while a failure
// value will trigger a SendFailureResult callback.
virtual nsresult SendPreprocessInfo();
// Must be overridden in subclasses. Called on the background thread to allow
// the subclass to serialize its results and send them to the child actor. A
// failed return value will trigger a SendFailureResult callback.
virtual nsresult SendSuccessResult() = 0;
// Must be overridden in subclasses. Called on the background thread to allow
// the subclass to send its failure code. Returning false will cause the
// transaction to be aborted with aResultCode. Returning true will not cause
// the transaction to be aborted.
virtual bool SendFailureResult(nsresult aResultCode) = 0;
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
auto MakeAutoSavepointCleanupHandler(DatabaseConnection& aConnection) {
return [this, &aConnection](const auto) {
if (!aConnection.GetUpdateRefcountFunction()) {
mAssumingPreviousOperationFail = true;
}
};
}
#endif
private:
void SendToConnectionPool();
void SendPreprocess();
void SendResults();
void SendPreprocessInfoOrResults(bool aSendPreprocessInfo);
// Not to be overridden by subclasses.
NS_DECL_NSIRUNNABLE
};
class Factory final : public PBackgroundIDBFactoryParent,
public AtomicSafeRefCounted<Factory> {
nsCString mSystemLocale;
RefPtr<DatabaseLoggingInfo> mLoggingInfo;
#ifdef DEBUG
bool mActorDestroyed;
#endif
// Reference counted.
~Factory() override;
public:
[[nodiscard]] static SafeRefPtr<Factory> Create(
const LoggingInfo& aLoggingInfo, const nsACString& aSystemLocale);
DatabaseLoggingInfo* GetLoggingInfo() const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mLoggingInfo);
return mLoggingInfo;
}
const nsCString& GetSystemLocale() const { return mSystemLocale; }
MOZ_DECLARE_REFCOUNTED_TYPENAME(mozilla::dom::indexedDB::Factory)
MOZ_INLINE_DECL_SAFEREFCOUNTING_INHERITED(Factory, AtomicSafeRefCounted)
// Only constructed in Create().
Factory(RefPtr<DatabaseLoggingInfo> aLoggingInfo,
const nsACString& aSystemLocale);
// IPDL methods are only called by IPDL.
void ActorDestroy(ActorDestroyReason aWhy) override;
mozilla::ipc::IPCResult RecvDeleteMe() override;
PBackgroundIDBFactoryRequestParent* AllocPBackgroundIDBFactoryRequestParent(
const FactoryRequestParams& aParams) override;
mozilla::ipc::IPCResult RecvPBackgroundIDBFactoryRequestConstructor(
PBackgroundIDBFactoryRequestParent* aActor,
const FactoryRequestParams& aParams) override;
bool DeallocPBackgroundIDBFactoryRequestParent(
PBackgroundIDBFactoryRequestParent* aActor) override;
mozilla::ipc::IPCResult RecvGetDatabases(
const PersistenceType& aPersistenceType,
const PrincipalInfo& aPrincipalInfo,
GetDatabasesResolver&& aResolve) override;
private:
Maybe<ContentParentId> GetContentParentId() const;
};
class WaitForTransactionsHelper final : public Runnable {
const nsCString mDatabaseId;
nsCOMPtr<nsIRunnable> mCallback;
enum class State { Initial = 0, WaitingForTransactions, Complete } mState;
public:
WaitForTransactionsHelper(const nsACString& aDatabaseId,
nsIRunnable* aCallback)
: Runnable("dom::indexedDB::WaitForTransactionsHelper"),
mDatabaseId(aDatabaseId),
mCallback(aCallback),
mState(State::Initial) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!aDatabaseId.IsEmpty());
MOZ_ASSERT(aCallback);
}
void WaitForTransactions();
NS_INLINE_DECL_REFCOUNTING_INHERITED(WaitForTransactionsHelper, Runnable)
private:
~WaitForTransactionsHelper() override {
MOZ_ASSERT(!mCallback);
MOZ_ASSERT(mState == State::Complete);
}
void MaybeWaitForTransactions();
void CallCallback();
NS_DECL_NSIRUNNABLE
};
class Database final : public PBackgroundIDBDatabaseParent,
public LinkedListElement<Database>,
public AtomicSafeRefCounted<Database> {
friend class VersionChangeTransaction;
class StartTransactionOp;
class UnmapBlobCallback;
private:
SafeRefPtr<Factory> mFactory;
SafeRefPtr<FullDatabaseMetadata> mMetadata;
SafeRefPtr<DatabaseFileManager> mFileManager;
ClientDirectoryLockHandle mDirectoryLockHandle;
nsTHashSet<TransactionBase*> mTransactions;
nsTHashMap<nsIDHashKey, SafeRefPtr<DatabaseFileInfo>> mMappedBlobs;
RefPtr<DatabaseConnection> mConnection;
const PrincipalInfo mPrincipalInfo;
const Maybe<ContentParentId> mOptionalContentParentId;
// XXX Consider changing this to ClientMetadata.
const quota::OriginMetadata mOriginMetadata;
const nsCString mId;
const nsString mFilePath;
const Maybe<const CipherKey> mKey;
int64_t mDirectoryLockId;
const uint32_t mTelemetryId;
const PersistenceType mPersistenceType;
const bool mInPrivateBrowsing;
FlippedOnce<false> mClosed;
FlippedOnce<false> mInvalidated;
FlippedOnce<false> mActorWasAlive;
FlippedOnce<false> mActorDestroyed;
nsCOMPtr<nsIEventTarget> mBackgroundThread;
#ifdef DEBUG
bool mAllBlobsUnmapped;
#endif
public:
// Created by OpenDatabaseOp.
Database(SafeRefPtr<Factory> aFactory, const PrincipalInfo& aPrincipalInfo,
const Maybe<ContentParentId>& aOptionalContentParentId,
const quota::OriginMetadata& aOriginMetadata, uint32_t aTelemetryId,
SafeRefPtr<FullDatabaseMetadata> aMetadata,
SafeRefPtr<DatabaseFileManager> aFileManager,
ClientDirectoryLockHandle aDirectoryLockHandle,
bool aInPrivateBrowsing, const Maybe<const CipherKey>& aMaybeKey);
void AssertIsOnConnectionThread() const {
#ifdef DEBUG
// mConnection is used to cache the result from ConnectionPool's
// GetOrCreateConnection method (potentially avoiding a lock and a hash
// lookup). However, once the connection is closed, the task queue for the
// given database is also destroyed, so the connection, which caches the
// event target it was created on, is no longer reliable for asserting that
// the current thread is the connection thread (mConnection might be reset
// when EnsureConnection is called again, but in the meantime, we have to
// fallback to just checking the main thread and the PBackgroud thread).
if (mConnection && !mConnection->Closed()) {
mConnection->AssertIsOnConnectionThread();
} else {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(mInvalidated);
}
#endif
}
NS_IMETHOD_(MozExternalRefCountType) AddRef() override {
return AtomicSafeRefCounted<Database>::AddRef();
}
NS_IMETHOD_(MozExternalRefCountType) Release() override {
return AtomicSafeRefCounted<Database>::Release();
}
MOZ_DECLARE_REFCOUNTED_TYPENAME(mozilla::dom::indexedDB::Database)
void Invalidate();
bool IsOwnedByProcess(ContentParentId aContentParentId) const {
return mOptionalContentParentId &&
mOptionalContentParentId.value() == aContentParentId;
}
const quota::OriginMetadata& OriginMetadata() const {
return mOriginMetadata;
}
const nsCString& Id() const { return mId; }
Maybe<ClientDirectoryLock&> MaybeDirectoryLockRef() const {
AssertIsOnBackgroundThread();
return ToMaybeRef(mDirectoryLockHandle.get());
}
int64_t DirectoryLockId() const { return mDirectoryLockId; }
uint32_t TelemetryId() const { return mTelemetryId; }
PersistenceType Type() const { return mPersistenceType; }
const nsString& FilePath() const { return mFilePath; }
DatabaseFileManager& GetFileManager() const { return *mFileManager; }
MovingNotNull<SafeRefPtr<DatabaseFileManager>> GetFileManagerPtr() const {
return WrapMovingNotNull(mFileManager.clonePtr());
}
const FullDatabaseMetadata& Metadata() const {
MOZ_ASSERT(mMetadata);
return *mMetadata;
}
SafeRefPtr<FullDatabaseMetadata> MetadataPtr() const {
MOZ_ASSERT(mMetadata);
return mMetadata.clonePtr();
}
PBackgroundParent* GetBackgroundParent() const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!IsActorDestroyed());
return Manager()->Manager();
}
DatabaseLoggingInfo* GetLoggingInfo() const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mFactory);
return mFactory->GetLoggingInfo();
}
bool RegisterTransaction(TransactionBase& aTransaction);
void UnregisterTransaction(TransactionBase& aTransaction);
void SetActorAlive();
void MapBlob(const IPCBlob& aIPCBlob, SafeRefPtr<DatabaseFileInfo> aFileInfo);
bool IsActorAlive() const {
AssertIsOnBackgroundThread();
return mActorWasAlive && !mActorDestroyed;
}
bool IsActorDestroyed() const {
AssertIsOnBackgroundThread();
return mActorWasAlive && mActorDestroyed;
}
bool IsClosed() const {
AssertIsOnBackgroundThread();
return mClosed;
}
bool IsInvalidated() const {
AssertIsOnBackgroundThread();
return mInvalidated;
}
nsresult EnsureConnection();
DatabaseConnection* GetConnection() const {
#ifdef DEBUG
if (mConnection) {
mConnection->AssertIsOnConnectionThread();
}
#endif
return mConnection;
}
void Stringify(nsACString& aResult) const;
bool IsInPrivateBrowsing() const {
AssertIsOnBackgroundThread();
return mInPrivateBrowsing;
}
const Maybe<const CipherKey>& MaybeKeyRef() const {
// This can be called on any thread, as it is const.
MOZ_ASSERT(mKey.isSome() == mInPrivateBrowsing);
return mKey;
}
~Database() override {
MOZ_ASSERT(mClosed);
MOZ_ASSERT_IF(mActorWasAlive, mActorDestroyed);
MOZ_DIAGNOSTIC_ASSERT(!isInList());
NS_ProxyRelease("ReleaseIDBFactory", mBackgroundThread.get(),
mFactory.forget());
}
private:
[[nodiscard]] SafeRefPtr<DatabaseFileInfo> GetBlob(const IPCBlob& aIPCBlob);
void UnmapBlob(const nsID& aID);
void UnmapAllBlobs();
bool CloseInternal();
void MaybeCloseConnection();
void ConnectionClosedCallback();
void CleanupMetadata();
// IPDL methods are only called by IPDL.
void ActorDestroy(ActorDestroyReason aWhy) override;
PBackgroundIDBDatabaseFileParent* AllocPBackgroundIDBDatabaseFileParent(
const IPCBlob& aIPCBlob) override;
bool DeallocPBackgroundIDBDatabaseFileParent(
PBackgroundIDBDatabaseFileParent* aActor) override;
already_AddRefed<PBackgroundIDBTransactionParent>
AllocPBackgroundIDBTransactionParent(
const nsTArray<nsString>& aObjectStoreNames, const Mode& aMode,
const Durability& aDurability) override;
mozilla::ipc::IPCResult RecvPBackgroundIDBTransactionConstructor(
PBackgroundIDBTransactionParent* aActor,
nsTArray<nsString>&& aObjectStoreNames, const Mode& aMode,
const Durability& aDurability) override;
mozilla::ipc::IPCResult RecvDeleteMe() override;
mozilla::ipc::IPCResult RecvBlocked() override;
mozilla::ipc::IPCResult RecvClose() override;
template <typename T>
static bool InvalidateAll(const nsTBaseHashSet<nsPtrHashKey<T>>& aTable);
};
class Database::StartTransactionOp final
: public TransactionDatabaseOperationBase {
friend class Database;
private:
explicit StartTransactionOp(SafeRefPtr<TransactionBase> aTransaction)
: TransactionDatabaseOperationBase(std::move(aTransaction),
/* aRequestId */ 0,
/* aLoggingSerialNumber */ 0) {}
~StartTransactionOp() override = default;
void RunOnConnectionThread() override;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
nsresult SendSuccessResult() override;
bool SendFailureResult(nsresult aResultCode) override;
void Cleanup() override;
};
class Database::UnmapBlobCallback final
: public RemoteLazyInputStreamParentCallback {
SafeRefPtr<Database> mDatabase;
nsCOMPtr<nsISerialEventTarget> mBackgroundThread;
public:
explicit UnmapBlobCallback(SafeRefPtr<Database> aDatabase)
: mDatabase(std::move(aDatabase)),
mBackgroundThread(GetCurrentSerialEventTarget()) {
AssertIsOnBackgroundThread();
}
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(Database::UnmapBlobCallback, override)
void ActorDestroyed(const nsID& aID) override {
MOZ_ASSERT(mDatabase);
mBackgroundThread->Dispatch(NS_NewRunnableFunction(
"UnmapBlobCallback", [aID, database = std::move(mDatabase)] {
AssertIsOnBackgroundThread();
database->UnmapBlob(aID);
}));
}
private:
~UnmapBlobCallback() = default;
};
/**
* In coordination with IDBDatabase's mFileActors weak-map on the child side, a
* long-lived mapping from a child process's live Blobs to their corresponding
* DatabaseFileInfo in our owning database. Assists in avoiding redundant IPC
* traffic and disk storage. This includes both:
* - Blobs retrieved from this database and sent to the child that do not need
* to be written to disk because they already exist on disk in this database's
* files directory.
* - Blobs retrieved from other databases or from anywhere else that will need
* to be written to this database's files directory. In this case we will
* hold a reference to its BlobImpl in mBlobImpl until we have successfully
* written the Blob to disk.
*
* Relevant Blob context: Blobs sent from the parent process to child processes
* are automatically linked back to their source BlobImpl when the child process
* references the Blob via IPC. This is done using the internal IPCBlob
* inputStream actor ID to DatabaseFileInfo mapping. However, when getting an
* actor in the child process for sending an in-child-created Blob to the
* parent process, there is (currently) no Blob machinery to automatically
* establish and reuse a long-lived Actor. As a result, without IDB's weak-map
* cleverness, a memory-backed Blob repeatedly sent from the child to the parent
* would appear as a different Blob each time, requiring the Blob data to be
* sent over IPC each time as well as potentially needing to be written to disk
* each time.
*
* This object remains alive as long as there is an active child actor or an
* ObjectStoreAddOrPutRequestOp::StoredFileInfo for a queued or active add/put
* op is holding a reference to us.
*/
class DatabaseFile final : public PBackgroundIDBDatabaseFileParent {
// mBlobImpl's ownership lifecycle:
// - Initialized on the background thread at creation time. Then
// responsibility is handed off to the connection thread.
// - Checked and used by the connection thread to generate a stream to write
// the blob to disk by an add/put operation.
// - Cleared on the connection thread once the file has successfully been
// written to disk.
InitializedOnce<const RefPtr<BlobImpl>> mBlobImpl;
const SafeRefPtr<DatabaseFileInfo> mFileInfo;
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(mozilla::dom::indexedDB::DatabaseFile);
const DatabaseFileInfo& GetFileInfo() const {
AssertIsOnBackgroundThread();
return *mFileInfo;
}
SafeRefPtr<DatabaseFileInfo> GetFileInfoPtr() const {
AssertIsOnBackgroundThread();
return mFileInfo.clonePtr();
}
/**
* If mBlobImpl is non-null (implying the contents of this file have not yet
* been written to disk), then return an input stream. Otherwise, if mBlobImpl
* is null (because the contents have been written to disk), returns null.
*/
[[nodiscard]] nsCOMPtr<nsIInputStream> GetInputStream(ErrorResult& rv) const;
/**
* To be called upon successful copying of the stream GetInputStream()
* returned so that we won't try and redundantly write the file to disk in the
* future. This is a separate step from GetInputStream() because
* the write could fail due to quota errors that happen now but that might
* not happen in a future attempt.
*/
void WriteSucceededClearBlobImpl() {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(*mBlobImpl);
mBlobImpl.destroy();
}
public:
// Called when sending to the child.
explicit DatabaseFile(SafeRefPtr<DatabaseFileInfo> aFileInfo)
: mBlobImpl{nullptr}, mFileInfo(std::move(aFileInfo)) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mFileInfo);
}
// Called when receiving from the child.
DatabaseFile(RefPtr<BlobImpl> aBlobImpl,
SafeRefPtr<DatabaseFileInfo> aFileInfo)
: mBlobImpl(std::move(aBlobImpl)), mFileInfo(std::move(aFileInfo)) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(*mBlobImpl);
MOZ_ASSERT(mFileInfo);
}
private:
~DatabaseFile() override = default;
void ActorDestroy(ActorDestroyReason aWhy) override {
AssertIsOnBackgroundThread();
}
};
nsCOMPtr<nsIInputStream> DatabaseFile::GetInputStream(ErrorResult& rv) const {
// We should only be called from our DB connection thread, not the background
// thread.
MOZ_ASSERT(!IsOnBackgroundThread());
// If we were constructed without a BlobImpl, or WriteSucceededClearBlobImpl
// was already called, return nullptr.
if (!mBlobImpl || !*mBlobImpl) {
return nullptr;
}
nsCOMPtr<nsIInputStream> inputStream;
(*mBlobImpl)->CreateInputStream(getter_AddRefs(inputStream), rv);
if (rv.Failed()) {
return nullptr;
}
return inputStream;
}
class TransactionBase : public AtomicSafeRefCounted<TransactionBase> {
friend class CursorBase;
template <IDBCursorType CursorType>
friend class Cursor;
class CommitOp;
protected:
using Mode = IDBTransaction::Mode;
using Durability = IDBTransaction::Durability;
private:
const SafeRefPtr<Database> mDatabase;
nsTArray<SafeRefPtr<FullObjectStoreMetadata>>
mModifiedAutoIncrementObjectStoreMetadataArray;
LazyInitializedOnceNotNull<const uint64_t> mTransactionId;
const nsCString mDatabaseId;
const int64_t mLoggingSerialNumber;
uint64_t mActiveRequestCount;
Atomic<bool> mInvalidatedOnAnyThread;
const Mode mMode;
const Durability mDurability;
FlippedOnce<false> mInitialized;
FlippedOnce<false> mHasBeenActiveOnConnectionThread;
FlippedOnce<false> mActorDestroyed;
FlippedOnce<false> mInvalidated;
protected:
nsresult mResultCode;
FlippedOnce<false> mCommitOrAbortReceived;
FlippedOnce<false> mCommittedOrAborted;
FlippedOnce<false> mForceAborted;
LazyInitializedOnce<const Maybe<int64_t>> mLastRequestBeforeCommit;
Maybe<int64_t> mLastFailedRequest;
public:
void AssertIsOnConnectionThread() const {
MOZ_ASSERT(mDatabase);
mDatabase->AssertIsOnConnectionThread();
}
bool IsActorDestroyed() const {
AssertIsOnBackgroundThread();
return mActorDestroyed;
}
// Must be called on the background thread.
bool IsInvalidated() const {
MOZ_ASSERT(IsOnBackgroundThread(), "Use IsInvalidatedOnAnyThread()");
MOZ_ASSERT_IF(mInvalidated, NS_FAILED(mResultCode));
return mInvalidated;
}
// May be called on any thread, but is more expensive than IsInvalidated().
bool IsInvalidatedOnAnyThread() const { return mInvalidatedOnAnyThread; }
void Init(const uint64_t aTransactionId) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aTransactionId);
mTransactionId.init(aTransactionId);
mInitialized.Flip();
}
void SetActiveOnConnectionThread() {
AssertIsOnConnectionThread();
mHasBeenActiveOnConnectionThread.Flip();
}
MOZ_DECLARE_REFCOUNTED_TYPENAME(mozilla::dom::indexedDB::TransactionBase)
void Abort(nsresult aResultCode, bool aForce);
uint64_t TransactionId() const { return *mTransactionId; }
const nsACString& DatabaseId() const { return mDatabaseId; }
Mode GetMode() const { return mMode; }
Durability GetDurability() const { return mDurability; }
const Database& GetDatabase() const {
MOZ_ASSERT(mDatabase);
return *mDatabase;
}
Database& GetMutableDatabase() const {
MOZ_ASSERT(mDatabase);
return *mDatabase;
}
SafeRefPtr<Database> GetDatabasePtr() const {
MOZ_ASSERT(mDatabase);
return mDatabase.clonePtr();
}
DatabaseLoggingInfo* GetLoggingInfo() const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mDatabase);
return mDatabase->GetLoggingInfo();
}
int64_t LoggingSerialNumber() const { return mLoggingSerialNumber; }
bool IsAborted() const {
AssertIsOnBackgroundThread();
return NS_FAILED(mResultCode);
}
[[nodiscard]] SafeRefPtr<FullObjectStoreMetadata> GetMetadataForObjectStoreId(
IndexOrObjectStoreId aObjectStoreId) const;
[[nodiscard]] SafeRefPtr<FullIndexMetadata> GetMetadataForIndexId(
FullObjectStoreMetadata& aObjectStoreMetadata,
IndexOrObjectStoreId aIndexId) const;
PBackgroundParent* GetBackgroundParent() const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!IsActorDestroyed());
return GetDatabase().GetBackgroundParent();
}
void NoteModifiedAutoIncrementObjectStore(
const SafeRefPtr<FullObjectStoreMetadata>& aMetadata);
void ForgetModifiedAutoIncrementObjectStore(
FullObjectStoreMetadata& aMetadata);
void NoteActiveRequest();
void NoteFinishedRequest(int64_t aRequestId, nsresult aResultCode);
void Invalidate();
virtual ~TransactionBase();
protected:
TransactionBase(SafeRefPtr<Database> aDatabase, Mode aMode,
Durability aDurability);
void NoteActorDestroyed() {
AssertIsOnBackgroundThread();
mActorDestroyed.Flip();
}
#ifdef DEBUG
// Only called by VersionChangeTransaction.
void FakeActorDestroyed() { mActorDestroyed.EnsureFlipped(); }
#endif
mozilla::ipc::IPCResult RecvCommit(IProtocol* aActor,
const Maybe<int64_t> aLastRequest);
mozilla::ipc::IPCResult RecvAbort(IProtocol* aActor, nsresult aResultCode);
void MaybeCommitOrAbort() {
AssertIsOnBackgroundThread();
// If we've already committed or aborted then there's nothing else to do.
if (mCommittedOrAborted) {
return;
}
// If there are active requests then we have to wait for those requests to
// complete (see NoteFinishedRequest).
if (mActiveRequestCount) {
return;
}
// If we haven't yet received a commit or abort message then there could be
// additional requests coming so we should wait unless we're being forced to
// abort.
if (!mCommitOrAbortReceived && !mForceAborted) {
return;
}
CommitOrAbort();
}
PBackgroundIDBRequestParent* AllocRequest(const int64_t aRequestId,
RequestParams&& aParams,
bool aTrustParams);
bool StartRequest(PBackgroundIDBRequestParent* aActor);
bool DeallocRequest(PBackgroundIDBRequestParent* aActor);
already_AddRefed<PBackgroundIDBCursorParent> AllocCursor(
const OpenCursorParams& aParams, bool aTrustParams);
bool StartCursor(PBackgroundIDBCursorParent* aActor, const int64_t aRequestId,
const OpenCursorParams& aParams);
virtual void UpdateMetadata(nsresult aResult) {}
virtual void SendCompleteNotification(nsresult aResult) = 0;
private:
bool VerifyRequestParams(const RequestParams& aParams) const;
bool VerifyRequestParams(const SerializedKeyRange& aParams) const;
bool VerifyRequestParams(const ObjectStoreAddPutParams& aParams) const;
bool VerifyRequestParams(const Maybe<SerializedKeyRange>& aParams) const;
void CommitOrAbort();
};
class TransactionBase::CommitOp final : public DatabaseOperationBase,
public ConnectionPool::FinishCallback {
friend class TransactionBase;
SafeRefPtr<TransactionBase> mTransaction;
nsresult mResultCode; ///< TODO: There is also a mResultCode in
///< DatabaseOperationBase. Is there a reason not to
///< use that? At least a more specific name should be
///< given to this one.
private:
CommitOp(SafeRefPtr<TransactionBase> aTransaction, nsresult aResultCode);
~CommitOp() override = default;
// Writes new autoIncrement counts to database.
nsresult WriteAutoIncrementCounts();
// Updates counts after a database activity has finished.
void CommitOrRollbackAutoIncrementCounts();
void AssertForeignKeyConsistency(DatabaseConnection* aConnection)
#ifdef DEBUG
;
#else
{
}
#endif
NS_DECL_NSIRUNNABLE
void TransactionFinishedBeforeUnblock() override;
void TransactionFinishedAfterUnblock() override;
public:
// We need to declare all of nsISupports, because FinishCallback has
// a pure-virtual nsISupports declaration.
NS_DECL_ISUPPORTS_INHERITED
};
class NormalTransaction final : public TransactionBase,
public PBackgroundIDBTransactionParent {
nsTArray<SafeRefPtr<FullObjectStoreMetadata>> mObjectStores;
// Reference counted.
~NormalTransaction() override = default;
bool IsSameProcessActor();
// Only called by TransactionBase.
void SendCompleteNotification(nsresult aResult) override;
// IPDL methods are only called by IPDL.
void ActorDestroy(ActorDestroyReason aWhy) override;
mozilla::ipc::IPCResult RecvDeleteMe() override;
mozilla::ipc::IPCResult RecvCommit(
const Maybe<int64_t>& aLastRequest) override;
mozilla::ipc::IPCResult RecvAbort(const nsresult& aResultCode) override;
PBackgroundIDBRequestParent* AllocPBackgroundIDBRequestParent(
const int64_t& aRequestId, const RequestParams& aParams) override;
mozilla::ipc::IPCResult RecvPBackgroundIDBRequestConstructor(
PBackgroundIDBRequestParent* aActor, const int64_t& aRequestId,
const RequestParams& aParams) override;
bool DeallocPBackgroundIDBRequestParent(
PBackgroundIDBRequestParent* aActor) override;
already_AddRefed<PBackgroundIDBCursorParent> AllocPBackgroundIDBCursorParent(
const int64_t& aRequestId, const OpenCursorParams& aParams) override;
mozilla::ipc::IPCResult RecvPBackgroundIDBCursorConstructor(
PBackgroundIDBCursorParent* aActor, const int64_t& aRequestId,
const OpenCursorParams& aParams) override;
public:
// This constructor is only called by Database.
NormalTransaction(
SafeRefPtr<Database> aDatabase, TransactionBase::Mode aMode,
TransactionBase::Durability aDurability,
nsTArray<SafeRefPtr<FullObjectStoreMetadata>>&& aObjectStores);
MOZ_INLINE_DECL_SAFEREFCOUNTING_INHERITED(NormalTransaction, TransactionBase)
};
class VersionChangeTransaction final
: public TransactionBase,
public PBackgroundIDBVersionChangeTransactionParent {
friend class OpenDatabaseOp;
RefPtr<OpenDatabaseOp> mOpenDatabaseOp;
SafeRefPtr<FullDatabaseMetadata> mOldMetadata;
FlippedOnce<false> mActorWasAlive;
public:
// Only called by OpenDatabaseOp.
explicit VersionChangeTransaction(OpenDatabaseOp* aOpenDatabaseOp);
MOZ_INLINE_DECL_SAFEREFCOUNTING_INHERITED(VersionChangeTransaction,
TransactionBase)
private:
// Reference counted.
~VersionChangeTransaction() override;
bool IsSameProcessActor();
// Only called by OpenDatabaseOp.
bool CopyDatabaseMetadata();
void SetActorAlive();
// Only called by TransactionBase.
void UpdateMetadata(nsresult aResult) override;
// Only called by TransactionBase.
void SendCompleteNotification(nsresult aResult) override;
// IPDL methods are only called by IPDL.
void ActorDestroy(ActorDestroyReason aWhy) override;
mozilla::ipc::IPCResult RecvDeleteMe() override;
mozilla::ipc::IPCResult RecvCommit(
const Maybe<int64_t>& aLastRequest) override;
mozilla::ipc::IPCResult RecvAbort(const nsresult& aResultCode) override;
mozilla::ipc::IPCResult RecvCreateObjectStore(
const ObjectStoreMetadata& aMetadata) override;
mozilla::ipc::IPCResult RecvDeleteObjectStore(
const IndexOrObjectStoreId& aObjectStoreId) override;
mozilla::ipc::IPCResult RecvRenameObjectStore(
const IndexOrObjectStoreId& aObjectStoreId,
const nsAString& aName) override;
mozilla::ipc::IPCResult RecvCreateIndex(
const IndexOrObjectStoreId& aObjectStoreId,
const IndexMetadata& aMetadata) override;
mozilla::ipc::IPCResult RecvDeleteIndex(
const IndexOrObjectStoreId& aObjectStoreId,
const IndexOrObjectStoreId& aIndexId) override;
mozilla::ipc::IPCResult RecvRenameIndex(
const IndexOrObjectStoreId& aObjectStoreId,
const IndexOrObjectStoreId& aIndexId, const nsAString& aName) override;
PBackgroundIDBRequestParent* AllocPBackgroundIDBRequestParent(
const int64_t& aRequestId, const RequestParams& aParams) override;
mozilla::ipc::IPCResult RecvPBackgroundIDBRequestConstructor(
PBackgroundIDBRequestParent* aActor, const int64_t& aRequestId,
const RequestParams& aParams) override;
bool DeallocPBackgroundIDBRequestParent(
PBackgroundIDBRequestParent* aActor) override;
already_AddRefed<PBackgroundIDBCursorParent> AllocPBackgroundIDBCursorParent(
const int64_t& aRequestId, const OpenCursorParams& aParams) override;
mozilla::ipc::IPCResult RecvPBackgroundIDBCursorConstructor(
PBackgroundIDBCursorParent* aActor, const int64_t& aRequestId,
const OpenCursorParams& aParams) override;
};
class FactoryOp : public DatabaseOperationBase,
public LinkedListElement<FactoryOp> {
public:
struct MaybeBlockedDatabaseInfo final {
SafeRefPtr<Database> mDatabase;
bool mBlocked;
MaybeBlockedDatabaseInfo(MaybeBlockedDatabaseInfo&&) = default;
MaybeBlockedDatabaseInfo& operator=(MaybeBlockedDatabaseInfo&&) = default;
MOZ_IMPLICIT MaybeBlockedDatabaseInfo(SafeRefPtr<Database> aDatabase)
: mDatabase(std::move(aDatabase)), mBlocked(false) {
MOZ_ASSERT(mDatabase);
MOZ_COUNT_CTOR(FactoryOp::MaybeBlockedDatabaseInfo);
}
~MaybeBlockedDatabaseInfo() {
MOZ_COUNT_DTOR(FactoryOp::MaybeBlockedDatabaseInfo);
}
bool operator==(const Database* aOther) const {
return mDatabase == aOther;
}
Database* operator->() const& MOZ_NO_ADDREF_RELEASE_ON_RETURN {
return mDatabase.unsafeGetRawPtr();
}
};
protected:
enum class State {
// Just created on the PBackground thread, dispatched to the current thread.
// Next step is either SendingResults if opening initialization failed, or
// DirectoryOpenPending if the opening initialization succeeded.
Initial,
// Waiting for directory open allowed on the PBackground thread. The next
// step is either SendingResults if directory lock failed to acquire, or
// DirectoryWorkOpen if the factory operation is not tied up to a specific
// database, or DatabaseOpenPending otherwise.
DirectoryOpenPending,
// Waiting to do/doing directory work on the QuotaManager IO thread. Its
// next step is DirectoryWorkDone if directory work was successful or
// SendingResults if directory work failed.
DirectoryWorkOpen,
// Checking if database work can be started. If the database is not blocked
// by other factory operations then the next step is DatabaseWorkOpen.
// Otherwise the next step is DatabaseOpenPending.
DirectoryWorkDone,
// Waiting for database open allowed on the PBackground thread. The next
// step is DatabaseWorkOpen.
DatabaseOpenPending,
// Waiting to do/doing work on the QuotaManager IO thread. Its next step is
// either BeginVersionChange if the requested version doesn't match the
// existing database version or SendingResults if the versions match.
DatabaseWorkOpen,
// Starting a version change transaction or deleting a database on the
// PBackground thread. We need to notify other databases that a version
// change is about to happen, and maybe tell the request that a version
// change has been blocked. If databases are notified then the next step is
// WaitingForOtherDatabasesToClose. Otherwise the next step is
// WaitingForTransactionsToComplete.
BeginVersionChange,
// Waiting for other databases to close on the PBackground thread. This
// state may persist until all databases are closed. The next state is
// WaitingForTransactionsToComplete.
WaitingForOtherDatabasesToClose,
// Waiting for all transactions that could interfere with this operation to
// complete on the PBackground thread. Next state is
// DatabaseWorkVersionChange.
WaitingForTransactionsToComplete,
// Waiting to do/doing work on the "work thread". This involves waiting for
// the VersionChangeOp (OpenDatabaseOp and DeleteDatabaseOp each have a
// different implementation) to do its work. If the VersionChangeOp is
// OpenDatabaseOp and it succeeded then the next state is
// DatabaseWorkVersionUpdate. Otherwise the next step is SendingResults.
DatabaseWorkVersionChange,
// Waiting to do/doing finalization work on the QuotaManager IO thread.
// Eventually the state will transition to SendingResults.
DatabaseWorkVersionUpdate,
// Waiting to send/sending results on the PBackground thread. Next step is
// Completed.
SendingResults,
// All done.
Completed
};
// Must be released on the background thread!
SafeRefPtr<Factory> mFactory;
Maybe<ContentParentId> mContentParentId;
// Must be released on the main thread!
ClientDirectoryLockHandle mDirectoryLockHandle;
nsTArray<NotNull<RefPtr<FactoryOp>>> mBlocking;
nsTHashSet<RefPtr<FactoryOp>> mBlockedOn;
nsTArray<MaybeBlockedDatabaseInfo> mMaybeBlockedDatabases;
const PrincipalInfo mPrincipalInfo;
OriginMetadata mOriginMetadata;
Maybe<nsString> mDatabaseName;
Maybe<nsCString> mDatabaseId;
Maybe<nsString> mDatabaseFilePath;
int64_t mDirectoryLockId;
const PersistenceType mPersistenceType;
State mState;
bool mWaitingForPermissionRetry;
bool mEnforcingQuota;
const bool mDeleting;
FlippedOnce<false> mInPrivateBrowsing;
public:
const nsACString& Origin() const {
AssertIsOnOwningThread();
return mOriginMetadata.mOrigin;
}
const Maybe<nsString>& DatabaseNameRef() const {
AssertIsOnOwningThread();
return mDatabaseName;
}
bool DatabaseFilePathIsKnown() const {
AssertIsOnOwningThread();
return mDatabaseFilePath.isSome();
}
const nsAString& DatabaseFilePath() const {
AssertIsOnOwningThread();
MOZ_ASSERT(mDatabaseFilePath);
return mDatabaseFilePath.ref();
}
nsresult DispatchThisAfterProcessingCurrentEvent(
nsCOMPtr<nsIEventTarget> aEventTarget);
void NoteDatabaseBlocked(Database* aDatabase);
void NoteDatabaseClosed(Database* aDatabase);
#ifdef DEBUG
bool HasBlockedDatabases() const { return !mMaybeBlockedDatabases.IsEmpty(); }
#endif
void StringifyState(nsACString& aResult) const;
void Stringify(nsACString& aResult) const;
protected:
FactoryOp(SafeRefPtr<Factory> aFactory,
const Maybe<ContentParentId>& aContentParentId,
const PersistenceType aPersistenceType,
const PrincipalInfo& aPrincipalInfo,
const Maybe<nsString>& aDatabaseName, bool aDeleting);
~FactoryOp() override {
// Normally this would be out-of-line since it is a virtual function but
// MSVC 2010 fails to link for some reason if it is not inlined here...
MOZ_ASSERT_IF(OperationMayProceed(),
mState == State::Initial || mState == State::Completed);
MOZ_DIAGNOSTIC_ASSERT(!isInList());
}
nsresult Open();
nsresult DirectoryOpen();
nsresult DirectoryWorkDone();
nsresult SendToIOThread();
void WaitForTransactions();
void CleanupMetadata();
void FinishSendResults();
nsresult SendVersionChangeMessages(DatabaseActorInfo* aDatabaseActorInfo,
Maybe<Database&> aOpeningDatabase,
uint64_t aOldVersion,
const Maybe<uint64_t>& aNewVersion);
// Methods that subclasses must implement.
virtual nsresult DoDirectoryWork() = 0;
virtual nsresult DatabaseOpen() = 0;
virtual nsresult DoDatabaseWork() = 0;
virtual nsresult BeginVersionChange() = 0;
virtual bool AreActorsAlive() = 0;
virtual nsresult DispatchToWorkThread() = 0;
virtual nsresult DoVersionUpdate() = 0;
// Should only be called by Run().
virtual void SendResults() = 0;
// Common nsIRunnable implementation that subclasses may not override.
NS_IMETHOD
Run() final;
void DirectoryLockAcquired(ClientDirectoryLockHandle aLockHandle);
void DirectoryLockFailed();
virtual void SendBlockedNotification() = 0;
private:
// Test whether this FactoryOp needs to wait for the given op.
bool MustWaitFor(const FactoryOp& aExistingOp);
void AddBlockingOp(FactoryOp& aOp) {
AssertIsOnOwningThread();
mBlocking.AppendElement(WrapNotNull(&aOp));
}
void AddBlockedOnOp(FactoryOp& aOp) {
AssertIsOnOwningThread();
mBlockedOn.Insert(&aOp);
}
void MaybeUnblock(FactoryOp& aOp) {
AssertIsOnOwningThread();
mBlockedOn.Remove(&aOp);
if (mBlockedOn.IsEmpty()) {
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(this));
}
}
};
class FactoryRequestOp : public FactoryOp,
public PBackgroundIDBFactoryRequestParent {
protected:
const CommonFactoryRequestParams mCommonParams;
FactoryRequestOp(SafeRefPtr<Factory> aFactory,
const Maybe<ContentParentId>& aContentParentId,
const CommonFactoryRequestParams& aCommonParams,
bool aDeleting)
: FactoryOp(std::move(aFactory), aContentParentId,
aCommonParams.metadata().persistenceType(),
aCommonParams.principalInfo(),
Some(aCommonParams.metadata().name()), aDeleting),
mCommonParams(aCommonParams) {}
nsresult DoDirectoryWork() override;
// IPDL methods.
void ActorDestroy(ActorDestroyReason aWhy) override;
};
class OpenDatabaseOp final : public FactoryRequestOp {
friend class Database;
friend class VersionChangeTransaction;
class VersionChangeOp;
SafeRefPtr<FullDatabaseMetadata> mMetadata;
uint64_t mRequestedVersion;
SafeRefPtr<DatabaseFileManager> mFileManager;
SafeRefPtr<Database> mDatabase;
SafeRefPtr<VersionChangeTransaction> mVersionChangeTransaction;
// This is only set while a VersionChangeOp is live. It holds a strong
// reference to its OpenDatabaseOp object so this is a weak pointer to avoid
// cycles.
VersionChangeOp* mVersionChangeOp;
MoveOnlyFunction<void()> mCompleteCallback;
uint32_t mTelemetryId;
public:
OpenDatabaseOp(SafeRefPtr<Factory> aFactory,
const Maybe<ContentParentId>& aContentParentId,
const CommonFactoryRequestParams& aParams);
private:
~OpenDatabaseOp() override { MOZ_ASSERT(!mVersionChangeOp); }
nsresult LoadDatabaseInformation(mozIStorageConnection& aConnection);
nsresult SendUpgradeNeeded();
void EnsureDatabaseActor();
nsresult EnsureDatabaseActorIsAlive();
mozilla::Result<DatabaseSpec, nsresult> MetadataToSpec() const;
void AssertMetadataConsistency(const FullDatabaseMetadata& aMetadata)
#ifdef DEBUG
;
#else
{
}
#endif
void ConnectionClosedCallback();
void ActorDestroy(ActorDestroyReason aWhy) override;
nsresult DatabaseOpen() override;
nsresult DoDatabaseWork() override;
nsresult BeginVersionChange() override;
bool AreActorsAlive() override;
void SendBlockedNotification() override;
nsresult DispatchToWorkThread() override;
nsresult DoVersionUpdate() override;
void SendResults() override;
static nsresult UpdateLocaleAwareIndex(mozIStorageConnection& aConnection,
const IndexMetadata& aIndexMetadata,
const nsCString& aLocale);
};
class OpenDatabaseOp::VersionChangeOp final
: public TransactionDatabaseOperationBase {
friend class OpenDatabaseOp;
RefPtr<OpenDatabaseOp> mOpenDatabaseOp;
const uint64_t mRequestedVersion;
uint64_t mPreviousVersion;
private:
explicit VersionChangeOp(OpenDatabaseOp* aOpenDatabaseOp)
: TransactionDatabaseOperationBase(
aOpenDatabaseOp->mVersionChangeTransaction.clonePtr(),
/* aRequestId */ 0, aOpenDatabaseOp->LoggingSerialNumber()),
mOpenDatabaseOp(aOpenDatabaseOp),
mRequestedVersion(aOpenDatabaseOp->mRequestedVersion),
mPreviousVersion(
aOpenDatabaseOp->mMetadata->mCommonMetadata.version()) {
MOZ_ASSERT(aOpenDatabaseOp);
MOZ_ASSERT(mRequestedVersion);
}
~VersionChangeOp() override { MOZ_ASSERT(!mOpenDatabaseOp); }
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
nsresult SendSuccessResult() override;
bool SendFailureResult(nsresult aResultCode) override;
void Cleanup() override;
};
class DeleteDatabaseOp final : public FactoryRequestOp {
class VersionChangeOp;
nsString mDatabaseDirectoryPath;
nsString mDatabaseFilenameBase;
uint64_t mPreviousVersion;
public:
DeleteDatabaseOp(SafeRefPtr<Factory> aFactory,
const Maybe<ContentParentId>& aContentParentId,
const CommonFactoryRequestParams& aParams)
: FactoryRequestOp(std::move(aFactory), aContentParentId, aParams,
/* aDeleting */ true),
mPreviousVersion(0) {}
private:
~DeleteDatabaseOp() override = default;
void LoadPreviousVersion(nsIFile& aDatabaseFile);
nsresult DatabaseOpen() override;
nsresult DoDatabaseWork() override;
nsresult BeginVersionChange() override;
bool AreActorsAlive() override;
void SendBlockedNotification() override;
nsresult DispatchToWorkThread() override;
nsresult DoVersionUpdate() override;
void SendResults() override;
};
class DeleteDatabaseOp::VersionChangeOp final : public DatabaseOperationBase {
friend class DeleteDatabaseOp;
RefPtr<DeleteDatabaseOp> mDeleteDatabaseOp;
private:
explicit VersionChangeOp(DeleteDatabaseOp* aDeleteDatabaseOp)
: DatabaseOperationBase(aDeleteDatabaseOp->BackgroundChildLoggingId(),
aDeleteDatabaseOp->LoggingSerialNumber()),
mDeleteDatabaseOp(aDeleteDatabaseOp) {
MOZ_ASSERT(aDeleteDatabaseOp);
MOZ_ASSERT(!aDeleteDatabaseOp->mDatabaseDirectoryPath.IsEmpty());
}
~VersionChangeOp() override = default;
nsresult RunOnIOThread();
void RunOnOwningThread();
NS_DECL_NSIRUNNABLE
};
class GetDatabasesOp final : public FactoryOp {
nsTHashMap<nsStringHashKey, DatabaseMetadata> mDatabaseMetadataTable;
nsTArray<DatabaseMetadata> mDatabaseMetadataArray;
Factory::GetDatabasesResolver mResolver;
public:
GetDatabasesOp(SafeRefPtr<Factory> aFactory,
const Maybe<ContentParentId>& aContentParentId,
const PersistenceType aPersistenceType,
const PrincipalInfo& aPrincipalInfo,
Factory::GetDatabasesResolver&& aResolver)
: FactoryOp(std::move(aFactory), aContentParentId, aPersistenceType,
aPrincipalInfo, Nothing(), /* aDeleting */ false),
mResolver(std::move(aResolver)) {}
private:
~GetDatabasesOp() override = default;
nsresult DatabasesNotAvailable();
nsresult DoDirectoryWork() override;
nsresult DatabaseOpen() override;
nsresult DoDatabaseWork() override;
nsresult BeginVersionChange() override;
bool AreActorsAlive() override;
void SendBlockedNotification() override;
nsresult DispatchToWorkThread() override;
nsresult DoVersionUpdate() override;
void SendResults() override;
};
class VersionChangeTransactionOp : public TransactionDatabaseOperationBase {
public:
void Cleanup() override;
protected:
explicit VersionChangeTransactionOp(
SafeRefPtr<VersionChangeTransaction> aTransaction)
: TransactionDatabaseOperationBase(std::move(aTransaction),
/* aRequestId */ 0) {}
~VersionChangeTransactionOp() override = default;
private:
nsresult SendSuccessResult() override;
bool SendFailureResult(nsresult aResultCode) override;
};
class CreateObjectStoreOp final : public VersionChangeTransactionOp {
friend class VersionChangeTransaction;
const ObjectStoreMetadata mMetadata;
private:
// Only created by VersionChangeTransaction.
CreateObjectStoreOp(SafeRefPtr<VersionChangeTransaction> aTransaction,
const ObjectStoreMetadata& aMetadata)
: VersionChangeTransactionOp(std::move(aTransaction)),
mMetadata(aMetadata) {
MOZ_ASSERT(aMetadata.id());
}
~CreateObjectStoreOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
};
class DeleteObjectStoreOp final : public VersionChangeTransactionOp {
friend class VersionChangeTransaction;
const SafeRefPtr<FullObjectStoreMetadata> mMetadata;
const bool mIsLastObjectStore;
private:
// Only created by VersionChangeTransaction.
DeleteObjectStoreOp(SafeRefPtr<VersionChangeTransaction> aTransaction,
SafeRefPtr<FullObjectStoreMetadata> aMetadata,
const bool aIsLastObjectStore)
: VersionChangeTransactionOp(std::move(aTransaction)),
mMetadata(std::move(aMetadata)),
mIsLastObjectStore(aIsLastObjectStore) {
MOZ_ASSERT(mMetadata->mCommonMetadata.id());
}
~DeleteObjectStoreOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
};
class RenameObjectStoreOp final : public VersionChangeTransactionOp {
friend class VersionChangeTransaction;
const int64_t mId;
const nsString mNewName;
private:
// Only created by VersionChangeTransaction.
RenameObjectStoreOp(SafeRefPtr<VersionChangeTransaction> aTransaction,
FullObjectStoreMetadata& aMetadata)
: VersionChangeTransactionOp(std::move(aTransaction)),
mId(aMetadata.mCommonMetadata.id()),
mNewName(aMetadata.mCommonMetadata.name()) {
MOZ_ASSERT(mId);
}
~RenameObjectStoreOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
};
class CreateIndexOp final : public VersionChangeTransactionOp {
friend class VersionChangeTransaction;
class UpdateIndexDataValuesFunction;
const IndexMetadata mMetadata;
Maybe<UniqueIndexTable> mMaybeUniqueIndexTable;
const SafeRefPtr<DatabaseFileManager> mFileManager;
const nsCString mDatabaseId;
const IndexOrObjectStoreId mObjectStoreId;
private:
// Only created by VersionChangeTransaction.
CreateIndexOp(SafeRefPtr<VersionChangeTransaction> aTransaction,
IndexOrObjectStoreId aObjectStoreId,
const IndexMetadata& aMetadata);
~CreateIndexOp() override = default;
nsresult InsertDataFromObjectStore(DatabaseConnection* aConnection);
nsresult InsertDataFromObjectStoreInternal(
DatabaseConnection* aConnection) const;
bool Init(TransactionBase& aTransaction) override;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
};
class CreateIndexOp::UpdateIndexDataValuesFunction final
: public mozIStorageFunction {
RefPtr<CreateIndexOp> mOp;
RefPtr<DatabaseConnection> mConnection;
const NotNull<SafeRefPtr<Database>> mDatabase;
public:
UpdateIndexDataValuesFunction(CreateIndexOp* aOp,
DatabaseConnection* aConnection,
SafeRefPtr<Database> aDatabase)
: mOp(aOp),
mConnection(aConnection),
mDatabase(WrapNotNull(std::move(aDatabase))) {
MOZ_ASSERT(aOp);
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
}
NS_DECL_ISUPPORTS
private:
~UpdateIndexDataValuesFunction() = default;
NS_DECL_MOZISTORAGEFUNCTION
};
class DeleteIndexOp final : public VersionChangeTransactionOp {
friend class VersionChangeTransaction;
const IndexOrObjectStoreId mObjectStoreId;
const IndexOrObjectStoreId mIndexId;
const bool mUnique;
const bool mIsLastIndex;
private:
// Only created by VersionChangeTransaction.
DeleteIndexOp(SafeRefPtr<VersionChangeTransaction> aTransaction,
IndexOrObjectStoreId aObjectStoreId,
IndexOrObjectStoreId aIndexId, const bool aUnique,
const bool aIsLastIndex);
~DeleteIndexOp() override = default;
nsresult RemoveReferencesToIndex(
DatabaseConnection* aConnection, const Key& aObjectDataKey,
nsTArray<IndexDataValue>& aIndexValues) const;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
};
class RenameIndexOp final : public VersionChangeTransactionOp {
friend class VersionChangeTransaction;
const IndexOrObjectStoreId mObjectStoreId;
const IndexOrObjectStoreId mIndexId;
const nsString mNewName;
private:
// Only created by VersionChangeTransaction.
RenameIndexOp(SafeRefPtr<VersionChangeTransaction> aTransaction,
FullIndexMetadata& aMetadata,
IndexOrObjectStoreId aObjectStoreId)
: VersionChangeTransactionOp(std::move(aTransaction)),
mObjectStoreId(aObjectStoreId),
mIndexId(aMetadata.mCommonMetadata.id()),
mNewName(aMetadata.mCommonMetadata.name()) {
MOZ_ASSERT(mIndexId);
}
~RenameIndexOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
};
class NormalTransactionOp : public TransactionDatabaseOperationBase,
public PBackgroundIDBRequestParent {
#ifdef DEBUG
bool mResponseSent;
#endif
public:
void Cleanup() override;
protected:
NormalTransactionOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId)
: TransactionDatabaseOperationBase(std::move(aTransaction), aRequestId)
#ifdef DEBUG
,
mResponseSent(false)
#endif
{
}
~NormalTransactionOp() override = default;
// An overload of DatabaseOperationBase's function that can avoid doing extra
// work on non-versionchange transactions.
mozilla::Result<bool, nsresult> ObjectStoreHasIndexes(
DatabaseConnection& aConnection, IndexOrObjectStoreId aObjectStoreId,
bool aMayHaveIndexes);
virtual mozilla::Result<PreprocessParams, nsresult> GetPreprocessParams();
// Subclasses use this override to set the IPDL response value.
virtual void GetResponse(RequestResponse& aResponse,
size_t* aResponseSize) = 0;
private:
nsresult SendPreprocessInfo() override;
nsresult SendSuccessResult() override;
bool SendFailureResult(nsresult aResultCode) override;
// IPDL methods.
void ActorDestroy(ActorDestroyReason aWhy) override;
mozilla::ipc::IPCResult RecvContinue(
const PreprocessResponse& aResponse) final;
};
class ObjectStoreAddOrPutRequestOp final : public NormalTransactionOp {
friend class TransactionBase;
using PersistenceType = mozilla::dom::quota::PersistenceType;
class StoredFileInfo final {
InitializedOnce<const NotNull<SafeRefPtr<DatabaseFileInfo>>> mFileInfo;
// Either nothing, a file actor or a non-Blob-backed inputstream to write to
// disk.
using FileActorOrInputStream =
Variant<Nothing, RefPtr<DatabaseFile>, nsCOMPtr<nsIInputStream>>;
InitializedOnce<const FileActorOrInputStream> mFileActorOrInputStream;
#ifdef DEBUG
const StructuredCloneFileBase::FileType mType;
#endif
void EnsureCipherKey();
void AssertInvariants() const;
StoredFileInfo(SafeRefPtr<DatabaseFileInfo> aFileInfo,
RefPtr<DatabaseFile> aFileActor);
StoredFileInfo(SafeRefPtr<DatabaseFileInfo> aFileInfo,
nsCOMPtr<nsIInputStream> aInputStream);
public:
#if defined(NS_BUILD_REFCNT_LOGGING)
// Only for MOZ_COUNT_CTOR.
StoredFileInfo(StoredFileInfo&& aOther)
: mFileInfo{std::move(aOther.mFileInfo)},
mFileActorOrInputStream{std::move(aOther.mFileActorOrInputStream)}
# ifdef DEBUG
,
mType{aOther.mType}
# endif
{
MOZ_COUNT_CTOR(ObjectStoreAddOrPutRequestOp::StoredFileInfo);
}
#else
StoredFileInfo(StoredFileInfo&&) = default;
#endif
static StoredFileInfo CreateForBlob(SafeRefPtr<DatabaseFileInfo> aFileInfo,
RefPtr<DatabaseFile> aFileActor);
static StoredFileInfo CreateForStructuredClone(
SafeRefPtr<DatabaseFileInfo> aFileInfo,
nsCOMPtr<nsIInputStream> aInputStream);
#if defined(DEBUG) || defined(NS_BUILD_REFCNT_LOGGING)
~StoredFileInfo() {
AssertIsOnBackgroundThread();
AssertInvariants();
MOZ_COUNT_DTOR(ObjectStoreAddOrPutRequestOp::StoredFileInfo);
}
#endif
bool IsValid() const { return static_cast<bool>(mFileInfo); }
const DatabaseFileInfo& GetFileInfo() const { return **mFileInfo; }
bool ShouldCompress() const;
void NotifyWriteSucceeded() const;
using InputStreamResult =
mozilla::Result<nsCOMPtr<nsIInputStream>, nsresult>;
InputStreamResult GetInputStream();
void Serialize(nsString& aText) const;
};
class SCInputStream;
ObjectStoreAddPutParams mParams;
Maybe<UniqueIndexTable> mUniqueIndexTable;
// This must be non-const so that we can update the mNextAutoIncrementId field
// if we are modifying an autoIncrement objectStore.
SafeRefPtr<FullObjectStoreMetadata> mMetadata;
nsTArray<StoredFileInfo> mStoredFileInfos;
Key mResponse;
const OriginMetadata mOriginMetadata;
const PersistenceType mPersistenceType;
const bool mOverwrite;
bool mObjectStoreMayHaveIndexes;
bool mDataOverThreshold;
private:
// Only created by TransactionBase.
ObjectStoreAddOrPutRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId,
RequestParams&& aParams);
~ObjectStoreAddOrPutRequestOp() override = default;
nsresult RemoveOldIndexDataValues(DatabaseConnection* aConnection);
bool Init(TransactionBase& aTransaction) override;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override;
void Cleanup() override;
};
void ObjectStoreAddOrPutRequestOp::StoredFileInfo::AssertInvariants() const {
// The only allowed types are eStructuredClone, eBlob and eMutableFile.
MOZ_ASSERT(StructuredCloneFileBase::eStructuredClone == mType ||
StructuredCloneFileBase::eBlob == mType ||
StructuredCloneFileBase::eMutableFile == mType);
// mFileInfo and a file actor in mFileActorOrInputStream are present until
// the object is moved away, but an inputStream in mFileActorOrInputStream
// can be released early.
MOZ_ASSERT_IF(static_cast<bool>(mFileActorOrInputStream) &&
mFileActorOrInputStream->is<RefPtr<DatabaseFile>>(),
static_cast<bool>(mFileInfo));
if (mFileInfo) {
// In a non-moved StoredFileInfo, one of the following is true:
// - This was an overflow structured clone (eStructuredClone) and
// storedFileInfo.mFileActorOrInputStream CAN be a non-nullptr input
// stream (but that might have been release by ReleaseInputStream).
MOZ_ASSERT_IF(
StructuredCloneFileBase::eStructuredClone == mType,
!mFileActorOrInputStream ||
(mFileActorOrInputStream->is<nsCOMPtr<nsIInputStream>>() &&
mFileActorOrInputStream->as<nsCOMPtr<nsIInputStream>>()));
// - This is a reference to a Blob (eBlob) that may or may not have
// already been written to disk. storedFileInfo.mFileActorOrInputStream
// MUST be a non-null file actor, but its GetInputStream may return
// nullptr (so don't assert on that).
MOZ_ASSERT_IF(StructuredCloneFileBase::eBlob == mType,
mFileActorOrInputStream->is<RefPtr<DatabaseFile>>() &&
mFileActorOrInputStream->as<RefPtr<DatabaseFile>>());
// - It's a mutable file (eMutableFile). No writing will be performed,
// and storedFileInfo.mFileActorOrInputStream is Nothing.
MOZ_ASSERT_IF(StructuredCloneFileBase::eMutableFile == mType,
mFileActorOrInputStream->is<Nothing>());
}
}
void ObjectStoreAddOrPutRequestOp::StoredFileInfo::EnsureCipherKey() {
const auto& fileInfo = GetFileInfo();
const auto& fileManager = fileInfo.Manager();
// No need to generate cipher keys if we are not in PBM
if (!fileManager.IsInPrivateBrowsingMode()) {
return;
}
nsCString keyId;
keyId.AppendInt(fileInfo.Id());
fileManager.MutableCipherKeyManagerRef().Ensure(keyId);
}
ObjectStoreAddOrPutRequestOp::StoredFileInfo::StoredFileInfo(
SafeRefPtr<DatabaseFileInfo> aFileInfo, RefPtr<DatabaseFile> aFileActor)
: mFileInfo{WrapNotNull(std::move(aFileInfo))},
mFileActorOrInputStream{std::move(aFileActor)}
#ifdef DEBUG
,
mType{StructuredCloneFileBase::eBlob}
#endif
{
AssertIsOnBackgroundThread();
AssertInvariants();
EnsureCipherKey();
MOZ_COUNT_CTOR(ObjectStoreAddOrPutRequestOp::StoredFileInfo);
}
ObjectStoreAddOrPutRequestOp::StoredFileInfo::StoredFileInfo(
SafeRefPtr<DatabaseFileInfo> aFileInfo,
nsCOMPtr<nsIInputStream> aInputStream)
: mFileInfo{WrapNotNull(std::move(aFileInfo))},
mFileActorOrInputStream{std::move(aInputStream)}
#ifdef DEBUG
,
mType{StructuredCloneFileBase::eStructuredClone}
#endif
{
AssertIsOnBackgroundThread();
AssertInvariants();
EnsureCipherKey();
MOZ_COUNT_CTOR(ObjectStoreAddOrPutRequestOp::StoredFileInfo);
}
ObjectStoreAddOrPutRequestOp::StoredFileInfo
ObjectStoreAddOrPutRequestOp::StoredFileInfo::CreateForBlob(
SafeRefPtr<DatabaseFileInfo> aFileInfo, RefPtr<DatabaseFile> aFileActor) {
return {std::move(aFileInfo), std::move(aFileActor)};
}
ObjectStoreAddOrPutRequestOp::StoredFileInfo
ObjectStoreAddOrPutRequestOp::StoredFileInfo::CreateForStructuredClone(
SafeRefPtr<DatabaseFileInfo> aFileInfo,
nsCOMPtr<nsIInputStream> aInputStream) {
return {std::move(aFileInfo), std::move(aInputStream)};
}
bool ObjectStoreAddOrPutRequestOp::StoredFileInfo::ShouldCompress() const {
// Must not be called after moving.
MOZ_ASSERT(IsValid());
// Compression is only necessary for eStructuredClone, i.e. when
// mFileActorOrInputStream stored an input stream. However, this is only
// called after GetInputStream, when mFileActorOrInputStream has been
// cleared, which is only possible for this type.
const bool res = !mFileActorOrInputStream;
MOZ_ASSERT(res == (StructuredCloneFileBase::eStructuredClone == mType));
return res;
}
void ObjectStoreAddOrPutRequestOp::StoredFileInfo::NotifyWriteSucceeded()
const {
MOZ_ASSERT(IsValid());
// For eBlob, clear the blob implementation.
if (mFileActorOrInputStream &&
mFileActorOrInputStream->is<RefPtr<DatabaseFile>>()) {
mFileActorOrInputStream->as<RefPtr<DatabaseFile>>()
->WriteSucceededClearBlobImpl();
}
// For the other types, no action is necessary.
}
ObjectStoreAddOrPutRequestOp::StoredFileInfo::InputStreamResult
ObjectStoreAddOrPutRequestOp::StoredFileInfo::GetInputStream() {
if (!mFileActorOrInputStream) {
MOZ_ASSERT(StructuredCloneFileBase::eStructuredClone == mType);
return nsCOMPtr<nsIInputStream>{};
}
// For the different cases, see also the comments in AssertInvariants.
return mFileActorOrInputStream->match(
[](const Nothing&) -> InputStreamResult {
return nsCOMPtr<nsIInputStream>{};
},
[](const RefPtr<DatabaseFile>& databaseActor) -> InputStreamResult {
ErrorResult rv;
auto inputStream = databaseActor->GetInputStream(rv);
if (NS_WARN_IF(rv.Failed())) {
return Err(rv.StealNSResult());
}
return inputStream;
},
[this](const nsCOMPtr<nsIInputStream>& inputStream) -> InputStreamResult {
auto res = inputStream;
// destroy() clears the inputStream parameter, so we needed to make a
// copy before
mFileActorOrInputStream.destroy();
AssertInvariants();
return res;
});
}
void ObjectStoreAddOrPutRequestOp::StoredFileInfo::Serialize(
nsString& aText) const {
AssertInvariants();
MOZ_ASSERT(IsValid());
const int64_t id = (*mFileInfo)->Id();
auto structuredCloneHandler = [&aText, id](const nsCOMPtr<nsIInputStream>&) {
// eStructuredClone
aText.Append('.');
aText.AppendInt(id);
};
// If mFileActorOrInputStream was moved, we had an inputStream before.
if (!mFileActorOrInputStream) {
structuredCloneHandler(nullptr);
return;
}
// This encoding is parsed in DeserializeStructuredCloneFile.
mFileActorOrInputStream->match(
[&aText, id](const Nothing&) {
// eMutableFile
aText.AppendInt(-id);
},
[&aText, id](const RefPtr<DatabaseFile>&) {
// eBlob
aText.AppendInt(id);
},
structuredCloneHandler);
}
class ObjectStoreAddOrPutRequestOp::SCInputStream final
: public nsIInputStream {
const JSStructuredCloneData& mData;
JSStructuredCloneData::Iterator mIter;
public:
explicit SCInputStream(const JSStructuredCloneData& aData)
: mData(aData), mIter(aData.Start()) {}
private:
virtual ~SCInputStream() = default;
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
};
class ObjectStoreGetRequestOp final : public NormalTransactionOp {
friend class TransactionBase;
const IndexOrObjectStoreId mObjectStoreId;
SafeRefPtr<Database> mDatabase;
const Maybe<SerializedKeyRange> mOptionalKeyRange;
AutoTArray<StructuredCloneReadInfoParent, 1> mResponse;
PBackgroundParent* mBackgroundParent;
uint32_t mPreprocessInfoCount;
const uint32_t mLimit;
const bool mGetAll;
private:
// Only created by TransactionBase.
ObjectStoreGetRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId,
const RequestParams& aParams, bool aGetAll);
~ObjectStoreGetRequestOp() override = default;
template <typename T>
mozilla::Result<T, nsresult> ConvertResponse(
StructuredCloneReadInfoParent&& aInfo);
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
bool HasPreprocessInfo() override;
mozilla::Result<PreprocessParams, nsresult> GetPreprocessParams() override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override;
};
class ObjectStoreGetKeyRequestOp final : public NormalTransactionOp {
friend class TransactionBase;
const IndexOrObjectStoreId mObjectStoreId;
const Maybe<SerializedKeyRange> mOptionalKeyRange;
const uint32_t mLimit;
const bool mGetAll;
nsTArray<Key> mResponse;
private:
// Only created by TransactionBase.
ObjectStoreGetKeyRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId,
const RequestParams& aParams, bool aGetAll);
~ObjectStoreGetKeyRequestOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override;
};
class ObjectStoreDeleteRequestOp final : public NormalTransactionOp {
friend class TransactionBase;
const ObjectStoreDeleteParams mParams;
ObjectStoreDeleteResponse mResponse;
bool mObjectStoreMayHaveIndexes;
private:
ObjectStoreDeleteRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId,
const ObjectStoreDeleteParams& aParams);
~ObjectStoreDeleteRequestOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override {
aResponse = std::move(mResponse);
*aResponseSize = 0;
}
};
class ObjectStoreClearRequestOp final : public NormalTransactionOp {
friend class TransactionBase;
const ObjectStoreClearParams mParams;
ObjectStoreClearResponse mResponse;
bool mObjectStoreMayHaveIndexes;
private:
ObjectStoreClearRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId,
const ObjectStoreClearParams& aParams);
~ObjectStoreClearRequestOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override {
aResponse = std::move(mResponse);
*aResponseSize = 0;
}
};
class ObjectStoreCountRequestOp final : public NormalTransactionOp {
friend class TransactionBase;
const ObjectStoreCountParams mParams;
ObjectStoreCountResponse mResponse;
private:
ObjectStoreCountRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId,
const ObjectStoreCountParams& aParams)
: NormalTransactionOp(std::move(aTransaction), aRequestId),
mParams(aParams) {}
~ObjectStoreCountRequestOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override {
aResponse = std::move(mResponse);
*aResponseSize = sizeof(uint64_t);
}
};
class IndexRequestOpBase : public NormalTransactionOp {
protected:
const SafeRefPtr<FullIndexMetadata> mMetadata;
protected:
IndexRequestOpBase(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId, const RequestParams& aParams)
: NormalTransactionOp(std::move(aTransaction), aRequestId),
mMetadata(IndexMetadataForParams(Transaction(), aParams)) {}
~IndexRequestOpBase() override = default;
private:
static SafeRefPtr<FullIndexMetadata> IndexMetadataForParams(
const TransactionBase& aTransaction, const RequestParams& aParams);
};
class IndexGetRequestOp final : public IndexRequestOpBase {
friend class TransactionBase;
SafeRefPtr<Database> mDatabase;
const Maybe<SerializedKeyRange> mOptionalKeyRange;
AutoTArray<StructuredCloneReadInfoParent, 1> mResponse;
PBackgroundParent* mBackgroundParent;
const uint32_t mLimit;
const bool mGetAll;
private:
// Only created by TransactionBase.
IndexGetRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId, const RequestParams& aParams,
bool aGetAll);
~IndexGetRequestOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override;
};
class IndexGetKeyRequestOp final : public IndexRequestOpBase {
friend class TransactionBase;
const Maybe<SerializedKeyRange> mOptionalKeyRange;
AutoTArray<Key, 1> mResponse;
const uint32_t mLimit;
const bool mGetAll;
private:
// Only created by TransactionBase.
IndexGetKeyRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId, const RequestParams& aParams,
bool aGetAll);
~IndexGetKeyRequestOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override;
};
class IndexCountRequestOp final : public IndexRequestOpBase {
friend class TransactionBase;
const IndexCountParams mParams;
IndexCountResponse mResponse;
private:
// Only created by TransactionBase.
IndexCountRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId, const RequestParams& aParams)
: IndexRequestOpBase(std::move(aTransaction), aRequestId, aParams),
mParams(aParams.get_IndexCountParams()) {}
~IndexCountRequestOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
void GetResponse(RequestResponse& aResponse, size_t* aResponseSize) override {
aResponse = std::move(mResponse);
*aResponseSize = sizeof(uint64_t);
}
};
template <IDBCursorType CursorType>
class Cursor;
constexpr IDBCursorType ToKeyOnlyType(const IDBCursorType aType) {
MOZ_ASSERT(aType == IDBCursorType::ObjectStore ||
aType == IDBCursorType::ObjectStoreKey ||
aType == IDBCursorType::Index || aType == IDBCursorType::IndexKey);
switch (aType) {
case IDBCursorType::ObjectStore:
[[fallthrough]];
case IDBCursorType::ObjectStoreKey:
return IDBCursorType::ObjectStoreKey;
case IDBCursorType::Index:
[[fallthrough]];
case IDBCursorType::IndexKey:
return IDBCursorType::IndexKey;
}
}
template <IDBCursorType CursorType>
using CursorPosition = CursorData<ToKeyOnlyType(CursorType)>;
#ifdef DEBUG
constexpr indexedDB::OpenCursorParams::Type ToOpenCursorParamsType(
const IDBCursorType aType) {
MOZ_ASSERT(aType == IDBCursorType::ObjectStore ||
aType == IDBCursorType::ObjectStoreKey ||
aType == IDBCursorType::Index || aType == IDBCursorType::IndexKey);
switch (aType) {
case IDBCursorType::ObjectStore:
return indexedDB::OpenCursorParams::TObjectStoreOpenCursorParams;
case IDBCursorType::ObjectStoreKey:
return indexedDB::OpenCursorParams::TObjectStoreOpenKeyCursorParams;
case IDBCursorType::Index:
return indexedDB::OpenCursorParams::TIndexOpenCursorParams;
case IDBCursorType::IndexKey:
return indexedDB::OpenCursorParams::TIndexOpenKeyCursorParams;
}
}
#endif
class CursorBase : public PBackgroundIDBCursorParent {
friend class TransactionBase;
template <IDBCursorType CursorType>
friend class CommonOpenOpHelper;
protected:
const SafeRefPtr<TransactionBase> mTransaction;
// This should only be touched on the PBackground thread to check whether
// the objectStore has been deleted. Holding these saves a hash lookup for
// every call to continue()/advance().
InitializedOnce<const NotNull<SafeRefPtr<FullObjectStoreMetadata>>>
mObjectStoreMetadata;
const IndexOrObjectStoreId mObjectStoreId;
LazyInitializedOnce<const Key>
mLocaleAwareRangeBound; ///< If the cursor is based on a key range, the
///< bound in the direction of iteration (e.g.
///< the upper bound in case of mDirection ==
///< NEXT). If the cursor is based on a key, it
///< is unset. If mLocale is set, this was
///< converted to mLocale.
const Direction mDirection;
const int32_t mMaxExtraCount;
const bool mIsSameProcessActor;
struct ConstructFromTransactionBase {};
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(mozilla::dom::indexedDB::CursorBase,
final)
CursorBase(SafeRefPtr<TransactionBase> aTransaction,
SafeRefPtr<FullObjectStoreMetadata> aObjectStoreMetadata,
Direction aDirection,
ConstructFromTransactionBase aConstructionTag);
protected:
// Reference counted.
~CursorBase() override { MOZ_ASSERT(!mObjectStoreMetadata); }
private:
virtual bool Start(const int64_t aRequestId,
const OpenCursorParams& aParams) = 0;
};
class IndexCursorBase : public CursorBase {
public:
bool IsLocaleAware() const { return !mLocale.IsEmpty(); }
IndexCursorBase(SafeRefPtr<TransactionBase> aTransaction,
SafeRefPtr<FullObjectStoreMetadata> aObjectStoreMetadata,
SafeRefPtr<FullIndexMetadata> aIndexMetadata,
Direction aDirection,
ConstructFromTransactionBase aConstructionTag)
: CursorBase{std::move(aTransaction), std::move(aObjectStoreMetadata),
aDirection, aConstructionTag},
mIndexMetadata(WrapNotNull(std::move(aIndexMetadata))),
mIndexId((*mIndexMetadata)->mCommonMetadata.id()),
mUniqueIndex((*mIndexMetadata)->mCommonMetadata.unique()),
mLocale((*mIndexMetadata)->mCommonMetadata.locale()) {}
protected:
IndexOrObjectStoreId Id() const { return mIndexId; }
// This should only be touched on the PBackground thread to check whether
// the index has been deleted. Holding these saves a hash lookup for every
// call to continue()/advance().
InitializedOnce<const NotNull<SafeRefPtr<FullIndexMetadata>>> mIndexMetadata;
const IndexOrObjectStoreId mIndexId;
const bool mUniqueIndex;
const nsCString
mLocale; ///< The locale if the cursor is locale-aware, otherwise empty.
struct ContinueQueries {
nsCString mContinueQuery;
nsCString mContinueToQuery;
nsCString mContinuePrimaryKeyQuery;
const nsACString& GetContinueQuery(const bool hasContinueKey,
const bool hasContinuePrimaryKey) const {
return hasContinuePrimaryKey ? mContinuePrimaryKeyQuery
: hasContinueKey ? mContinueToQuery
: mContinueQuery;
}
};
};
class ObjectStoreCursorBase : public CursorBase {
public:
using CursorBase::CursorBase;
static constexpr bool IsLocaleAware() { return false; }
protected:
IndexOrObjectStoreId Id() const { return mObjectStoreId; }
struct ContinueQueries {
nsCString mContinueQuery;
nsCString mContinueToQuery;
const nsACString& GetContinueQuery(const bool hasContinueKey,
const bool hasContinuePrimaryKey) const {
MOZ_ASSERT(!hasContinuePrimaryKey);
return hasContinueKey ? mContinueToQuery : mContinueQuery;
}
};
};
using FilesArray = nsTArray<nsTArray<StructuredCloneFileParent>>;
struct PseudoFilesArray {
static constexpr bool IsEmpty() { return true; }
static constexpr void Clear() {}
};
template <IDBCursorType CursorType>
using FilesArrayT =
std::conditional_t<!CursorTypeTraits<CursorType>::IsKeyOnlyCursor,
FilesArray, PseudoFilesArray>;
class ValueCursorBase {
friend struct ValuePopulateResponseHelper<true>;
friend struct ValuePopulateResponseHelper<false>;
protected:
explicit ValueCursorBase(TransactionBase* const aTransaction)
: mDatabase(aTransaction->GetDatabasePtr()),
mFileManager(mDatabase->GetFileManagerPtr()),
mBackgroundParent(WrapNotNull(aTransaction->GetBackgroundParent())) {
MOZ_ASSERT(mDatabase);
}
void ProcessFiles(CursorResponse& aResponse, const FilesArray& aFiles);
~ValueCursorBase() { MOZ_ASSERT(!mBackgroundParent); }
const SafeRefPtr<Database> mDatabase;
const NotNull<SafeRefPtr<DatabaseFileManager>> mFileManager;
InitializedOnce<const NotNull<PBackgroundParent*>> mBackgroundParent;
};
class KeyCursorBase {
protected:
explicit KeyCursorBase(TransactionBase* const /*aTransaction*/) {}
static constexpr void ProcessFiles(CursorResponse& aResponse,
const PseudoFilesArray& aFiles) {}
};
template <IDBCursorType CursorType>
class CursorOpBaseHelperBase;
template <IDBCursorType CursorType>
class Cursor final
: public std::conditional_t<
CursorTypeTraits<CursorType>::IsObjectStoreCursor,
ObjectStoreCursorBase, IndexCursorBase>,
public std::conditional_t<CursorTypeTraits<CursorType>::IsKeyOnlyCursor,
KeyCursorBase, ValueCursorBase> {
using Base =
std::conditional_t<CursorTypeTraits<CursorType>::IsObjectStoreCursor,
ObjectStoreCursorBase, IndexCursorBase>;
using KeyValueBase =
std::conditional_t<CursorTypeTraits<CursorType>::IsKeyOnlyCursor,
KeyCursorBase, ValueCursorBase>;
static constexpr bool IsIndexCursor =
!CursorTypeTraits<CursorType>::IsObjectStoreCursor;
static constexpr bool IsValueCursor =
!CursorTypeTraits<CursorType>::IsKeyOnlyCursor;
class CursorOpBase;
class OpenOp;
class ContinueOp;
using Base::Id;
using CursorBase::Manager;
using CursorBase::mDirection;
using CursorBase::mObjectStoreId;
using CursorBase::mTransaction;
using typename CursorBase::ActorDestroyReason;
using TypedOpenOpHelper =
std::conditional_t<IsIndexCursor, IndexOpenOpHelper<CursorType>,
ObjectStoreOpenOpHelper<CursorType>>;
friend class CursorOpBaseHelperBase<CursorType>;
friend class CommonOpenOpHelper<CursorType>;
friend TypedOpenOpHelper;
friend class OpenOpHelper<CursorType>;
CursorOpBase* mCurrentlyRunningOp = nullptr;
LazyInitializedOnce<const typename Base::ContinueQueries> mContinueQueries;
// Only called by TransactionBase.
bool Start(const int64_t aRequestId, const OpenCursorParams& aParams) final;
void SendResponseInternal(CursorResponse& aResponse,
const FilesArrayT<CursorType>& aFiles);
// Must call SendResponseInternal!
bool SendResponse(const CursorResponse& aResponse) = delete;
// IPDL methods.
void ActorDestroy(ActorDestroyReason aWhy) override;
mozilla::ipc::IPCResult RecvDeleteMe() override;
mozilla::ipc::IPCResult RecvContinue(
const int64_t& aRequestId, const CursorRequestParams& aParams,
const Key& aCurrentKey, const Key& aCurrentObjectStoreKey) override;
public:
Cursor(SafeRefPtr<TransactionBase> aTransaction,
SafeRefPtr<FullObjectStoreMetadata> aObjectStoreMetadata,
SafeRefPtr<FullIndexMetadata> aIndexMetadata,
typename Base::Direction aDirection,
typename Base::ConstructFromTransactionBase aConstructionTag)
: Base{std::move(aTransaction), std::move(aObjectStoreMetadata),
std::move(aIndexMetadata), aDirection, aConstructionTag},
KeyValueBase{this->mTransaction.unsafeGetRawPtr()} {}
Cursor(SafeRefPtr<TransactionBase> aTransaction,
SafeRefPtr<FullObjectStoreMetadata> aObjectStoreMetadata,
typename Base::Direction aDirection,
typename Base::ConstructFromTransactionBase aConstructionTag)
: Base{std::move(aTransaction), std::move(aObjectStoreMetadata),
aDirection, aConstructionTag},
KeyValueBase{this->mTransaction.unsafeGetRawPtr()} {}
private:
void SetOptionalKeyRange(const Maybe<SerializedKeyRange>& aOptionalKeyRange,
bool* aOpen);
bool VerifyRequestParams(const CursorRequestParams& aParams,
const CursorPosition<CursorType>& aPosition) const;
~Cursor() final = default;
};
template <IDBCursorType CursorType>
class Cursor<CursorType>::CursorOpBase
: public TransactionDatabaseOperationBase {
friend class CursorOpBaseHelperBase<CursorType>;
protected:
RefPtr<Cursor> mCursor;
FilesArrayT<CursorType> mFiles; // TODO: Consider removing this member
// entirely if we are no value cursor.
CursorResponse mResponse;
#ifdef DEBUG
bool mResponseSent;
#endif
protected:
explicit CursorOpBase(Cursor* aCursor, const int64_t aRequestId)
: TransactionDatabaseOperationBase(aCursor->mTransaction.clonePtr(),
/* aRequestId */ aRequestId),
mCursor(aCursor)
#ifdef DEBUG
,
mResponseSent(false)
#endif
{
AssertIsOnBackgroundThread();
MOZ_ASSERT(aCursor);
}
~CursorOpBase() override = default;
bool SendFailureResult(nsresult aResultCode) final;
nsresult SendSuccessResult() final;
void Cleanup() override;
};
template <IDBCursorType CursorType>
class OpenOpHelper;
using ResponseSizeOrError = Result<size_t, nsresult>;
template <IDBCursorType CursorType>
class CursorOpBaseHelperBase {
public:
explicit CursorOpBaseHelperBase(
typename Cursor<CursorType>::CursorOpBase& aOp)
: mOp{aOp} {}
ResponseSizeOrError PopulateResponseFromStatement(mozIStorageStatement* aStmt,
bool aInitializeResponse,
Key* const aOptOutSortKey);
void PopulateExtraResponses(mozIStorageStatement* aStmt,
uint32_t aMaxExtraCount,
const size_t aInitialResponseSize,
const nsACString& aOperation,
Key* const aOptPreviousSortKey);
protected:
Cursor<CursorType>& GetCursor() {
MOZ_ASSERT(mOp.mCursor);
return *mOp.mCursor;
}
void SetResponse(CursorResponse aResponse) {
mOp.mResponse = std::move(aResponse);
}
protected:
typename Cursor<CursorType>::CursorOpBase& mOp;
};
class CommonOpenOpHelperBase {
protected:
static void AppendConditionClause(const nsACString& aColumnName,
const nsACString& aStatementParameterName,
bool aLessThan, bool aEquals,
nsCString& aResult);
};
template <IDBCursorType CursorType>
class CommonOpenOpHelper : public CursorOpBaseHelperBase<CursorType>,
protected CommonOpenOpHelperBase {
public:
explicit CommonOpenOpHelper(typename Cursor<CursorType>::OpenOp& aOp)
: CursorOpBaseHelperBase<CursorType>{aOp} {}
protected:
using CursorOpBaseHelperBase<CursorType>::GetCursor;
using CursorOpBaseHelperBase<CursorType>::PopulateExtraResponses;
using CursorOpBaseHelperBase<CursorType>::PopulateResponseFromStatement;
using CursorOpBaseHelperBase<CursorType>::SetResponse;
const Maybe<SerializedKeyRange>& GetOptionalKeyRange() const {
// This downcast is safe, since we initialized mOp from an OpenOp in the
// ctor.
return static_cast<typename Cursor<CursorType>::OpenOp&>(this->mOp)
.mOptionalKeyRange;
}
nsresult ProcessStatementSteps(mozIStorageStatement* aStmt);
};
template <IDBCursorType CursorType>
class ObjectStoreOpenOpHelper : protected CommonOpenOpHelper<CursorType> {
public:
using CommonOpenOpHelper<CursorType>::CommonOpenOpHelper;
protected:
using CommonOpenOpHelper<CursorType>::GetCursor;
using CommonOpenOpHelper<CursorType>::GetOptionalKeyRange;
using CommonOpenOpHelper<CursorType>::AppendConditionClause;
void PrepareKeyConditionClauses(const nsACString& aDirectionClause,
const nsACString& aQueryStart);
};
template <IDBCursorType CursorType>
class IndexOpenOpHelper : protected CommonOpenOpHelper<CursorType> {
public:
using CommonOpenOpHelper<CursorType>::CommonOpenOpHelper;
protected:
using CommonOpenOpHelper<CursorType>::GetCursor;
using CommonOpenOpHelper<CursorType>::GetOptionalKeyRange;
using CommonOpenOpHelper<CursorType>::AppendConditionClause;
void PrepareIndexKeyConditionClause(
const nsACString& aDirectionClause,
const nsLiteralCString& aObjectDataKeyPrefix, nsAutoCString aQueryStart);
};
template <>
class OpenOpHelper<IDBCursorType::ObjectStore>
: public ObjectStoreOpenOpHelper<IDBCursorType::ObjectStore> {
public:
using ObjectStoreOpenOpHelper<
IDBCursorType::ObjectStore>::ObjectStoreOpenOpHelper;
nsresult DoDatabaseWork(DatabaseConnection* aConnection);
};
template <>
class OpenOpHelper<IDBCursorType::ObjectStoreKey>
: public ObjectStoreOpenOpHelper<IDBCursorType::ObjectStoreKey> {
public:
using ObjectStoreOpenOpHelper<
IDBCursorType::ObjectStoreKey>::ObjectStoreOpenOpHelper;
nsresult DoDatabaseWork(DatabaseConnection* aConnection);
};
template <>
class OpenOpHelper<IDBCursorType::Index>
: IndexOpenOpHelper<IDBCursorType::Index> {
private:
void PrepareKeyConditionClauses(const nsACString& aDirectionClause,
nsAutoCString aQueryStart) {
PrepareIndexKeyConditionClause(aDirectionClause, "index_table."_ns,
std::move(aQueryStart));
}
public:
using IndexOpenOpHelper<IDBCursorType::Index>::IndexOpenOpHelper;
nsresult DoDatabaseWork(DatabaseConnection* aConnection);
};
template <>
class OpenOpHelper<IDBCursorType::IndexKey>
: IndexOpenOpHelper<IDBCursorType::IndexKey> {
private:
void PrepareKeyConditionClauses(const nsACString& aDirectionClause,
nsAutoCString aQueryStart) {
PrepareIndexKeyConditionClause(aDirectionClause, ""_ns,
std::move(aQueryStart));
}
public:
using IndexOpenOpHelper<IDBCursorType::IndexKey>::IndexOpenOpHelper;
nsresult DoDatabaseWork(DatabaseConnection* aConnection);
};
template <IDBCursorType CursorType>
class Cursor<CursorType>::OpenOp final : public CursorOpBase {
friend class Cursor<CursorType>;
friend class CommonOpenOpHelper<CursorType>;
const Maybe<SerializedKeyRange> mOptionalKeyRange;
using CursorOpBase::mCursor;
using CursorOpBase::mResponse;
// Only created by Cursor.
OpenOp(Cursor* const aCursor, const int64_t aRequestId,
const Maybe<SerializedKeyRange>& aOptionalKeyRange)
: CursorOpBase(aCursor, aRequestId),
mOptionalKeyRange(aOptionalKeyRange) {}
// Reference counted.
~OpenOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
};
template <IDBCursorType CursorType>
class Cursor<CursorType>::ContinueOp final
: public Cursor<CursorType>::CursorOpBase {
friend class Cursor<CursorType>;
using CursorOpBase::mCursor;
using CursorOpBase::mResponse;
const CursorRequestParams mParams;
// Only created by Cursor.
ContinueOp(Cursor* const aCursor, int64_t aRequestId,
CursorRequestParams aParams, CursorPosition<CursorType> aPosition)
: CursorOpBase(aCursor, aRequestId),
mParams(std::move(aParams)),
mCurrentPosition{std::move(aPosition)} {
MOZ_ASSERT(mParams.type() != CursorRequestParams::T__None);
}
// Reference counted.
~ContinueOp() override = default;
nsresult DoDatabaseWork(DatabaseConnection* aConnection) override;
const CursorPosition<CursorType> mCurrentPosition;
};
class Utils final : public PBackgroundIndexedDBUtilsParent {
#ifdef DEBUG
bool mActorDestroyed;
#endif
public:
Utils();
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(mozilla::dom::indexedDB::Utils)
private:
// Reference counted.
~Utils() override;
// IPDL methods are only called by IPDL.
void ActorDestroy(ActorDestroyReason aWhy) override;
mozilla::ipc::IPCResult RecvDeleteMe() override;
mozilla::ipc::IPCResult RecvGetFileReferences(
const PersistenceType& aPersistenceType, const nsACString& aOrigin,
const nsAString& aDatabaseName, const int64_t& aFileId, int32_t* aRefCnt,
int32_t* aDBRefCnt, bool* aResult) override;
mozilla::ipc::IPCResult RecvDoMaintenance(
DoMaintenanceResolver&& aResolver) override;
};
/*******************************************************************************
* Other class declarations
******************************************************************************/
struct DatabaseActorInfo final {
friend class mozilla::DefaultDelete<DatabaseActorInfo>;
SafeRefPtr<FullDatabaseMetadata> mMetadata;
// We don't use LinkedList<CheckedUnsafePtr<Database>> because
// CheckedUnsafePtr is not suitable for use within LinkedList. While it's
// theoretically possible to adapt LinkedList to support it, doing so would
// introduce unnecessary overhead. Instead, we use a simpler and more
// efficient approach. Each Database instance asserts !isInList() in its
// destructor to catch dangling pointer issues.
LinkedList<Database> mLiveDatabases;
RefPtr<FactoryOp> mWaitingFactoryOp;
DatabaseActorInfo(SafeRefPtr<FullDatabaseMetadata> aMetadata,
NotNull<Database*> aDatabase)
: mMetadata(std::move(aMetadata)) {
MOZ_COUNT_CTOR(DatabaseActorInfo);
mLiveDatabases.insertBack(aDatabase);
}
private:
~DatabaseActorInfo() {
MOZ_ASSERT(mLiveDatabases.isEmpty());
MOZ_ASSERT(!mWaitingFactoryOp || !mWaitingFactoryOp->HasBlockedDatabases());
MOZ_COUNT_DTOR(DatabaseActorInfo);
}
};
class DatabaseLoggingInfo final {
#ifdef DEBUG
// Just for potential warnings.
friend class Factory;
#endif
LoggingInfo mLoggingInfo;
public:
explicit DatabaseLoggingInfo(const LoggingInfo& aLoggingInfo)
: mLoggingInfo(aLoggingInfo) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aLoggingInfo.nextTransactionSerialNumber());
MOZ_ASSERT(aLoggingInfo.nextVersionChangeTransactionSerialNumber());
MOZ_ASSERT(aLoggingInfo.nextRequestSerialNumber());
}
const nsID& Id() const {
AssertIsOnBackgroundThread();
return mLoggingInfo.backgroundChildLoggingId();
}
int64_t NextTransactionSN(IDBTransaction::Mode aMode) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mLoggingInfo.nextTransactionSerialNumber() < INT64_MAX);
MOZ_ASSERT(mLoggingInfo.nextVersionChangeTransactionSerialNumber() >
INT64_MIN);
if (aMode == IDBTransaction::Mode::VersionChange) {
return mLoggingInfo.nextVersionChangeTransactionSerialNumber()--;
}
return mLoggingInfo.nextTransactionSerialNumber()++;
}
uint64_t NextRequestSN() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mLoggingInfo.nextRequestSerialNumber() < UINT64_MAX);
return mLoggingInfo.nextRequestSerialNumber()++;
}
NS_INLINE_DECL_REFCOUNTING(DatabaseLoggingInfo)
private:
~DatabaseLoggingInfo();
};
class QuotaClient final : public mozilla::dom::quota::Client {
friend class GetDatabasesOp;
static QuotaClient* sInstance;
nsCOMPtr<nsIEventTarget> mBackgroundThread;
nsCOMPtr<nsITimer> mDeleteTimer;
nsTArray<RefPtr<Maintenance>> mMaintenanceQueue;
RefPtr<Maintenance> mCurrentMaintenance;
RefPtr<nsThreadPool> mMaintenanceThreadPool;
nsClassHashtable<nsRefPtrHashKey<DatabaseFileManager>, nsTArray<int64_t>>
mPendingDeleteInfos;
public:
QuotaClient();
static QuotaClient* GetInstance() {
AssertIsOnBackgroundThread();
return sInstance;
}
nsIEventTarget* BackgroundThread() const {
MOZ_ASSERT(mBackgroundThread);
return mBackgroundThread;
}
nsresult AsyncDeleteFile(DatabaseFileManager* aFileManager, int64_t aFileId);
nsresult FlushPendingFileDeletions();
RefPtr<BoolPromise> DoMaintenance();
RefPtr<Maintenance> GetCurrentMaintenance() const {
return mCurrentMaintenance;
}
void NoteFinishedMaintenance(Maintenance* aMaintenance) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aMaintenance);
MOZ_ASSERT(mCurrentMaintenance == aMaintenance);
mCurrentMaintenance = nullptr;
QuotaManager::MaybeRecordQuotaClientShutdownStep(quota::Client::IDB,
"Maintenance finished"_ns);
ProcessMaintenanceQueue();
}
nsThreadPool* GetOrCreateThreadPool();
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(mozilla::dom::indexedDB::QuotaClient,
override)
mozilla::dom::quota::Client::Type GetType() override;
nsresult UpgradeStorageFrom1_0To2_0(nsIFile* aDirectory) override;
nsresult UpgradeStorageFrom2_1To2_2(nsIFile* aDirectory) override;
Result<UsageInfo, nsresult> InitOrigin(PersistenceType aPersistenceType,
const OriginMetadata& aOriginMetadata,
const AtomicBool& aCanceled) override;
nsresult InitOriginWithoutTracking(PersistenceType aPersistenceType,
const OriginMetadata& aOriginMetadata,
const AtomicBool& aCanceled) override;
Result<UsageInfo, nsresult> GetUsageForOrigin(
PersistenceType aPersistenceType, const OriginMetadata& aOriginMetadata,
const AtomicBool& aCanceled) override;
void OnOriginClearCompleted(const OriginMetadata& aOriginMetadata) override;
void OnRepositoryClearCompleted(PersistenceType aPersistenceType) override;
void ReleaseIOThreadObjects() override;
void AbortOperationsForLocks(
const DirectoryLockIdTable& aDirectoryLockIds) override;
void AbortOperationsForProcess(ContentParentId aContentParentId) override;
void AbortAllOperations() override;
void StartIdleMaintenance() override;
void StopIdleMaintenance() override;
private:
~QuotaClient() override;
void InitiateShutdown() override;
bool IsShutdownCompleted() const override;
nsCString GetShutdownStatus() const override;
void ForceKillActors() override;
void FinalizeShutdown() override;
static void DeleteTimerCallback(nsITimer* aTimer, void* aClosure);
void AbortAllMaintenances();
Result<nsCOMPtr<nsIFile>, nsresult> GetDirectory(
const OriginMetadata& aOriginMetadata);
struct SubdirectoriesToProcessAndDatabaseFilenames {
AutoTArray<nsString, 20> subdirsToProcess;
nsTHashSet<nsString> databaseFilenames{20};
};
struct SubdirectoriesToProcessAndDatabaseFilenamesAndObsoleteFilenames {
AutoTArray<nsString, 20> subdirsToProcess;
nsTHashSet<nsString> databaseFilenames{20};
nsTHashSet<nsString> obsoleteFilenames{20};
};
enum class ObsoleteFilenamesHandling { Include, Omit };
template <ObsoleteFilenamesHandling ObsoleteFilenames>
using GetDatabaseFilenamesResult = std::conditional_t<
ObsoleteFilenames == ObsoleteFilenamesHandling::Include,
SubdirectoriesToProcessAndDatabaseFilenamesAndObsoleteFilenames,
SubdirectoriesToProcessAndDatabaseFilenames>;
// Returns a two-part or three-part structure:
//
// The first part is an array of subdirectories to process.
//
// The second part is a hashtable of database filenames.
//
// When ObsoleteFilenames is ObsoleteFilenamesHandling::Include, will also
// collect files based on the marker files. For now,
// GetUsageForOriginInternal() is the only consumer of this result because it
// checks those unfinished deletion and clean them up after that.
template <ObsoleteFilenamesHandling ObsoleteFilenames =
ObsoleteFilenamesHandling::Omit>
Result<GetDatabaseFilenamesResult<ObsoleteFilenames>,
nsresult> static GetDatabaseFilenames(nsIFile& aDirectory,
const AtomicBool& aCanceled);
nsresult GetUsageForOriginInternal(PersistenceType aPersistenceType,
const OriginMetadata& aOriginMetadata,
const AtomicBool& aCanceled,
bool aInitializing, UsageInfo* aUsageInfo);
// Runs on the PBackground thread. Checks to see if there's a queued
// Maintenance to run.
void ProcessMaintenanceQueue();
};
class DeleteFilesRunnable final : public Runnable {
using ClientDirectoryLock = mozilla::dom::quota::ClientDirectoryLock;
enum State {
// Just created on the PBackground thread. Next step is
// State_DirectoryOpenPending.
State_Initial,
// Waiting for directory open allowed on the main thread. The next step is
// State_DatabaseWorkOpen.
State_DirectoryOpenPending,
// Waiting to do/doing work on the QuotaManager IO thread. The next step is
// State_UnblockingOpen.
State_DatabaseWorkOpen,
// Notifying the QuotaManager that it can proceed to the next operation on
// the main thread. Next step is State_Completed.
State_UnblockingOpen,
// All done.
State_Completed
};
nsCOMPtr<nsIEventTarget> mOwningEventTarget;
SafeRefPtr<DatabaseFileManager> mFileManager;
ClientDirectoryLockHandle mDirectoryLockHandle;
nsTArray<int64_t> mFileIds;
State mState;
DEBUGONLY(bool mDEBUGCountsAsPending = false);
static uint64_t sPendingRunnables;
public:
DeleteFilesRunnable(SafeRefPtr<DatabaseFileManager> aFileManager,
nsTArray<int64_t>&& aFileIds);
void RunImmediately();
static bool IsDeletionPending() { return sPendingRunnables > 0; }
private:
#ifdef DEBUG
~DeleteFilesRunnable();
#else
~DeleteFilesRunnable() = default;
#endif
void Open();
void DoDatabaseWork();
void Finish();
void UnblockOpen();
NS_DECL_NSIRUNNABLE
void DirectoryLockAcquired(ClientDirectoryLockHandle aLockHandle);
void DirectoryLockFailed();
};
class Maintenance final : public Runnable {
struct DirectoryInfo final {
InitializedOnce<const OriginMetadata> mOriginMetadata;
InitializedOnce<const nsTArray<nsString>> mDatabasePaths;
const PersistenceType mPersistenceType;
DirectoryInfo(PersistenceType aPersistenceType,
OriginMetadata aOriginMetadata,
nsTArray<nsString>&& aDatabasePaths);
DirectoryInfo(const DirectoryInfo& aOther) = delete;
DirectoryInfo(DirectoryInfo&& aOther) = delete;
~DirectoryInfo() { MOZ_COUNT_DTOR(Maintenance::DirectoryInfo); }
};
enum class State {
// Newly created on the PBackground thread. Will proceed immediately or be
// added to the maintenance queue. The next step is either
// DirectoryOpenPending if IndexedDatabaseManager is running, or
// CreateIndexedDatabaseManager if not.
Initial = 0,
// Create IndexedDatabaseManager on the main thread. The next step is either
// Finishing if IndexedDatabaseManager initialization fails, or
// IndexedDatabaseManagerOpen if initialization succeeds.
CreateIndexedDatabaseManager,
// Call OpenDirectory() on the PBackground thread. The next step is
// DirectoryOpenPending.
IndexedDatabaseManagerOpen,
// Waiting for directory open allowed on the PBackground thread. The next
// step is either Finishing if directory lock failed to acquire, or
// DirectoryWorkOpen if directory lock is acquired.
DirectoryOpenPending,
// Waiting to do/doing work on the QuotaManager IO thread. The next step is
// BeginDatabaseMaintenance.
DirectoryWorkOpen,
// Dispatching a runnable for each database on the PBackground thread. The
// next state is either WaitingForDatabaseMaintenancesToComplete if at least
// one runnable has been dispatched, or Finishing otherwise.
BeginDatabaseMaintenance,
// Waiting for DatabaseMaintenance to finish on maintenance thread pool.
// The next state is Finishing if the last runnable has finished.
WaitingForDatabaseMaintenancesToComplete,
// Waiting to finish/finishing on the PBackground thread. The next step is
// Completed.
Finishing,
// All done.
Complete
};
RefPtr<QuotaClient> mQuotaClient;
MozPromiseHolder<BoolPromise> mPromiseHolder;
PRTime mStartTime;
RefPtr<UniversalDirectoryLock> mPendingDirectoryLock;
// The directory lock is normally dropped by BeginDatabaseMaintenance, but if
// something fails (in any method), the Finish method will do the cleanup.
RefPtr<UniversalDirectoryLock> mDirectoryLock;
nsTArray<nsCOMPtr<nsIRunnable>> mCompleteCallbacks;
nsTArray<DirectoryInfo> mDirectoryInfos;
nsTHashMap<nsStringHashKey, DatabaseMaintenance*> mDatabaseMaintenances;
nsresult mResultCode;
Atomic<bool> mAborted;
bool mOpenStorageForAllRepositoriesFailed;
State mState;
public:
explicit Maintenance(QuotaClient* aQuotaClient)
: Runnable("dom::indexedDB::Maintenance"),
mQuotaClient(aQuotaClient),
mStartTime(PR_Now()),
mResultCode(NS_OK),
mAborted(false),
mOpenStorageForAllRepositoriesFailed(false),
mState(State::Initial) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aQuotaClient);
MOZ_ASSERT(QuotaClient::GetInstance() == aQuotaClient);
MOZ_ASSERT(mStartTime);
}
nsIEventTarget* BackgroundThread() const {
MOZ_ASSERT(mQuotaClient);
return mQuotaClient->BackgroundThread();
}
PRTime StartTime() const { return mStartTime; }
bool IsAborted() const { return mAborted; }
void RunImmediately() {
MOZ_ASSERT(mState == State::Initial);
Unused << this->Run();
}
RefPtr<BoolPromise> OnResults() {
AssertIsOnBackgroundThread();
return mPromiseHolder.Ensure(__func__);
}
void Abort();
void RegisterDatabaseMaintenance(DatabaseMaintenance* aDatabaseMaintenance);
void UnregisterDatabaseMaintenance(DatabaseMaintenance* aDatabaseMaintenance);
bool HasDatabaseMaintenances() const { return mDatabaseMaintenances.Count(); }
RefPtr<DatabaseMaintenance> GetDatabaseMaintenance(
const nsAString& aDatabasePath) const {
AssertIsOnBackgroundThread();
return mDatabaseMaintenances.Get(aDatabasePath);
}
void WaitForCompletion(nsIRunnable* aCallback) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mDatabaseMaintenances.Count());
mCompleteCallbacks.AppendElement(aCallback);
}
void Stringify(nsACString& aResult) const;
private:
~Maintenance() override {
MOZ_ASSERT(mState == State::Complete);
MOZ_ASSERT(!mDatabaseMaintenances.Count());
}
// Runs on the PBackground thread. Checks if IndexedDatabaseManager is
// running. Calls OpenDirectory() or dispatches to the main thread on which
// CreateIndexedDatabaseManager() is called.
nsresult Start();
// Runs on the main thread. Once IndexedDatabaseManager is created it will
// dispatch to the PBackground thread on which OpenDirectory() is called.
nsresult CreateIndexedDatabaseManager();
RefPtr<UniversalDirectoryLockPromise> OpenStorageDirectory(
const PersistenceScope& aPersistenceScope, bool aInitializeOrigins);
// Runs on the PBackground thread. Once QuotaManager has given a lock it will
// call DirectoryOpen().
nsresult OpenDirectory();
// Runs on the PBackground thread. Dispatches to the QuotaManager I/O thread.
nsresult DirectoryOpen();
// Runs on the QuotaManager I/O thread. Once it finds databases it will
// dispatch to the PBackground thread on which BeginDatabaseMaintenance()
// is called.
nsresult DirectoryWork();
// Runs on the PBackground thread. It dispatches a runnable for each database.
nsresult BeginDatabaseMaintenance();
// Runs on the PBackground thread. Called when the maintenance is finished or
// if any of above methods fails.
void Finish();
NS_DECL_NSIRUNNABLE
void DirectoryLockAcquired(UniversalDirectoryLock* aLock);
void DirectoryLockFailed();
};
Maintenance::DirectoryInfo::DirectoryInfo(PersistenceType aPersistenceType,
OriginMetadata aOriginMetadata,
nsTArray<nsString>&& aDatabasePaths)
: mOriginMetadata(std::move(aOriginMetadata)),
mDatabasePaths(std::move(aDatabasePaths)),
mPersistenceType(aPersistenceType) {
MOZ_ASSERT(aPersistenceType != PERSISTENCE_TYPE_INVALID);
MOZ_ASSERT(!mOriginMetadata->mGroup.IsEmpty());
MOZ_ASSERT(!mOriginMetadata->mOrigin.IsEmpty());
#ifdef DEBUG
MOZ_ASSERT(!mDatabasePaths->IsEmpty());
for (const nsAString& databasePath : *mDatabasePaths) {
MOZ_ASSERT(!databasePath.IsEmpty());
}
#endif
MOZ_COUNT_CTOR(Maintenance::DirectoryInfo);
}
class DatabaseMaintenance final : public Runnable {
// The minimum amount of time that has passed since the last vacuum before we
// will attempt to analyze the database for fragmentation.
static const PRTime kMinVacuumAge =
PRTime(PR_USEC_PER_SEC) * 60 * 60 * 24 * 7;
// If the percent of database pages that are not in contiguous order is higher
// than this percentage we will attempt a vacuum.
static const int32_t kPercentUnorderedThreshold = 30;
// If the percent of file size growth since the last vacuum is higher than
// this percentage we will attempt a vacuum.
static const int32_t kPercentFileSizeGrowthThreshold = 10;
// The number of freelist pages beyond which we will favor an incremental
// vacuum over a full vacuum.
static const int32_t kMaxFreelistThreshold = 5;
// If the percent of unused file bytes in the database exceeds this percentage
// then we will attempt a full vacuum.
static const int32_t kPercentUnusedThreshold = 20;
enum class MaintenanceAction { Nothing = 0, IncrementalVacuum, FullVacuum };
RefPtr<Maintenance> mMaintenance;
// The directory lock is dropped in RunOnOwningThread which serves as a
// cleanup method and is always called.
RefPtr<ClientDirectoryLock> mDirectoryLock;
const OriginMetadata mOriginMetadata;
const nsString mDatabasePath;
int64_t mDirectoryLockId;
nsCOMPtr<nsIRunnable> mCompleteCallback;
const PersistenceType mPersistenceType;
const Maybe<CipherKey> mMaybeKey;
Atomic<bool> mAborted;
DataMutex<nsCOMPtr<mozIStorageConnection>> mSharedStorageConnection;
public:
DatabaseMaintenance(Maintenance* aMaintenance,
RefPtr<ClientDirectoryLock> aDirectoryLock,
PersistenceType aPersistenceType,
const OriginMetadata& aOriginMetadata,
const nsAString& aDatabasePath,
const Maybe<CipherKey>& aMaybeKey)
: Runnable("dom::indexedDB::DatabaseMaintenance"),
mMaintenance(aMaintenance),
mDirectoryLock(std::move(aDirectoryLock)),
mOriginMetadata(aOriginMetadata),
mDatabasePath(aDatabasePath),
mPersistenceType(aPersistenceType),
mMaybeKey{aMaybeKey},
mAborted(false),
mSharedStorageConnection("sharedStorageConnection") {
MOZ_ASSERT(mDirectoryLock);
MOZ_ASSERT(mDirectoryLock->Id() >= 0);
mDirectoryLockId = mDirectoryLock->Id();
}
const nsAString& DatabasePath() const { return mDatabasePath; }
void WaitForCompletion(nsIRunnable* aCallback) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mCompleteCallback);
mCompleteCallback = aCallback;
}
void Stringify(nsACString& aResult) const;
nsresult Abort();
private:
~DatabaseMaintenance() override = default;
// Runs on maintenance thread pool. Does maintenance on the database.
void PerformMaintenanceOnDatabase();
// Runs on maintenance thread pool as part of PerformMaintenanceOnDatabase.
nsresult CheckIntegrity(mozIStorageConnection& aConnection, bool* aOk);
// Runs on maintenance thread pool as part of PerformMaintenanceOnDatabase.
nsresult DetermineMaintenanceAction(mozIStorageConnection& aConnection,
nsIFile* aDatabaseFile,
MaintenanceAction* aMaintenanceAction);
// Runs on maintenance thread pool as part of PerformMaintenanceOnDatabase.
void IncrementalVacuum(mozIStorageConnection& aConnection);
// Runs on maintenance thread pool as part of PerformMaintenanceOnDatabase.
void FullVacuum(mozIStorageConnection& aConnection, nsIFile* aDatabaseFile);
// Runs on the PBackground thread. It dispatches a complete callback and
// unregisters from Maintenance.
void RunOnOwningThread();
// Runs on maintenance thread pool. Once it performs database maintenance
// it will dispatch to the PBackground thread on which RunOnOwningThread()
// is called.
void RunOnConnectionThread();
// TODO: Could QuotaClient::IsShuttingDownOnNonBackgroundThread() call
// be part of mMaintenance::IsAborted() ?
inline bool IsAborted() const {
return mMaintenance->IsAborted() || mAborted ||
NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread());
}
NS_DECL_NSIRUNNABLE
};
#ifdef DEBUG
class DEBUGThreadSlower final : public nsIThreadObserver {
public:
DEBUGThreadSlower() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(kDEBUGThreadSleepMS);
}
NS_DECL_ISUPPORTS
private:
~DEBUGThreadSlower() { AssertIsOnBackgroundThread(); }
NS_DECL_NSITHREADOBSERVER
};
#endif // DEBUG
/*******************************************************************************
* Helper classes
******************************************************************************/
// XXX Get rid of FileHelper and move the functions into DatabaseFileManager.
// Then, DatabaseFileManager::Get(Journal)Directory and
// DatabaseFileManager::GetFileForId might eventually be made private.
class MOZ_STACK_CLASS FileHelper final {
const SafeRefPtr<DatabaseFileManager> mFileManager;
LazyInitializedOnce<const NotNull<nsCOMPtr<nsIFile>>> mFileDirectory;
LazyInitializedOnce<const NotNull<nsCOMPtr<nsIFile>>> mJournalDirectory;
class ReadCallback;
LazyInitializedOnce<const NotNull<RefPtr<ReadCallback>>> mReadCallback;
public:
explicit FileHelper(SafeRefPtr<DatabaseFileManager>&& aFileManager)
: mFileManager(std::move(aFileManager)) {
MOZ_ASSERT(mFileManager);
}
nsresult Init();
[[nodiscard]] nsCOMPtr<nsIFile> GetFile(const DatabaseFileInfo& aFileInfo);
[[nodiscard]] nsCOMPtr<nsIFile> GetJournalFile(
const DatabaseFileInfo& aFileInfo);
nsresult CreateFileFromStream(nsIFile& aFile, nsIFile& aJournalFile,
nsIInputStream& aInputStream, bool aCompress,
const Maybe<CipherKey>& aMaybeKey);
private:
nsresult SyncCopy(nsIInputStream& aInputStream,
nsIOutputStream& aOutputStream, char* aBuffer,
uint32_t aBufferSize);
nsresult SyncRead(nsIInputStream& aInputStream, char* aBuffer,
uint32_t aBufferSize, uint32_t* aRead);
};
/*******************************************************************************
* Helper Functions
******************************************************************************/
bool GetFilenameBase(const nsAString& aFilename, const nsAString& aSuffix,
nsDependentSubstring& aFilenameBase) {
MOZ_ASSERT(!aFilename.IsEmpty());
MOZ_ASSERT(aFilenameBase.IsEmpty());
if (!StringEndsWith(aFilename, aSuffix) ||
aFilename.Length() == aSuffix.Length()) {
return false;
}
MOZ_ASSERT(aFilename.Length() > aSuffix.Length());
aFilenameBase.Rebind(aFilename, 0, aFilename.Length() - aSuffix.Length());
return true;
}
class EncryptedFileBlobImpl final : public FileBlobImpl {
public:
EncryptedFileBlobImpl(const nsCOMPtr<nsIFile>& aNativeFile,
const DatabaseFileInfo::IdType aId,
const CipherKey& aKey)
: FileBlobImpl{aNativeFile}, mKey{aKey} {
SetFileId(aId);
}
uint64_t GetSize(ErrorResult& aRv) override {
nsCOMPtr<nsIInputStream> inputStream;
CreateInputStream(getter_AddRefs(inputStream), aRv);
if (aRv.Failed()) {
return 0;
}
MOZ_ASSERT(inputStream);
QM_TRY_RETURN(MOZ_TO_RESULT_INVOKE_MEMBER(inputStream, Available), 0,
[&aRv](const nsresult rv) { aRv = rv; });
}
void CreateInputStream(nsIInputStream** aInputStream,
ErrorResult& aRv) const override {
nsCOMPtr<nsIInputStream> baseInputStream;
FileBlobImpl::CreateInputStream(getter_AddRefs(baseInputStream), aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
*aInputStream =
MakeAndAddRef<DecryptingInputStream<IndexedDBCipherStrategy>>(
WrapNotNull(std::move(baseInputStream)), kEncryptedStreamBlockSize,
mKey)
.take();
}
void GetBlobImplType(nsAString& aBlobImplType) const override {
aBlobImplType = u"EncryptedFileBlobImpl"_ns;
}
already_AddRefed<BlobImpl> CreateSlice(uint64_t aStart, uint64_t aLength,
const nsAString& aContentType,
ErrorResult& aRv) const override {
MOZ_CRASH("Not implemented because this should be unreachable.");
}
private:
const CipherKey mKey;
};
RefPtr<BlobImpl> CreateFileBlobImpl(const Database& aDatabase,
const nsCOMPtr<nsIFile>& aNativeFile,
const DatabaseFileInfo::IdType aId) {
if (aDatabase.IsInPrivateBrowsing()) {
nsCString keyId;
keyId.AppendInt(aId);
const auto& key =
aDatabase.GetFileManager().MutableCipherKeyManagerRef().Get(keyId);
MOZ_RELEASE_ASSERT(key.isSome());
return MakeRefPtr<EncryptedFileBlobImpl>(aNativeFile, aId, *key);
}
auto impl = MakeRefPtr<FileBlobImpl>(aNativeFile);
impl->SetFileId(aId);
return impl;
}
Result<nsTArray<SerializedStructuredCloneFile>, nsresult>
SerializeStructuredCloneFiles(const SafeRefPtr<Database>& aDatabase,
const nsTArray<StructuredCloneFileParent>& aFiles,
bool aForPreprocess) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aDatabase);
if (aFiles.IsEmpty()) {
return nsTArray<SerializedStructuredCloneFile>{};
}
const nsCOMPtr<nsIFile> directory =
aDatabase->GetFileManager().GetCheckedDirectory();
QM_TRY(OkIf(directory), Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR),
IDB_REPORT_INTERNAL_ERR_LAMBDA);
nsTArray<SerializedStructuredCloneFile> serializedStructuredCloneFiles;
QM_TRY(OkIf(serializedStructuredCloneFiles.SetCapacity(aFiles.Length(),
fallible)),
Err(NS_ERROR_OUT_OF_MEMORY));
QM_TRY(TransformIfAbortOnErr(
aFiles, MakeBackInserter(serializedStructuredCloneFiles),
[aForPreprocess](const auto& file) {
return !aForPreprocess ||
file.Type() == StructuredCloneFileBase::eStructuredClone;
},
[&directory, &aDatabase, aForPreprocess](
const auto& file) -> Result<SerializedStructuredCloneFile, nsresult> {
const int64_t fileId = file.FileInfo().Id();
MOZ_ASSERT(fileId > 0);
const nsCOMPtr<nsIFile> nativeFile =
mozilla::dom::indexedDB::DatabaseFileManager::GetCheckedFileForId(
directory, fileId);
QM_TRY(OkIf(nativeFile), Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR),
IDB_REPORT_INTERNAL_ERR_LAMBDA);
switch (file.Type()) {
case StructuredCloneFileBase::eStructuredClone:
if (!aForPreprocess) {
return SerializedStructuredCloneFile{
null_t(), StructuredCloneFileBase::eStructuredClone};
}
[[fallthrough]];
case StructuredCloneFileBase::eBlob: {
const auto impl = CreateFileBlobImpl(*aDatabase, nativeFile,
file.FileInfo().Id());
IPCBlob ipcBlob;
// This can only fail if the child has crashed.
QM_TRY(MOZ_TO_RESULT(IPCBlobUtils::Serialize(impl, ipcBlob)),
Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR),
IDB_REPORT_INTERNAL_ERR_LAMBDA);
aDatabase->MapBlob(ipcBlob, file.FileInfoPtr());
return SerializedStructuredCloneFile{ipcBlob, file.Type()};
}
case StructuredCloneFileBase::eMutableFile:
case StructuredCloneFileBase::eWasmBytecode:
case StructuredCloneFileBase::eWasmCompiled: {
// Set file() to null, support for storing WebAssembly.Modules has
// been removed in bug 1469395. Support for de-serialization of
// WebAssembly.Modules modules has been removed in bug 1561876.
// Support for MutableFile has been removed in bug 1500343. Full
// removal is tracked in bug 1487479.
return SerializedStructuredCloneFile{null_t(), file.Type()};
}
default:
MOZ_CRASH("Should never get here!");
}
}));
return std::move(serializedStructuredCloneFiles);
}
bool IsFileNotFoundError(const nsresult aRv) {
return aRv == NS_ERROR_FILE_NOT_FOUND;
}
enum struct Idempotency { Yes, No };
// Delete a file, decreasing the quota usage as appropriate. If the file no
// longer exists but aIdempotency is Idempotency::Yes, success is returned,
// although quota usage can't be decreased. (With the assumption being that the
// file was already deleted prior to this logic running, and the non-existent
// file was no longer tracked by quota because it didn't exist at
// initialization time or a previous deletion call updated the usage.)
nsresult DeleteFile(nsIFile& aFile, QuotaManager* const aQuotaManager,
const PersistenceType aPersistenceType,
const OriginMetadata& aOriginMetadata,
const Idempotency aIdempotency) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
// Callers which pass Idempotency::Yes call this function without checking if
// the file already exists (idempotent usage). QM_OR_ELSE_WARN_IF is not used
// here since we just want to log NS_ERROR_FILE_NOT_FOUND results and not spam
// the reports.
// Theoretically, there should be no QM_OR_ELSE_(WARN|LOG_VERBOSE)_IF when a
// caller passes Idempotency::No, but it's simpler when the predicate just
// always returns false in that case.
const auto isIgnorableError = [&aIdempotency]() -> bool (*)(nsresult) {
if (aIdempotency == Idempotency::Yes) {
return IsFileNotFoundError;
}
return [](const nsresult rv) { return false; };
}();
QM_TRY_INSPECT(
const auto& fileSize,
([aQuotaManager, &aFile,
isIgnorableError]() -> Result<Maybe<int64_t>, nsresult> {
if (aQuotaManager) {
QM_TRY_INSPECT(
const Maybe<int64_t>& fileSize,
QM_OR_ELSE_LOG_VERBOSE_IF(
// Expression.
MOZ_TO_RESULT_INVOKE_MEMBER(aFile, GetFileSize)
.map([](const int64_t val) { return Some(val); }),
// Predicate.
isIgnorableError,
// Fallback.
ErrToDefaultOk<Maybe<int64_t>>));
// XXX Can we really assert that the file size is not 0 if
// it existed? This might be violated by external
// influences.
MOZ_ASSERT(!fileSize || fileSize.value() >= 0);
return fileSize;
}
return Some(int64_t(0));
}()));
if (!fileSize) {
return NS_OK;
}
QM_TRY_INSPECT(const auto& didExist,
QM_OR_ELSE_LOG_VERBOSE_IF(
// Expression.
MOZ_TO_RESULT(aFile.Remove(false)).map(Some<Ok>),
// Predicate.
isIgnorableError,
// Fallback.
ErrToDefaultOk<Maybe<Ok>>));
if (!didExist) {
// XXX If we get here, this means that the file still existed when we
// queried its size, but no longer when we tried to remove it. Not sure if
// this should really be silently accepted in idempotent mode.
return NS_OK;
}
if (fileSize.value() > 0) {
MOZ_ASSERT(aQuotaManager);
aQuotaManager->DecreaseUsageForClient(
ClientMetadata{aOriginMetadata, Client::IDB}, fileSize.value());
}
return NS_OK;
}
nsresult DeleteFile(nsIFile& aDirectory, const nsAString& aFilename,
QuotaManager* const aQuotaManager,
const PersistenceType aPersistenceType,
const OriginMetadata& aOriginMetadata,
const Idempotency aIdempotent) {
AssertIsOnIOThread();
MOZ_ASSERT(!aFilename.IsEmpty());
QM_TRY_INSPECT(const auto& file, CloneFileAndAppend(aDirectory, aFilename));
return DeleteFile(*file, aQuotaManager, aPersistenceType, aOriginMetadata,
aIdempotent);
}
// Delete files in a directory that you think exists. If the directory doesn't
// exist, an error will not be returned, but warning telemetry will be
// generated! So only call this on directories that you know exist (idempotent
// usage, but it's not recommended).
nsresult DeleteFilesNoQuota(nsIFile& aFile) {
AssertIsOnIOThread();
QM_TRY_INSPECT(const auto& didExist,
QM_OR_ELSE_WARN_IF(
// Expression.
MOZ_TO_RESULT(aFile.Remove(true)).map(Some<Ok>),
// Predicate.
IsFileNotFoundError,
// Fallback.
ErrToDefaultOk<Maybe<Ok>>));
Unused << didExist;
return NS_OK;
}
nsresult DeleteFilesNoQuota(nsIFile* aDirectory, const nsAString& aFilename) {
AssertIsOnIOThread();
MOZ_ASSERT(aDirectory);
MOZ_ASSERT(!aFilename.IsEmpty());
// The current using function hasn't initialized the origin, so in here we
// don't update the size of origin. Adding this assertion for preventing from
// misusing.
DebugOnly<QuotaManager*> quotaManager = QuotaManager::Get();
MOZ_ASSERT(!quotaManager->IsTemporaryStorageInitializedInternal());
QM_TRY_INSPECT(const auto& file, CloneFileAndAppend(*aDirectory, aFilename));
QM_TRY(MOZ_TO_RESULT(DeleteFilesNoQuota(*file)));
return NS_OK;
}
// CreateMarkerFile and RemoveMarkerFile are a pair of functions to indicate
// whether having removed all the files successfully. The marker file should
// be checked before executing the next operation or initialization.
Result<nsCOMPtr<nsIFile>, nsresult> CreateMarkerFile(
nsIFile& aBaseDirectory, const nsAString& aDatabaseNameBase) {
AssertIsOnIOThread();
MOZ_ASSERT(!aDatabaseNameBase.IsEmpty());
QM_TRY_INSPECT(
const auto& markerFile,
CloneFileAndAppend(aBaseDirectory,
kIdbDeletionMarkerFilePrefix + aDatabaseNameBase));
// Callers call this function without checking if the file already exists
// (idempotent usage). QM_OR_ELSE_WARN_IF is not used here since we just want
// to log NS_ERROR_FILE_ALREADY_EXISTS result and not spam the reports.
//
// TODO: In theory if this file exists, then RemoveDatabaseFilesAndDirectory
// should have cleaned it up, but obviously we can crash and not clean it up,
// which is the whole point of the marker file. In that case, we'll realize
// the marker file exists in OpenDatabaseOp::DoDatabaseWork or
// GetUsageForOriginInternal and resume the removal by calling
// RemoveDatabaseFilesAndDirectory again, but we will also try to create the
// marker file again, so if we see this marker file, it is part
// of our standard operating procedure to redundantly try and create the
// marker here. We currently treat this as idempotent usage, but we could
// add an additional argument to RemoveDatabaseFilesAndDirectory which would
// indicate that we are resuming an unfinished removal, so the marker already
// exists and doesn't have to be created, and change
// QM_OR_ELSE_LOG_VERBOSE_IF to QM_OR_ELSE_WARN_IF in the end.
QM_TRY(QM_OR_ELSE_LOG_VERBOSE_IF(
// Expression.
MOZ_TO_RESULT(markerFile->Create(nsIFile::NORMAL_FILE_TYPE, 0644)),
// Predicate.
IsSpecificError<NS_ERROR_FILE_ALREADY_EXISTS>,
// Fallback.
ErrToDefaultOk<>));
return markerFile;
}
nsresult RemoveMarkerFile(nsIFile* aMarkerFile) {
AssertIsOnIOThread();
MOZ_ASSERT(aMarkerFile);
DebugOnly<bool> exists;
MOZ_ASSERT(NS_SUCCEEDED(aMarkerFile->Exists(&exists)));
MOZ_ASSERT(exists);
QM_TRY(MOZ_TO_RESULT(aMarkerFile->Remove(false)));
return NS_OK;
}
Result<Ok, nsresult> DeleteFileManagerDirectory(
nsIFile& aFileManagerDirectory, QuotaManager* aQuotaManager,
const PersistenceType aPersistenceType,
const OriginMetadata& aOriginMetadata) {
// XXX In theory, deleting can continue for other files in case of a failure,
// leaving only those files behind that cause the problem actually. However,
// the current architecture doesn't allow having more databases (for the same
// name) on disk, so trying to delete as much as possible won't help much
// because we need to delete entire .files directory in the end anyway.
QM_TRY(DatabaseFileManager::TraverseFiles(
aFileManagerDirectory,
// KnownDirEntryOp
[&aQuotaManager, aPersistenceType, &aOriginMetadata](
nsIFile& file, const bool isDirectory) -> Result<Ok, nsresult> {
if (isDirectory) {
// The journal directory doesn't count towards quota.
QM_TRY_RETURN(MOZ_TO_RESULT(DeleteFilesNoQuota(file)));
}
// Stored files do count towards quota.
QM_TRY_RETURN(
MOZ_TO_RESULT(DeleteFile(file, aQuotaManager, aPersistenceType,
aOriginMetadata, Idempotency::Yes)));
},
// UnknownDirEntryOp
[aPersistenceType, &aOriginMetadata](
nsIFile& file, const bool isDirectory) -> Result<Ok, nsresult> {
// Unknown files and directories don't count towards quota.
if (isDirectory) {
QM_TRY_RETURN(MOZ_TO_RESULT(DeleteFilesNoQuota(file)));
}
QM_TRY_RETURN(MOZ_TO_RESULT(
DeleteFile(file, /* doesn't count */ nullptr, aPersistenceType,
aOriginMetadata, Idempotency::Yes)));
}));
QM_TRY_RETURN(MOZ_TO_RESULT(aFileManagerDirectory.Remove(false)));
}
// Idempotently delete all the parts of an IndexedDB database including its
// SQLite database file, its WAL journal, it's shared-memory file, and its
// Blob/Files sub-directory. A marker file is created prior to performing the
// deletion so that in the event we crash or fail to successfully delete the
// database and its files, we will re-attempt the deletion the next time the
// origin is initialized using this method. Because this means the method may be
// called on a partially deleted database, this method uses DeleteFile which
// succeeds when the file we ask it to delete does not actually exist. The
// marker file is removed once deletion has successfully completed.
nsresult RemoveDatabaseFilesAndDirectory(nsIFile& aBaseDirectory,
const nsAString& aDatabaseFilenameBase,
QuotaManager* aQuotaManager,
const PersistenceType aPersistenceType,
const OriginMetadata& aOriginMetadata,
const nsAString& aDatabaseName) {
AssertIsOnIOThread();
MOZ_ASSERT(!aDatabaseFilenameBase.IsEmpty());
AUTO_PROFILER_LABEL("RemoveDatabaseFilesAndDirectory", DOM);
QM_TRY_UNWRAP(auto markerFile,
CreateMarkerFile(aBaseDirectory, aDatabaseFilenameBase));
// The database file counts towards quota.
QM_TRY(MOZ_TO_RESULT(DeleteFile(
aBaseDirectory, aDatabaseFilenameBase + kSQLiteSuffix, aQuotaManager,
aPersistenceType, aOriginMetadata, Idempotency::Yes)));
// .sqlite-journal files don't count towards quota.
QM_TRY(MOZ_TO_RESULT(DeleteFile(aBaseDirectory,
aDatabaseFilenameBase + kSQLiteJournalSuffix,
/* doesn't count */ nullptr, aPersistenceType,
aOriginMetadata, Idempotency::Yes)));
// .sqlite-shm files don't count towards quota.
QM_TRY(MOZ_TO_RESULT(DeleteFile(aBaseDirectory,
aDatabaseFilenameBase + kSQLiteSHMSuffix,
/* doesn't count */ nullptr, aPersistenceType,
aOriginMetadata, Idempotency::Yes)));
// .sqlite-wal files do count towards quota.
QM_TRY(MOZ_TO_RESULT(DeleteFile(
aBaseDirectory, aDatabaseFilenameBase + kSQLiteWALSuffix, aQuotaManager,
aPersistenceType, aOriginMetadata, Idempotency::Yes)));
// The files directory counts towards quota.
QM_TRY_INSPECT(
const auto& fmDirectory,
CloneFileAndAppend(aBaseDirectory, aDatabaseFilenameBase +
kFileManagerDirectoryNameSuffix));
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(fmDirectory, Exists));
if (exists) {
QM_TRY_INSPECT(const bool& isDirectory,
MOZ_TO_RESULT_INVOKE_MEMBER(fmDirectory, IsDirectory));
QM_TRY(OkIf(isDirectory), NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
QM_TRY(DeleteFileManagerDirectory(*fmDirectory, aQuotaManager,
aPersistenceType, aOriginMetadata));
}
IndexedDatabaseManager* mgr = IndexedDatabaseManager::Get();
MOZ_ASSERT_IF(aQuotaManager, mgr);
if (mgr) {
mgr->InvalidateFileManager(aPersistenceType, aOriginMetadata.mOrigin,
aDatabaseName);
}
QM_TRY(MOZ_TO_RESULT(RemoveMarkerFile(markerFile)));
return NS_OK;
}
/*******************************************************************************
* Globals
******************************************************************************/
// Counts the number of "live" Factory, FactoryOp and Database instances.
uint64_t gBusyCount = 0;
// We don't use LinkedList<CheckedUnsafePtr<FactoryOp>> because
// CheckedUnsafePtr is not suitable for use within LinkedList. While it's
// theoretically possible to adapt LinkedList to support it, doing so would
// introduce unnecessary overhead. Instead, we use a simpler and more
// efficient approach. Each FactoryOp instance asserts !isInList() in its
// destructor to catch dangling pointer issues.
using FactoryOpArray = LinkedList<FactoryOp>;
StaticAutoPtr<FactoryOpArray> gFactoryOps;
// Maps a database id to information about live database actors.
using DatabaseActorHashtable =
nsClassHashtable<nsCStringHashKey, DatabaseActorInfo>;
StaticAutoPtr<DatabaseActorHashtable> gLiveDatabaseHashtable;
StaticRefPtr<ConnectionPool> gConnectionPool;
using DatabaseLoggingInfoHashtable =
nsTHashMap<nsIDHashKey, DatabaseLoggingInfo*>;
StaticAutoPtr<DatabaseLoggingInfoHashtable> gLoggingInfoHashtable;
using TelemetryIdHashtable = nsTHashMap<nsUint32HashKey, uint32_t>;
StaticAutoPtr<TelemetryIdHashtable> gTelemetryIdHashtable;
// Protects all reads and writes to gTelemetryIdHashtable.
StaticAutoPtr<Mutex> gTelemetryIdMutex;
// For private browsing, maps the raw database names provided by content to a
// replacement UUID in order to avoid exposing the name of the database on
// disk or a directly derived value, such as the non-private-browsing
// representation. This mapping will be the same for all databases with the
// same name across all storage keys/origins for the lifetime of the IDB
// QuotaClient. In tests, the QuotaClient may be created and destroyed multiple
// times, but for normal browser use the QuotaClient will last until the
// browser shuts down. Bug 1831835 will improve this implementation to avoid
// using the same mapping across storage keys and to deal with the resulting
// lifecycle issues of the additional memory use.
using StorageDatabaseNameHashtable = nsTHashMap<nsString, nsString>;
StaticAutoPtr<StorageDatabaseNameHashtable> gStorageDatabaseNameHashtable;
// Protects all reads and writes to gStorageDatabaseNameHashtable.
StaticAutoPtr<Mutex> gStorageDatabaseNameMutex;
#ifdef DEBUG
StaticRefPtr<DEBUGThreadSlower> gDEBUGThreadSlower;
#endif // DEBUG
void IncreaseBusyCount() {
AssertIsOnBackgroundThread();
// If this is the first instance then we need to do some initialization.
if (!gBusyCount) {
MOZ_ASSERT(!gFactoryOps);
gFactoryOps = new FactoryOpArray();
MOZ_ASSERT(!gLiveDatabaseHashtable);
gLiveDatabaseHashtable = new DatabaseActorHashtable();
MOZ_ASSERT(!gLoggingInfoHashtable);
gLoggingInfoHashtable = new DatabaseLoggingInfoHashtable();
#ifdef DEBUG
if (kDEBUGThreadPriority != nsISupportsPriority::PRIORITY_NORMAL) {
NS_WARNING(
"PBackground thread debugging enabled, priority has been "
"modified!");
nsCOMPtr<nsISupportsPriority> thread =
do_QueryInterface(NS_GetCurrentThread());
MOZ_ASSERT(thread);
MOZ_ALWAYS_SUCCEEDS(thread->SetPriority(kDEBUGThreadPriority));
}
if (kDEBUGThreadSleepMS) {
NS_WARNING(
"PBackground thread debugging enabled, sleeping after every "
"event!");
nsCOMPtr<nsIThreadInternal> thread =
do_QueryInterface(NS_GetCurrentThread());
MOZ_ASSERT(thread);
gDEBUGThreadSlower = new DEBUGThreadSlower();
MOZ_ALWAYS_SUCCEEDS(thread->AddObserver(gDEBUGThreadSlower));
}
#endif // DEBUG
}
gBusyCount++;
}
void DecreaseBusyCount() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(gBusyCount);
// Clean up if there are no more instances.
if (--gBusyCount == 0) {
MOZ_ASSERT(gLoggingInfoHashtable);
gLoggingInfoHashtable = nullptr;
MOZ_ASSERT(gLiveDatabaseHashtable);
MOZ_ASSERT(!gLiveDatabaseHashtable->Count());
gLiveDatabaseHashtable = nullptr;
MOZ_ASSERT(gFactoryOps);
MOZ_ASSERT(gFactoryOps->isEmpty());
gFactoryOps = nullptr;
#ifdef DEBUG
if (kDEBUGThreadPriority != nsISupportsPriority::PRIORITY_NORMAL) {
nsCOMPtr<nsISupportsPriority> thread =
do_QueryInterface(NS_GetCurrentThread());
MOZ_ASSERT(thread);
MOZ_ALWAYS_SUCCEEDS(
thread->SetPriority(nsISupportsPriority::PRIORITY_NORMAL));
}
if (kDEBUGThreadSleepMS) {
MOZ_ASSERT(gDEBUGThreadSlower);
nsCOMPtr<nsIThreadInternal> thread =
do_QueryInterface(NS_GetCurrentThread());
MOZ_ASSERT(thread);
MOZ_ALWAYS_SUCCEEDS(thread->RemoveObserver(gDEBUGThreadSlower));
gDEBUGThreadSlower = nullptr;
}
#endif // DEBUG
}
}
template <typename Condition>
void InvalidateLiveDatabasesMatching(const Condition& aCondition) {
AssertIsOnBackgroundThread();
if (!gLiveDatabaseHashtable) {
return;
}
// Invalidating a Database will cause it to be removed from the
// gLiveDatabaseHashtable entries' mLiveDatabases, and, if it was the last
// element in mLiveDatabases, to remove the whole hashtable entry. Therefore,
// we need to make a temporary list of the databases to invalidate to avoid
// iterator invalidation.
nsTArray<SafeRefPtr<Database>> databases;
for (const auto& liveDatabasesEntry : gLiveDatabaseHashtable->Values()) {
for (Database* const database : liveDatabasesEntry->mLiveDatabases) {
if (aCondition(*database)) {
databases.AppendElement(
SafeRefPtr{database, AcquireStrongRefFromRawPtr{}});
}
}
}
for (const auto& database : databases) {
database->Invalidate();
}
}
uint32_t TelemetryIdForFile(nsIFile* aFile) {
// May be called on any thread!
MOZ_ASSERT(aFile);
MOZ_ASSERT(gTelemetryIdMutex);
// The storage directory is structured like this:
//
// <profile>/storage/<persistence>/<origin>/idb/<filename>.sqlite
//
// For the purposes of this function we're only concerned with the
// <persistence>, <origin>, and <filename> pieces.
nsString filename;
MOZ_ALWAYS_SUCCEEDS(aFile->GetLeafName(filename));
// Make sure we were given a database file.
MOZ_ASSERT(StringEndsWith(filename, kSQLiteSuffix));
filename.Truncate(filename.Length() - kSQLiteSuffix.Length());
// Get the "idb" directory.
nsCOMPtr<nsIFile> idbDirectory;
MOZ_ALWAYS_SUCCEEDS(aFile->GetParent(getter_AddRefs(idbDirectory)));
DebugOnly<nsString> idbLeafName;
MOZ_ASSERT(NS_SUCCEEDED(idbDirectory->GetLeafName(idbLeafName)));
MOZ_ASSERT(static_cast<nsString&>(idbLeafName).EqualsLiteral("idb"));
// Get the <origin> directory.
nsCOMPtr<nsIFile> originDirectory;
MOZ_ALWAYS_SUCCEEDS(idbDirectory->GetParent(getter_AddRefs(originDirectory)));
nsString origin;
MOZ_ALWAYS_SUCCEEDS(originDirectory->GetLeafName(origin));
// Any databases in these directories are owned by the application and should
// not have their filenames masked. Hopefully they also appear in the
// Telemetry.cpp whitelist.
if (origin.EqualsLiteral("chrome") ||
origin.EqualsLiteral("moz-safe-about+home")) {
return 0;
}
// Get the <persistence> directory.
nsCOMPtr<nsIFile> persistenceDirectory;
MOZ_ALWAYS_SUCCEEDS(
originDirectory->GetParent(getter_AddRefs(persistenceDirectory)));
nsString persistence;
MOZ_ALWAYS_SUCCEEDS(persistenceDirectory->GetLeafName(persistence));
constexpr auto separator = u"*"_ns;
uint32_t hashValue =
HashString(persistence + separator + origin + separator + filename);
MutexAutoLock lock(*gTelemetryIdMutex);
if (!gTelemetryIdHashtable) {
gTelemetryIdHashtable = new TelemetryIdHashtable();
}
return gTelemetryIdHashtable->LookupOrInsertWith(hashValue, [] {
static uint32_t sNextId = 1;
// We're locked, no need for atomics.
return sNextId++;
});
}
nsAutoString GetDatabaseFilenameBase(const nsAString& aDatabaseName,
bool aIsPrivate) {
nsAutoString databaseFilenameBase;
if (aIsPrivate) {
MOZ_DIAGNOSTIC_ASSERT(gStorageDatabaseNameMutex);
MutexAutoLock lock(*gStorageDatabaseNameMutex);
if (!gStorageDatabaseNameHashtable) {
gStorageDatabaseNameHashtable = new StorageDatabaseNameHashtable();
}
databaseFilenameBase.Append(
gStorageDatabaseNameHashtable->LookupOrInsertWith(aDatabaseName, []() {
return NSID_TrimBracketsUTF16(nsID::GenerateUUID());
}));
return databaseFilenameBase;
}
// WARNING: do not change this hash function. See the comment in HashName()
// for details.
databaseFilenameBase.AppendInt(HashName(aDatabaseName));
nsAutoCString escapedName;
if (!NS_Escape(NS_ConvertUTF16toUTF8(aDatabaseName), escapedName,
url_XPAlphas)) {
MOZ_CRASH("Can't escape database name!");
}
const char* forwardIter = escapedName.BeginReading();
const char* backwardIter = escapedName.EndReading() - 1;
nsAutoCString substring;
while (forwardIter <= backwardIter && substring.Length() < 21) {
if (substring.Length() % 2) {
substring.Append(*backwardIter--);
} else {
substring.Append(*forwardIter++);
}
}
databaseFilenameBase.AppendASCII(substring.get(), substring.Length());
return databaseFilenameBase;
}
const CommonIndexOpenCursorParams& GetCommonIndexOpenCursorParams(
const OpenCursorParams& aParams) {
switch (aParams.type()) {
case OpenCursorParams::TIndexOpenCursorParams:
return aParams.get_IndexOpenCursorParams().commonIndexParams();
case OpenCursorParams::TIndexOpenKeyCursorParams:
return aParams.get_IndexOpenKeyCursorParams().commonIndexParams();
default:
MOZ_CRASH("Should never get here!");
}
}
const CommonOpenCursorParams& GetCommonOpenCursorParams(
const OpenCursorParams& aParams) {
switch (aParams.type()) {
case OpenCursorParams::TObjectStoreOpenCursorParams:
return aParams.get_ObjectStoreOpenCursorParams().commonParams();
case OpenCursorParams::TObjectStoreOpenKeyCursorParams:
return aParams.get_ObjectStoreOpenKeyCursorParams().commonParams();
case OpenCursorParams::TIndexOpenCursorParams:
case OpenCursorParams::TIndexOpenKeyCursorParams:
return GetCommonIndexOpenCursorParams(aParams).commonParams();
default:
MOZ_CRASH("Should never get here!");
}
}
// TODO: Using nsCString as a return type here seems to lead to a dependency on
// some temporaries, which I did not expect. Is it a good idea that the default
// operator+ behaviour constructs such strings? It is certainly useful as an
// optimization, but this should be better done via an appropriately named
// function rather than an operator.
nsAutoCString MakeColumnPairSelectionList(
const nsLiteralCString& aPlainColumnName,
const nsLiteralCString& aLocaleAwareColumnName,
const nsLiteralCString& aSortColumnAlias, const bool aIsLocaleAware) {
return aPlainColumnName +
(aIsLocaleAware ? EmptyCString() : " as "_ns + aSortColumnAlias) +
", "_ns + aLocaleAwareColumnName +
(aIsLocaleAware ? " as "_ns + aSortColumnAlias : EmptyCString());
}
constexpr bool IsIncreasingOrder(const IDBCursorDirection aDirection) {
MOZ_ASSERT(aDirection == IDBCursorDirection::Next ||
aDirection == IDBCursorDirection::Nextunique ||
aDirection == IDBCursorDirection::Prev ||
aDirection == IDBCursorDirection::Prevunique);
return aDirection == IDBCursorDirection::Next ||
aDirection == IDBCursorDirection::Nextunique;
}
constexpr bool IsUnique(const IDBCursorDirection aDirection) {
MOZ_ASSERT(aDirection == IDBCursorDirection::Next ||
aDirection == IDBCursorDirection::Nextunique ||
aDirection == IDBCursorDirection::Prev ||
aDirection == IDBCursorDirection::Prevunique);
return aDirection == IDBCursorDirection::Nextunique ||
aDirection == IDBCursorDirection::Prevunique;
}
// TODO: In principle, this could be constexpr, if operator+(nsLiteralCString,
// nsLiteralCString) were constexpr and returned a literal type.
nsAutoCString MakeDirectionClause(const IDBCursorDirection aDirection) {
return " ORDER BY "_ns + kColumnNameKey +
(IsIncreasingOrder(aDirection) ? " ASC"_ns : " DESC"_ns);
}
enum struct ComparisonOperator {
LessThan,
LessOrEquals,
Equals,
GreaterThan,
GreaterOrEquals,
};
constexpr nsLiteralCString GetComparisonOperatorString(
const ComparisonOperator aComparisonOperator) {
switch (aComparisonOperator) {
case ComparisonOperator::LessThan:
return "<"_ns;
case ComparisonOperator::LessOrEquals:
return "<="_ns;
case ComparisonOperator::Equals:
return "=="_ns;
case ComparisonOperator::GreaterThan:
return ">"_ns;
case ComparisonOperator::GreaterOrEquals:
return ">="_ns;
}
// TODO: This is just to silence the "control reaches end of non-void
// function" warning. Cannot use MOZ_CRASH in a constexpr function,
// unfortunately.
return ""_ns;
}
nsAutoCString GetKeyClause(const nsACString& aColumnName,
const ComparisonOperator aComparisonOperator,
const nsLiteralCString& aStmtParamName) {
return aColumnName + " "_ns +
GetComparisonOperatorString(aComparisonOperator) + " :"_ns +
aStmtParamName;
}
nsAutoCString GetSortKeyClause(const ComparisonOperator aComparisonOperator,
const nsLiteralCString& aStmtParamName) {
return GetKeyClause(kColumnNameAliasSortKey, aComparisonOperator,
aStmtParamName);
}
template <IDBCursorType CursorType>
struct PopulateResponseHelper;
struct CommonPopulateResponseHelper {
explicit CommonPopulateResponseHelper(
const TransactionDatabaseOperationBase& aOp)
: mOp{aOp} {}
nsresult GetKeys(mozIStorageStatement* const aStmt,
Key* const aOptOutSortKey) {
QM_TRY(MOZ_TO_RESULT(GetCommonKeys(aStmt)));
if (aOptOutSortKey) {
*aOptOutSortKey = mPosition;
}
return NS_OK;
}
nsresult GetCommonKeys(mozIStorageStatement* const aStmt) {
MOZ_ASSERT(mPosition.IsUnset());
QM_TRY(MOZ_TO_RESULT(mPosition.SetFromStatement(aStmt, 0)));
IDB_LOG_MARK_PARENT_TRANSACTION_REQUEST(
"PRELOAD: Populating response with key %s", "Populating%.0s",
IDB_LOG_ID_STRING(mOp.BackgroundChildLoggingId()),
mOp.TransactionLoggingSerialNumber(), mOp.LoggingSerialNumber(),
mPosition.GetBuffer().get());
return NS_OK;
}
template <typename Response>
void FillKeys(Response& aResponse) {
MOZ_ASSERT(!mPosition.IsUnset());
aResponse.key() = std::move(mPosition);
}
template <typename Response>
static size_t GetKeySize(const Response& aResponse) {
return aResponse.key().GetBuffer().Length();
}
protected:
const Key& GetPosition() const { return mPosition; }
private:
const TransactionDatabaseOperationBase& mOp;
Key mPosition;
};
struct IndexPopulateResponseHelper : CommonPopulateResponseHelper {
using CommonPopulateResponseHelper::CommonPopulateResponseHelper;
nsresult GetKeys(mozIStorageStatement* const aStmt,
Key* const aOptOutSortKey) {
MOZ_ASSERT(mLocaleAwarePosition.IsUnset());
MOZ_ASSERT(mObjectStorePosition.IsUnset());
QM_TRY(MOZ_TO_RESULT(CommonPopulateResponseHelper::GetCommonKeys(aStmt)));
QM_TRY(MOZ_TO_RESULT(mLocaleAwarePosition.SetFromStatement(aStmt, 1)));
QM_TRY(MOZ_TO_RESULT(mObjectStorePosition.SetFromStatement(aStmt, 2)));
if (aOptOutSortKey) {
*aOptOutSortKey =
mLocaleAwarePosition.IsUnset() ? GetPosition() : mLocaleAwarePosition;
}
return NS_OK;
}
template <typename Response>
void FillKeys(Response& aResponse) {
MOZ_ASSERT(!mLocaleAwarePosition.IsUnset());
MOZ_ASSERT(!mObjectStorePosition.IsUnset());
CommonPopulateResponseHelper::FillKeys(aResponse);
aResponse.sortKey() = std::move(mLocaleAwarePosition);
aResponse.objectKey() = std::move(mObjectStorePosition);
}
template <typename Response>
static size_t GetKeySize(Response& aResponse) {
return CommonPopulateResponseHelper::GetKeySize(aResponse) +
aResponse.sortKey().GetBuffer().Length() +
aResponse.objectKey().GetBuffer().Length();
}
private:
Key mLocaleAwarePosition, mObjectStorePosition;
};
struct KeyPopulateResponseHelper {
static constexpr nsresult MaybeGetCloneInfo(
mozIStorageStatement* const /*aStmt*/, const CursorBase& /*aCursor*/) {
return NS_OK;
}
template <typename Response>
static constexpr void MaybeFillCloneInfo(Response& /*aResponse*/,
FilesArray* const /*aFiles*/) {}
template <typename Response>
static constexpr size_t MaybeGetCloneInfoSize(const Response& /*aResponse*/) {
return 0;
}
};
template <bool StatementHasIndexKeyBindings>
struct ValuePopulateResponseHelper {
nsresult MaybeGetCloneInfo(mozIStorageStatement* const aStmt,
const ValueCursorBase& aCursor) {
constexpr auto offset = StatementHasIndexKeyBindings ? 2 : 0;
QM_TRY_UNWRAP(auto cloneInfo,
GetStructuredCloneReadInfoFromStatement(
aStmt, 2 + offset, 1 + offset, *aCursor.mFileManager));
mCloneInfo.init(std::move(cloneInfo));
if (mCloneInfo->HasPreprocessInfo()) {
IDB_WARNING("Preprocessing for cursors not yet implemented!");
return NS_ERROR_NOT_IMPLEMENTED;
}
return NS_OK;
}
template <typename Response>
void MaybeFillCloneInfo(Response& aResponse, FilesArray* const aFiles) {
auto cloneInfo = mCloneInfo.release();
aResponse.cloneInfo().data().data = cloneInfo.ReleaseData();
aFiles->AppendElement(cloneInfo.ReleaseFiles());
}
template <typename Response>
static size_t MaybeGetCloneInfoSize(const Response& aResponse) {
return aResponse.cloneInfo().data().data.Size();
}
private:
LazyInitializedOnceEarlyDestructible<const StructuredCloneReadInfoParent>
mCloneInfo;
};
template <>
struct PopulateResponseHelper<IDBCursorType::ObjectStore>
: ValuePopulateResponseHelper<false>, CommonPopulateResponseHelper {
using CommonPopulateResponseHelper::CommonPopulateResponseHelper;
static auto& GetTypedResponse(CursorResponse* const aResponse) {
return aResponse->get_ArrayOfObjectStoreCursorResponse();
}
};
template <>
struct PopulateResponseHelper<IDBCursorType::ObjectStoreKey>
: KeyPopulateResponseHelper, CommonPopulateResponseHelper {
using CommonPopulateResponseHelper::CommonPopulateResponseHelper;
static auto& GetTypedResponse(CursorResponse* const aResponse) {
return aResponse->get_ArrayOfObjectStoreKeyCursorResponse();
}
};
template <>
struct PopulateResponseHelper<IDBCursorType::Index>
: ValuePopulateResponseHelper<true>, IndexPopulateResponseHelper {
using IndexPopulateResponseHelper::IndexPopulateResponseHelper;
static auto& GetTypedResponse(CursorResponse* const aResponse) {
return aResponse->get_ArrayOfIndexCursorResponse();
}
};
template <>
struct PopulateResponseHelper<IDBCursorType::IndexKey>
: KeyPopulateResponseHelper, IndexPopulateResponseHelper {
using IndexPopulateResponseHelper::IndexPopulateResponseHelper;
static auto& GetTypedResponse(CursorResponse* const aResponse) {
return aResponse->get_ArrayOfIndexKeyCursorResponse();
}
};
nsresult DispatchAndReturnFileReferences(
PersistenceType aPersistenceType, const nsACString& aOrigin,
const nsAString& aDatabaseName, const int64_t aFileId,
int32_t* const aMemRefCnt, int32_t* const aDBRefCnt, bool* const aResult) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aMemRefCnt);
MOZ_ASSERT(aDBRefCnt);
MOZ_ASSERT(aResult);
*aResult = false;
*aMemRefCnt = -1;
*aDBRefCnt = -1;
mozilla::Monitor monitor MOZ_ANNOTATED(__func__);
bool waiting = true;
auto lambda = [&] {
AssertIsOnIOThread();
{
IndexedDatabaseManager* const mgr = IndexedDatabaseManager::Get();
MOZ_ASSERT(mgr);
const SafeRefPtr<DatabaseFileManager> fileManager =
mgr->GetFileManager(aPersistenceType, aOrigin, aDatabaseName);
if (fileManager) {
const SafeRefPtr<DatabaseFileInfo> fileInfo =
fileManager->GetFileInfo(aFileId);
if (fileInfo) {
fileInfo->GetReferences(aMemRefCnt, aDBRefCnt);
if (*aMemRefCnt != -1) {
// We added an extra temp ref, so account for that accordingly.
(*aMemRefCnt)--;
}
*aResult = true;
}
}
}
mozilla::MonitorAutoLock lock(monitor);
MOZ_ASSERT(waiting);
waiting = false;
lock.Notify();
};
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
// XXX can't we simply use NS_DispatchAndSpinEventLoopUntilComplete instead of
// using a monitor?
QM_TRY(MOZ_TO_RESULT(quotaManager->IOThread()->Dispatch(
NS_NewRunnableFunction("GetFileReferences", std::move(lambda)),
NS_DISPATCH_NORMAL)));
mozilla::MonitorAutoLock autolock(monitor);
while (waiting) {
autolock.Wait();
}
return NS_OK;
}
class DeserializeIndexValueHelper final : public Runnable {
public:
DeserializeIndexValueHelper(int64_t aIndexID, const KeyPath& aKeyPath,
bool aMultiEntry, const nsACString& aLocale,
StructuredCloneReadInfoParent& aCloneReadInfo,
nsTArray<IndexUpdateInfo>& aUpdateInfoArray)
: Runnable("DeserializeIndexValueHelper"),
mMonitor("DeserializeIndexValueHelper::mMonitor"),
mIndexID(aIndexID),
mKeyPath(aKeyPath),
mMultiEntry(aMultiEntry),
mLocale(aLocale),
mCloneReadInfo(aCloneReadInfo),
mUpdateInfoArray(aUpdateInfoArray),
mStatus(NS_ERROR_FAILURE) {}
nsresult DispatchAndWait() {
// FIXME(Bug 1637530) Re-enable optimization using a non-system-principaled
// JS context
#if 0
// We don't need to go to the main-thread and use the sandbox. Let's create
// the updateInfo data here.
if (!mCloneReadInfo.Data().Size()) {
AutoJSAPI jsapi;
jsapi.Init();
JS::Rooted<JS::Value> value(jsapi.cx());
value.setUndefined();
ErrorResult rv;
IDBObjectStore::AppendIndexUpdateInfo(
mIndexID, mKeyPath, mMultiEntry, &mUpdateInfoArray,
/* aAutoIncrementedObjectStoreKeyPath */ VoidString(), &rv);
return rv.Failed() ? rv.StealNSResult() : NS_OK;
}
#endif
// The operation will continue on the main-thread.
MOZ_ASSERT(!(mCloneReadInfo.Data().Size() % sizeof(uint64_t)));
MonitorAutoLock lock(mMonitor);
RefPtr<Runnable> self = this;
QM_TRY(MOZ_TO_RESULT(SchedulerGroup::Dispatch(self.forget())));
lock.Wait();
return mStatus;
}
NS_IMETHOD
Run() override {
MOZ_ASSERT(NS_IsMainThread());
AutoJSAPI jsapi;
jsapi.Init();
JSContext* const cx = jsapi.cx();
JS::Rooted<JSObject*> global(cx, GetSandbox(cx));
QM_TRY(OkIf(global), NS_OK,
[this](const NotOk) { OperationCompleted(NS_ERROR_FAILURE); });
const JSAutoRealm ar(cx, global);
JS::Rooted<JS::Value> value(cx);
QM_TRY(MOZ_TO_RESULT(DeserializeIndexValue(cx, &value)), NS_OK,
[this](const nsresult rv) { OperationCompleted(rv); });
ErrorResult errorResult;
IDBObjectStore::AppendIndexUpdateInfo(
mIndexID, mKeyPath, mMultiEntry, mLocale, cx, value, &mUpdateInfoArray,
/* aAutoIncrementedObjectStoreKeyPath */ VoidString(), &errorResult);
QM_TRY(OkIf(!errorResult.Failed()), NS_OK,
([this, &errorResult](const NotOk) {
OperationCompleted(errorResult.StealNSResult());
}));
OperationCompleted(NS_OK);
return NS_OK;
}
private:
nsresult DeserializeIndexValue(JSContext* aCx,
JS::MutableHandle<JS::Value> aValue) {
static const JSStructuredCloneCallbacks callbacks = {
StructuredCloneReadCallback<StructuredCloneReadInfoParent>,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr};
if (!JS_ReadStructuredClone(
aCx, mCloneReadInfo.Data(), JS_STRUCTURED_CLONE_VERSION,
JS::StructuredCloneScope::DifferentProcessForIndexedDB, aValue,
JS::CloneDataPolicy(), &callbacks, &mCloneReadInfo)) {
return NS_ERROR_DOM_DATA_CLONE_ERR;
}
return NS_OK;
}
void OperationCompleted(nsresult aStatus) {
mStatus = aStatus;
MonitorAutoLock lock(mMonitor);
lock.Notify();
}
Monitor mMonitor MOZ_UNANNOTATED;
const int64_t mIndexID;
const KeyPath& mKeyPath;
const bool mMultiEntry;
const nsCString mLocale;
StructuredCloneReadInfoParent& mCloneReadInfo;
nsTArray<IndexUpdateInfo>& mUpdateInfoArray;
nsresult mStatus;
};
auto DeserializeIndexValueToUpdateInfos(
int64_t aIndexID, const KeyPath& aKeyPath, bool aMultiEntry,
const nsACString& aLocale, StructuredCloneReadInfoParent& aCloneReadInfo) {
MOZ_ASSERT(!NS_IsMainThread());
using ArrayType = AutoTArray<IndexUpdateInfo, 32>;
using ResultType = Result<ArrayType, nsresult>;
ArrayType updateInfoArray;
const auto helper = MakeRefPtr<DeserializeIndexValueHelper>(
aIndexID, aKeyPath, aMultiEntry, aLocale, aCloneReadInfo,
updateInfoArray);
const nsresult rv = helper->DispatchAndWait();
return NS_FAILED(rv) ? Err(rv) : ResultType{std::move(updateInfoArray)};
}
bool IsSome(
const Maybe<CachingDatabaseConnection::BorrowedStatement>& aMaybeStmt) {
return aMaybeStmt.isSome();
}
already_AddRefed<nsIThreadPool> MakeConnectionIOTarget() {
nsCOMPtr<nsIThreadPool> threadPool = new nsThreadPool();
MOZ_ALWAYS_SUCCEEDS(threadPool->SetThreadLimit(kMaxConnectionThreadCount));
MOZ_ALWAYS_SUCCEEDS(
threadPool->SetIdleThreadLimit(kMaxIdleConnectionThreadCount));
MOZ_ALWAYS_SUCCEEDS(
threadPool->SetIdleThreadMaximumTimeout(kConnectionThreadMaxIdleMS));
MOZ_ALWAYS_SUCCEEDS(
threadPool->SetIdleThreadGraceTimeout(kConnectionThreadGraceIdleMS));
MOZ_ALWAYS_SUCCEEDS(threadPool->SetName("IndexedDB IO"_ns));
return threadPool.forget();
}
} // namespace
/*******************************************************************************
* Exported functions
******************************************************************************/
already_AddRefed<PBackgroundIDBFactoryParent> AllocPBackgroundIDBFactoryParent(
const LoggingInfo& aLoggingInfo, const nsACString& aSystemLocale) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread())) {
return nullptr;
}
if (NS_AUUF_OR_WARN_IF(!aLoggingInfo.nextTransactionSerialNumber()) ||
NS_AUUF_OR_WARN_IF(
!aLoggingInfo.nextVersionChangeTransactionSerialNumber()) ||
NS_AUUF_OR_WARN_IF(!aLoggingInfo.nextRequestSerialNumber())) {
return nullptr;
}
SafeRefPtr<Factory> actor = Factory::Create(aLoggingInfo, aSystemLocale);
MOZ_ASSERT(actor);
return actor.forget();
}
bool RecvPBackgroundIDBFactoryConstructor(
PBackgroundIDBFactoryParent* aActor, const LoggingInfo& /* aLoggingInfo */,
const nsACString& /* aSystemLocale */) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
MOZ_ASSERT(!QuotaClient::IsShuttingDownOnBackgroundThread());
return true;
}
PBackgroundIndexedDBUtilsParent* AllocPBackgroundIndexedDBUtilsParent() {
AssertIsOnBackgroundThread();
RefPtr<Utils> actor = new Utils();
return actor.forget().take();
}
bool DeallocPBackgroundIndexedDBUtilsParent(
PBackgroundIndexedDBUtilsParent* aActor) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
RefPtr<Utils> actor = dont_AddRef(static_cast<Utils*>(aActor));
return true;
}
bool RecvFlushPendingFileDeletions() {
AssertIsOnBackgroundThread();
if (QuotaClient* quotaClient = QuotaClient::GetInstance()) {
QM_WARNONLY_TRY(QM_TO_RESULT(quotaClient->FlushPendingFileDeletions()));
}
return true;
}
RefPtr<mozilla::dom::quota::Client> CreateQuotaClient() {
AssertIsOnBackgroundThread();
return MakeRefPtr<QuotaClient>();
}
nsresult DatabaseFileManager::AsyncDeleteFile(int64_t aFileId) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!ContainsFileInfo(aFileId));
QuotaClient* quotaClient = QuotaClient::GetInstance();
if (quotaClient) {
QM_TRY(MOZ_TO_RESULT(quotaClient->AsyncDeleteFile(this, aFileId)));
}
return NS_OK;
}
/*******************************************************************************
* DatabaseConnection implementation
******************************************************************************/
DatabaseConnection::DatabaseConnection(
MovingNotNull<nsCOMPtr<mozIStorageConnection>> aStorageConnection,
MovingNotNull<SafeRefPtr<DatabaseFileManager>> aFileManager)
: CachingDatabaseConnection(std::move(aStorageConnection)),
mFileManager(std::move(aFileManager)),
mLastDurability(IDBTransaction::Durability::Default),
mInReadTransaction(false),
mInWriteTransaction(false)
#ifdef DEBUG
,
mDEBUGSavepointCount(0)
#endif
{
AssertIsOnConnectionThread();
MOZ_ASSERT(mFileManager);
}
DatabaseConnection::~DatabaseConnection() {
MOZ_ASSERT(!mFileManager);
MOZ_ASSERT(!mUpdateRefcountFunction);
MOZ_DIAGNOSTIC_ASSERT(!mInWriteTransaction);
MOZ_ASSERT(!mDEBUGSavepointCount);
}
nsresult DatabaseConnection::Init() {
AssertIsOnConnectionThread();
MOZ_ASSERT(!mInReadTransaction);
MOZ_ASSERT(!mInWriteTransaction);
QM_TRY(MOZ_TO_RESULT(ExecuteCachedStatement("BEGIN;"_ns)));
mInReadTransaction = true;
return NS_OK;
}
nsresult DatabaseConnection::BeginWriteTransaction(
const IDBTransaction::Durability aDurability) {
AssertIsOnConnectionThread();
MOZ_ASSERT(HasStorageConnection());
MOZ_ASSERT(mInReadTransaction);
MOZ_ASSERT(!mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::BeginWriteTransaction", DOM);
// Release our read locks.
QM_TRY(MOZ_TO_RESULT(ExecuteCachedStatement("ROLLBACK;"_ns)));
mInReadTransaction = false;
if (mLastDurability != aDurability) {
auto synchronousMode = [aDurability]() -> nsLiteralCString {
switch (aDurability) {
case IDBTransaction::Durability::Default:
return GetDefaultSynchronousMode();
case IDBTransaction::Durability::Strict:
return "EXTRA"_ns;
case IDBTransaction::Durability::Relaxed:
return "OFF"_ns;
default:
MOZ_CRASH("Unknown CheckpointMode!");
}
}();
QM_TRY(MOZ_TO_RESULT(ExecuteCachedStatement("PRAGMA synchronous = "_ns +
synchronousMode + ";"_ns)));
mLastDurability = aDurability;
}
if (!mUpdateRefcountFunction) {
MOZ_ASSERT(mFileManager);
RefPtr<UpdateRefcountFunction> function =
new UpdateRefcountFunction(this, **mFileManager);
QM_TRY(MOZ_TO_RESULT(MutableStorageConnection().CreateFunction(
"update_refcount"_ns,
/* aNumArguments */ 2, function)));
mUpdateRefcountFunction = std::move(function);
}
// This one cannot obviously use ExecuteCachedStatement because of the custom
// error handling for Execute only. If only Execute can produce
// NS_ERROR_STORAGE_BUSY, we could actually use ExecuteCachedStatement and
// simplify this.
QM_TRY_INSPECT(const auto& beginStmt,
BorrowCachedStatement("BEGIN IMMEDIATE;"_ns));
QM_TRY(QM_OR_ELSE_WARN_IF(
// Expression.
MOZ_TO_RESULT(beginStmt->Execute()),
// Predicate.
IsSpecificError<NS_ERROR_STORAGE_BUSY>,
// Fallback.
([&beginStmt](nsresult rv) {
NS_WARNING(
"Received NS_ERROR_STORAGE_BUSY when attempting to start write "
"transaction, retrying for up to 10 seconds");
// Another thread must be using the database. Wait up to 10 seconds
// for that to complete.
const TimeStamp start = TimeStamp::NowLoRes();
while (true) {
PR_Sleep(PR_MillisecondsToInterval(100));
rv = beginStmt->Execute();
if (rv != NS_ERROR_STORAGE_BUSY ||
TimeStamp::NowLoRes() - start > TimeDuration::FromSeconds(10)) {
break;
}
}
return MOZ_TO_RESULT(rv);
})));
mInWriteTransaction = true;
return NS_OK;
}
nsresult DatabaseConnection::CommitWriteTransaction() {
AssertIsOnConnectionThread();
MOZ_ASSERT(HasStorageConnection());
MOZ_ASSERT(!mInReadTransaction);
MOZ_ASSERT(mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::CommitWriteTransaction", DOM);
QM_TRY(MOZ_TO_RESULT(ExecuteCachedStatement("COMMIT;"_ns)));
mInWriteTransaction = false;
return NS_OK;
}
void DatabaseConnection::RollbackWriteTransaction() {
AssertIsOnConnectionThread();
MOZ_ASSERT(!mInReadTransaction);
MOZ_DIAGNOSTIC_ASSERT(HasStorageConnection());
AUTO_PROFILER_LABEL("DatabaseConnection::RollbackWriteTransaction", DOM);
if (!mInWriteTransaction) {
return;
}
QM_WARNONLY_TRY(
BorrowCachedStatement("ROLLBACK;"_ns)
.andThen([&self = *this](const auto& stmt) -> Result<Ok, nsresult> {
// This may fail if SQLite already rolled back the transaction
// so ignore any errors.
// XXX ROLLBACK can fail quite normmally if a previous statement
// failed to execute successfully so SQLite rolled back the
// transaction already. However, if it failed because of some other
// reason, we could try to close the connection.
Unused << stmt->Execute();
self.mInWriteTransaction = false;
return Ok{};
}));
}
void DatabaseConnection::FinishWriteTransaction() {
AssertIsOnConnectionThread();
MOZ_ASSERT(HasStorageConnection());
MOZ_ASSERT(!mInReadTransaction);
MOZ_ASSERT(!mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::FinishWriteTransaction", DOM);
if (mUpdateRefcountFunction) {
mUpdateRefcountFunction->Reset();
}
QM_WARNONLY_TRY(MOZ_TO_RESULT(ExecuteCachedStatement("BEGIN;"_ns))
.andThen([&](const auto) -> Result<Ok, nsresult> {
mInReadTransaction = true;
return Ok{};
}));
}
nsresult DatabaseConnection::StartSavepoint() {
AssertIsOnConnectionThread();
MOZ_ASSERT(HasStorageConnection());
MOZ_ASSERT(mUpdateRefcountFunction);
MOZ_ASSERT(mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::StartSavepoint", DOM);
QM_TRY(MOZ_TO_RESULT(ExecuteCachedStatement(SAVEPOINT_CLAUSE)));
mUpdateRefcountFunction->StartSavepoint();
#ifdef DEBUG
MOZ_ASSERT(mDEBUGSavepointCount < UINT32_MAX);
mDEBUGSavepointCount++;
#endif
return NS_OK;
}
nsresult DatabaseConnection::ReleaseSavepoint() {
AssertIsOnConnectionThread();
MOZ_ASSERT(HasStorageConnection());
MOZ_ASSERT(mUpdateRefcountFunction);
MOZ_ASSERT(mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::ReleaseSavepoint", DOM);
QM_TRY(MOZ_TO_RESULT(ExecuteCachedStatement("RELEASE "_ns SAVEPOINT_CLAUSE)));
mUpdateRefcountFunction->ReleaseSavepoint();
#ifdef DEBUG
MOZ_ASSERT(mDEBUGSavepointCount);
mDEBUGSavepointCount--;
#endif
return NS_OK;
}
nsresult DatabaseConnection::RollbackSavepoint() {
AssertIsOnConnectionThread();
MOZ_ASSERT(HasStorageConnection());
MOZ_ASSERT(mUpdateRefcountFunction);
MOZ_ASSERT(mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::RollbackSavepoint", DOM);
#ifdef DEBUG
MOZ_ASSERT(mDEBUGSavepointCount);
mDEBUGSavepointCount--;
#endif
mUpdateRefcountFunction->RollbackSavepoint();
QM_TRY_INSPECT(const auto& stmt,
BorrowCachedStatement("ROLLBACK TO "_ns SAVEPOINT_CLAUSE));
// This may fail if SQLite already rolled back the savepoint so ignore any
// errors.
Unused << stmt->Execute();
return NS_OK;
}
nsresult DatabaseConnection::CheckpointInternal(CheckpointMode aMode) {
AssertIsOnConnectionThread();
MOZ_ASSERT(!mInReadTransaction);
MOZ_ASSERT(!mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::CheckpointInternal", DOM);
nsAutoCString stmtString;
stmtString.AssignLiteral("PRAGMA wal_checkpoint(");
switch (aMode) {
case CheckpointMode::Full:
// Ensures that the database is completely checkpointed and flushed to
// disk.
stmtString.AppendLiteral("FULL");
break;
case CheckpointMode::Restart:
// Like Full, but also ensures that the next write will start overwriting
// the existing WAL file rather than letting the WAL file grow.
stmtString.AppendLiteral("RESTART");
break;
case CheckpointMode::Truncate:
// Like Restart but also truncates the existing WAL file.
stmtString.AppendLiteral("TRUNCATE");
break;
default:
MOZ_CRASH("Unknown CheckpointMode!");
}
stmtString.AppendLiteral(");");
QM_TRY(MOZ_TO_RESULT(ExecuteCachedStatement(stmtString)));
return NS_OK;
}
void DatabaseConnection::DoIdleProcessing(bool aNeedsCheckpoint,
const Atomic<bool>& aInterrupted) {
AssertIsOnConnectionThread();
MOZ_ASSERT(mInReadTransaction);
MOZ_ASSERT(!mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::DoIdleProcessing", DOM);
CachingDatabaseConnection::CachedStatement freelistStmt;
const uint32_t freelistCount = [this, &freelistStmt] {
QM_TRY_RETURN(GetFreelistCount(freelistStmt), 0u);
}();
CachedStatement rollbackStmt;
CachedStatement beginStmt;
if (aNeedsCheckpoint || freelistCount) {
QM_TRY_UNWRAP(rollbackStmt, GetCachedStatement("ROLLBACK;"_ns), QM_VOID);
QM_TRY_UNWRAP(beginStmt, GetCachedStatement("BEGIN;"_ns), QM_VOID);
// Release the connection's normal transaction. It's possible that it could
// fail, but that isn't a problem here.
Unused << rollbackStmt.Borrow()->Execute();
mInReadTransaction = false;
}
const bool freedSomePages =
freelistCount && [this, &freelistStmt, &rollbackStmt, freelistCount,
aNeedsCheckpoint, &aInterrupted] {
// Warn in case of an error, but do not propagate it. Just indicate we
// didn't free any pages.
QM_TRY_INSPECT(
const bool& res,
ReclaimFreePagesWhileIdle(freelistStmt, rollbackStmt, freelistCount,
aNeedsCheckpoint, aInterrupted),
false);
// Make sure we didn't leave a transaction running.
MOZ_ASSERT(!mInReadTransaction);
MOZ_ASSERT(!mInWriteTransaction);
return res;
}();
// Truncate the WAL if we were asked to or if we managed to free some space.
if (aNeedsCheckpoint || freedSomePages) {
QM_WARNONLY_TRY(QM_TO_RESULT(CheckpointInternal(CheckpointMode::Truncate)));
}
// Finally try to restart the read transaction if we rolled it back earlier.
if (beginStmt) {
QM_WARNONLY_TRY(
MOZ_TO_RESULT(beginStmt.Borrow()->Execute())
.andThen([&self = *this](const Ok) -> Result<Ok, nsresult> {
self.mInReadTransaction = true;
return Ok{};
}));
}
}
Result<bool, nsresult> DatabaseConnection::ReclaimFreePagesWhileIdle(
CachedStatement& aFreelistStatement, CachedStatement& aRollbackStatement,
uint32_t aFreelistCount, bool aNeedsCheckpoint,
const Atomic<bool>& aInterrupted) {
AssertIsOnConnectionThread();
MOZ_ASSERT(aFreelistStatement);
MOZ_ASSERT(aRollbackStatement);
MOZ_ASSERT(aFreelistCount);
MOZ_ASSERT(!mInReadTransaction);
MOZ_ASSERT(!mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::ReclaimFreePagesWhileIdle", DOM);
uint32_t pauseOnConnectionThreadMs = StaticPrefs::
dom_indexedDB_connectionIdleMaintenance_pauseOnConnectionThreadMs();
if (pauseOnConnectionThreadMs > 0) {
PR_Sleep(PR_MillisecondsToInterval(pauseOnConnectionThreadMs));
}
// Make sure we don't keep working if anything else needs this thread.
if (aInterrupted) {
return false;
}
// Make all the statements we'll need up front.
// Only try to free 10% at a time so that we can bail out if this connection
// suddenly becomes active or if the thread is needed otherwise.
QM_TRY_INSPECT(
const auto& incrementalVacuumStmt,
GetCachedStatement(
"PRAGMA incremental_vacuum("_ns +
IntToCString(std::max(uint64_t(1), uint64_t(aFreelistCount / 10))) +
");"_ns));
QM_TRY_INSPECT(const auto& beginImmediateStmt,
GetCachedStatement("BEGIN IMMEDIATE;"_ns));
QM_TRY_INSPECT(const auto& commitStmt, GetCachedStatement("COMMIT;"_ns));
if (aNeedsCheckpoint) {
// Freeing pages is a journaled operation, so it will require additional WAL
// space. However, we're idle and are about to checkpoint anyway, so doing a
// RESTART checkpoint here should allow us to reuse any existing space.
QM_TRY(MOZ_TO_RESULT(CheckpointInternal(CheckpointMode::Restart)));
}
// Start the write transaction.
QM_TRY(MOZ_TO_RESULT(beginImmediateStmt.Borrow()->Execute()));
mInWriteTransaction = true;
bool freedSomePages = false;
const auto rollback = [&aRollbackStatement, this](const auto&) {
MOZ_ASSERT(mInWriteTransaction);
// Something failed, make sure we roll everything back.
Unused << aRollbackStatement.Borrow()->Execute();
// XXX Is rollback infallible? Shouldn't we check the result?
mInWriteTransaction = false;
};
uint64_t previousFreelistCount = (uint64_t)aFreelistCount + 1;
QM_TRY(CollectWhile(
[&aFreelistCount, &previousFreelistCount,
&aInterrupted]() -> Result<bool, nsresult> {
if (aInterrupted) {
// On interrupt, abort and roll back this transaction. It's ok
// if we never make progress here because the idle service
// should eventually reclaim this space.
return false;
}
// If we were not able to free anything, we might either see
// a DB that has no auto-vacuum support at all or some other
// (hopefully temporary) condition that prevents vacuum from
// working. Just carry on in non-DEBUG.
bool madeProgress = previousFreelistCount != aFreelistCount;
previousFreelistCount = aFreelistCount;
MOZ_ASSERT(madeProgress);
QM_WARNONLY_TRY(MOZ_TO_RESULT(madeProgress));
return madeProgress && (aFreelistCount != 0);
},
[&aFreelistStatement, &aFreelistCount, &incrementalVacuumStmt,
&freedSomePages, this]() -> mozilla::Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(incrementalVacuumStmt.Borrow()->Execute()));
freedSomePages = true;
QM_TRY_UNWRAP(aFreelistCount,
GetFreelistCount(aFreelistStatement));
return Ok{};
})
.andThen([&commitStmt, &freedSomePages, &aInterrupted, &rollback,
this](Ok) -> Result<Ok, nsresult> {
if (aInterrupted) {
rollback(Ok{});
freedSomePages = false;
}
if (freedSomePages) {
// Commit the write transaction.
QM_TRY(MOZ_TO_RESULT(commitStmt.Borrow()->Execute()),
QM_PROPAGATE,
[](const auto&) { NS_WARNING("Failed to commit!"); });
mInWriteTransaction = false;
}
return Ok{};
}),
QM_PROPAGATE, rollback);
return freedSomePages;
}
Result<uint32_t, nsresult> DatabaseConnection::GetFreelistCount(
CachedStatement& aCachedStatement) {
AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("DatabaseConnection::GetFreelistCount", DOM);
if (!aCachedStatement) {
QM_TRY_UNWRAP(aCachedStatement,
GetCachedStatement("PRAGMA freelist_count;"_ns));
}
const auto borrowedStatement = aCachedStatement.Borrow();
QM_TRY_UNWRAP(const DebugOnly<bool> hasResult,
MOZ_TO_RESULT_INVOKE_MEMBER(&*borrowedStatement, ExecuteStep));
MOZ_ASSERT(hasResult);
QM_TRY_INSPECT(const int32_t& freelistCount,
MOZ_TO_RESULT_INVOKE_MEMBER(*borrowedStatement, GetInt32, 0));
MOZ_ASSERT(freelistCount >= 0);
return uint32_t(freelistCount);
}
void DatabaseConnection::Close() {
AssertIsOnConnectionThread();
MOZ_ASSERT(!mDEBUGSavepointCount);
MOZ_DIAGNOSTIC_ASSERT(!mInWriteTransaction);
AUTO_PROFILER_LABEL("DatabaseConnection::Close", DOM);
if (mUpdateRefcountFunction) {
MOZ_ALWAYS_SUCCEEDS(
MutableStorageConnection().RemoveFunction("update_refcount"_ns));
mUpdateRefcountFunction = nullptr;
}
CachingDatabaseConnection::Close();
mFileManager.destroy();
}
nsresult DatabaseConnection::DisableQuotaChecks() {
AssertIsOnConnectionThread();
MOZ_ASSERT(HasStorageConnection());
if (!mQuotaObject) {
MOZ_ASSERT(!mJournalQuotaObject);
QM_TRY(MOZ_TO_RESULT(MutableStorageConnection().GetQuotaObjects(
getter_AddRefs(mQuotaObject), getter_AddRefs(mJournalQuotaObject))));
MOZ_ASSERT(mQuotaObject);
MOZ_ASSERT(mJournalQuotaObject);
}
mQuotaObject->DisableQuotaCheck();
mJournalQuotaObject->DisableQuotaCheck();
return NS_OK;
}
void DatabaseConnection::EnableQuotaChecks() {
AssertIsOnConnectionThread();
if (!mQuotaObject) {
MOZ_ASSERT(!mJournalQuotaObject);
// DisableQuotaChecks failed earlier, so we don't need to enable quota
// checks again.
return;
}
MOZ_ASSERT(mJournalQuotaObject);
const RefPtr<QuotaObject> quotaObject = std::move(mQuotaObject);
const RefPtr<QuotaObject> journalQuotaObject = std::move(mJournalQuotaObject);
quotaObject->EnableQuotaCheck();
journalQuotaObject->EnableQuotaCheck();
QM_TRY_INSPECT(const int64_t& fileSize, GetFileSize(quotaObject->Path()),
QM_VOID);
QM_TRY_INSPECT(const int64_t& journalFileSize,
GetFileSize(journalQuotaObject->Path()), QM_VOID);
DebugOnly<bool> result = journalQuotaObject->MaybeUpdateSize(
journalFileSize, /* aTruncate */ true);
MOZ_ASSERT(result);
result = quotaObject->MaybeUpdateSize(fileSize, /* aTruncate */ true);
MOZ_ASSERT(result);
}
Result<int64_t, nsresult> DatabaseConnection::GetFileSize(
const nsAString& aPath) {
MOZ_ASSERT(!aPath.IsEmpty());
QM_TRY_INSPECT(const auto& file, QM_NewLocalFile(aPath));
QM_TRY_INSPECT(const bool& exists, MOZ_TO_RESULT_INVOKE_MEMBER(file, Exists));
if (exists) {
QM_TRY_RETURN(MOZ_TO_RESULT_INVOKE_MEMBER(file, GetFileSize));
}
return 0;
}
DatabaseConnection::AutoSavepoint::AutoSavepoint()
: mConnection(nullptr)
#ifdef DEBUG
,
mDEBUGTransaction(nullptr)
#endif
{
MOZ_COUNT_CTOR(DatabaseConnection::AutoSavepoint);
}
DatabaseConnection::AutoSavepoint::~AutoSavepoint() {
MOZ_COUNT_DTOR(DatabaseConnection::AutoSavepoint);
if (mConnection) {
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mDEBUGTransaction);
MOZ_ASSERT(
mDEBUGTransaction->GetMode() == IDBTransaction::Mode::ReadWrite ||
mDEBUGTransaction->GetMode() == IDBTransaction::Mode::ReadWriteFlush ||
mDEBUGTransaction->GetMode() == IDBTransaction::Mode::Cleanup ||
mDEBUGTransaction->GetMode() == IDBTransaction::Mode::VersionChange);
QM_WARNONLY_TRY(QM_TO_RESULT(mConnection->RollbackSavepoint()));
}
}
nsresult DatabaseConnection::AutoSavepoint::Start(
const TransactionBase& aTransaction) {
MOZ_ASSERT(aTransaction.GetMode() == IDBTransaction::Mode::ReadWrite ||
aTransaction.GetMode() == IDBTransaction::Mode::ReadWriteFlush ||
aTransaction.GetMode() == IDBTransaction::Mode::Cleanup ||
aTransaction.GetMode() == IDBTransaction::Mode::VersionChange);
DatabaseConnection* connection = aTransaction.GetDatabase().GetConnection();
MOZ_ASSERT(connection);
connection->AssertIsOnConnectionThread();
// The previous operation failed to begin a write transaction and the
// following opertion jumped to the connection thread before the previous
// operation has updated its failure to the transaction.
if (!connection->GetUpdateRefcountFunction()) {
NS_WARNING(
"The connection was closed because the previous operation "
"failed!");
return NS_ERROR_DOM_INDEXEDDB_ABORT_ERR;
}
MOZ_ASSERT(!mConnection);
MOZ_ASSERT(!mDEBUGTransaction);
QM_TRY(MOZ_TO_RESULT(connection->StartSavepoint()));
mConnection = connection;
#ifdef DEBUG
mDEBUGTransaction = &aTransaction;
#endif
return NS_OK;
}
nsresult DatabaseConnection::AutoSavepoint::Commit() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mDEBUGTransaction);
QM_TRY(MOZ_TO_RESULT(mConnection->ReleaseSavepoint()));
mConnection = nullptr;
#ifdef DEBUG
mDEBUGTransaction = nullptr;
#endif
return NS_OK;
}
DatabaseConnection::UpdateRefcountFunction::UpdateRefcountFunction(
DatabaseConnection* const aConnection, DatabaseFileManager& aFileManager)
: mConnection(aConnection),
mFileManager(aFileManager),
mInSavepoint(false) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
}
nsresult DatabaseConnection::UpdateRefcountFunction::WillCommit() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mConnection->HasStorageConnection());
AUTO_PROFILER_LABEL("DatabaseConnection::UpdateRefcountFunction::WillCommit",
DOM);
// The parameter names are not used, parameters are bound by index
// only locally in the same function.
auto update =
[updateStatement = LazyStatement{*mConnection,
"UPDATE file "
"SET refcount = refcount + :delta "
"WHERE id = :id"_ns},
selectStatement = LazyStatement{*mConnection,
"SELECT id "
"FROM file "
"WHERE id = :id"_ns},
insertStatement =
LazyStatement{
*mConnection,
"INSERT INTO file (id, refcount) VALUES(:id, :delta)"_ns},
this](int64_t aId, int32_t aDelta) mutable -> Result<Ok, nsresult> {
AUTO_PROFILER_LABEL(
"DatabaseConnection::UpdateRefcountFunction::WillCommit::Update", DOM);
{
QM_TRY_INSPECT(const auto& borrowedUpdateStatement,
updateStatement.Borrow());
QM_TRY(
MOZ_TO_RESULT(borrowedUpdateStatement->BindInt32ByIndex(0, aDelta)));
QM_TRY(MOZ_TO_RESULT(borrowedUpdateStatement->BindInt64ByIndex(1, aId)));
QM_TRY(MOZ_TO_RESULT(borrowedUpdateStatement->Execute()));
}
QM_TRY_INSPECT(
const int32_t& rows,
MOZ_TO_RESULT_INVOKE_MEMBER(mConnection->MutableStorageConnection(),
GetAffectedRows));
if (rows > 0) {
QM_TRY_INSPECT(
const bool& hasResult,
selectStatement
.BorrowAndExecuteSingleStep(
[aId](auto& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(0, aId)));
return Ok{};
})
.map(IsSome));
if (!hasResult) {
// Don't have to create the journal here, we can create all at once,
// just before commit
mJournalsToCreateBeforeCommit.AppendElement(aId);
}
return Ok{};
}
QM_TRY_INSPECT(const auto& borrowedInsertStatement,
insertStatement.Borrow());
QM_TRY(MOZ_TO_RESULT(borrowedInsertStatement->BindInt64ByIndex(0, aId)));
QM_TRY(MOZ_TO_RESULT(borrowedInsertStatement->BindInt32ByIndex(1, aDelta)));
QM_TRY(MOZ_TO_RESULT(borrowedInsertStatement->Execute()));
mJournalsToRemoveAfterCommit.AppendElement(aId);
return Ok{};
};
QM_TRY(CollectEachInRange(
mFileInfoEntries, [&update](const auto& entry) -> Result<Ok, nsresult> {
const auto delta = entry.GetData()->Delta();
if (delta) {
QM_TRY(update(entry.GetKey(), delta));
}
return Ok{};
}));
QM_TRY(MOZ_TO_RESULT(CreateJournals()));
return NS_OK;
}
void DatabaseConnection::UpdateRefcountFunction::DidCommit() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("DatabaseConnection::UpdateRefcountFunction::DidCommit",
DOM);
for (const auto& entry : mFileInfoEntries.Values()) {
entry->MaybeUpdateDBRefs();
}
QM_WARNONLY_TRY(QM_TO_RESULT(RemoveJournals(mJournalsToRemoveAfterCommit)));
}
void DatabaseConnection::UpdateRefcountFunction::DidAbort() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("DatabaseConnection::UpdateRefcountFunction::DidAbort",
DOM);
QM_WARNONLY_TRY(QM_TO_RESULT(RemoveJournals(mJournalsToRemoveAfterAbort)));
}
void DatabaseConnection::UpdateRefcountFunction::StartSavepoint() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(!mInSavepoint);
MOZ_ASSERT(!mSavepointEntriesIndex.Count());
mInSavepoint = true;
}
void DatabaseConnection::UpdateRefcountFunction::ReleaseSavepoint() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mInSavepoint);
mSavepointEntriesIndex.Clear();
mInSavepoint = false;
}
void DatabaseConnection::UpdateRefcountFunction::RollbackSavepoint() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(mInSavepoint);
for (const auto& entry : mSavepointEntriesIndex.Values()) {
entry->DecBySavepointDelta();
}
mInSavepoint = false;
mSavepointEntriesIndex.Clear();
}
void DatabaseConnection::UpdateRefcountFunction::Reset() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(!mSavepointEntriesIndex.Count());
MOZ_ASSERT(!mInSavepoint);
mJournalsToCreateBeforeCommit.Clear();
mJournalsToRemoveAfterCommit.Clear();
mJournalsToRemoveAfterAbort.Clear();
// DatabaseFileInfo implementation automatically removes unreferenced files,
// but it's done asynchronously and with a delay. We want to remove them (and
// decrease quota usage) before we fire the commit event.
for (const auto& entry : mFileInfoEntries.Values()) {
// We need to move mFileInfo into a raw pointer in order to release it
// explicitly with aSyncDeleteFile == true.
DatabaseFileInfo* const fileInfo = entry->ReleaseFileInfo().forget().take();
MOZ_ASSERT(fileInfo);
fileInfo->Release(/* aSyncDeleteFile */ true);
}
mFileInfoEntries.Clear();
}
nsresult DatabaseConnection::UpdateRefcountFunction::ProcessValue(
mozIStorageValueArray* aValues, int32_t aIndex, UpdateType aUpdateType) {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(aValues);
AUTO_PROFILER_LABEL(
"DatabaseConnection::UpdateRefcountFunction::ProcessValue", DOM);
QM_TRY_INSPECT(const int32_t& type,
MOZ_TO_RESULT_INVOKE_MEMBER(aValues, GetTypeOfIndex, aIndex));
if (type == mozIStorageValueArray::VALUE_TYPE_NULL) {
return NS_OK;
}
QM_TRY_INSPECT(const auto& ids, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, aValues, GetString, aIndex));
QM_TRY_INSPECT(const auto& files,
DeserializeStructuredCloneFiles(mFileManager, ids));
for (const StructuredCloneFileParent& file : files) {
const int64_t id = file.FileInfo().Id();
MOZ_ASSERT(id > 0);
const auto entry =
WrapNotNull(mFileInfoEntries.GetOrInsertNew(id, file.FileInfoPtr()));
if (mInSavepoint) {
mSavepointEntriesIndex.InsertOrUpdate(id, entry);
}
switch (aUpdateType) {
case UpdateType::Increment:
entry->IncDeltas(mInSavepoint);
break;
case UpdateType::Decrement:
entry->DecDeltas(mInSavepoint);
break;
default:
MOZ_CRASH("Unknown update type!");
}
}
return NS_OK;
}
nsresult DatabaseConnection::UpdateRefcountFunction::CreateJournals() {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL(
"DatabaseConnection::UpdateRefcountFunction::CreateJournals", DOM);
const nsCOMPtr<nsIFile> journalDirectory = mFileManager.GetJournalDirectory();
QM_TRY(OkIf(journalDirectory), NS_ERROR_FAILURE);
for (const int64_t id : mJournalsToCreateBeforeCommit) {
const nsCOMPtr<nsIFile> file =
DatabaseFileManager::GetFileForId(journalDirectory, id);
QM_TRY(OkIf(file), NS_ERROR_FAILURE);
QM_TRY(MOZ_TO_RESULT(file->Create(nsIFile::NORMAL_FILE_TYPE, 0644)));
mJournalsToRemoveAfterAbort.AppendElement(id);
}
return NS_OK;
}
nsresult DatabaseConnection::UpdateRefcountFunction::RemoveJournals(
const nsTArray<int64_t>& aJournals) {
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL(
"DatabaseConnection::UpdateRefcountFunction::RemoveJournals", DOM);
nsCOMPtr<nsIFile> journalDirectory = mFileManager.GetJournalDirectory();
QM_TRY(OkIf(journalDirectory), NS_ERROR_FAILURE);
for (const auto& journal : aJournals) {
nsCOMPtr<nsIFile> file =
DatabaseFileManager::GetFileForId(journalDirectory, journal);
QM_TRY(OkIf(file), NS_ERROR_FAILURE);
QM_WARNONLY_TRY(QM_TO_RESULT(file->Remove(false)));
}
return NS_OK;
}
NS_IMPL_ISUPPORTS(DatabaseConnection::UpdateRefcountFunction,
mozIStorageFunction)
NS_IMETHODIMP
DatabaseConnection::UpdateRefcountFunction::OnFunctionCall(
mozIStorageValueArray* aValues, nsIVariant** _retval) {
MOZ_ASSERT(aValues);
MOZ_ASSERT(_retval);
AUTO_PROFILER_LABEL(
"DatabaseConnection::UpdateRefcountFunction::OnFunctionCall", DOM);
#ifdef DEBUG
{
QM_TRY_INSPECT(const uint32_t& numEntries,
MOZ_TO_RESULT_INVOKE_MEMBER(aValues, GetNumEntries),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(numEntries == 2);
QM_TRY_INSPECT(const int32_t& type1,
MOZ_TO_RESULT_INVOKE_MEMBER(aValues, GetTypeOfIndex, 0),
QM_ASSERT_UNREACHABLE);
QM_TRY_INSPECT(const int32_t& type2,
MOZ_TO_RESULT_INVOKE_MEMBER(aValues, GetTypeOfIndex, 1),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(!(type1 == mozIStorageValueArray::VALUE_TYPE_NULL &&
type2 == mozIStorageValueArray::VALUE_TYPE_NULL));
}
#endif
QM_TRY(MOZ_TO_RESULT(ProcessValue(aValues, 0, UpdateType::Decrement)));
QM_TRY(MOZ_TO_RESULT(ProcessValue(aValues, 1, UpdateType::Increment)));
return NS_OK;
}
/*******************************************************************************
* ConnectionPool implementation
******************************************************************************/
ConnectionPool::ConnectionPool()
: mDatabasesMutex("ConnectionPool::mDatabasesMutex"),
mIOTarget(MakeConnectionIOTarget()),
mIdleTimer(NS_NewTimer()),
mNextTransactionId(0) {
AssertIsOnOwningThread();
AssertIsOnBackgroundThread();
MOZ_ASSERT(mIdleTimer);
}
ConnectionPool::~ConnectionPool() {
AssertIsOnOwningThread();
MOZ_ASSERT(mIdleDatabases.IsEmpty());
MOZ_ASSERT(!mIdleTimer);
MOZ_ASSERT(mTargetIdleTime.IsNull());
MOZ_ASSERT(!mDatabases.Count());
MOZ_ASSERT(!mTransactions.Count());
MOZ_ASSERT(mQueuedTransactions.IsEmpty());
MOZ_ASSERT(mCompleteCallbacks.IsEmpty());
MOZ_ASSERT(mShutdownRequested);
MOZ_ASSERT(mShutdownComplete);
}
// static
void ConnectionPool::IdleTimerCallback(nsITimer* aTimer, void* aClosure) {
MOZ_ASSERT(aTimer);
MOZ_ASSERT(aClosure);
AUTO_PROFILER_LABEL("ConnectionPool::IdleTimerCallback", DOM);
auto& self = *static_cast<ConnectionPool*>(aClosure);
MOZ_ASSERT(self.mIdleTimer);
MOZ_ASSERT(SameCOMIdentity(self.mIdleTimer, aTimer));
MOZ_ASSERT(!self.mTargetIdleTime.IsNull());
self.mTargetIdleTime = TimeStamp();
// Cheat a little.
const TimeStamp now =
TimeStamp::NowLoRes() + TimeDuration::FromMilliseconds(500);
// XXX Move this to ArrayAlgorithm.h?
const auto removeUntil = [](auto& array, auto&& cond) {
const auto begin = array.begin(), end = array.end();
array.RemoveElementsRange(
begin, std::find_if(begin, end, std::forward<decltype(cond)>(cond)));
};
removeUntil(self.mIdleDatabases, [now, &self](const auto& info) {
if (now >= info.mIdleTime) {
if ((*info.mDatabaseInfo)->mIdle) {
self.PerformIdleDatabaseMaintenance(*info.mDatabaseInfo.ref());
} else {
self.CloseDatabase(*info.mDatabaseInfo.ref());
}
return false;
}
return true;
});
self.AdjustIdleTimer();
}
Result<RefPtr<DatabaseConnection>, nsresult>
ConnectionPool::GetOrCreateConnection(const Database& aDatabase) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
AUTO_PROFILER_LABEL("ConnectionPool::GetOrCreateConnection", DOM);
DatabaseInfo* dbInfo;
{
MutexAutoLock lock(mDatabasesMutex);
dbInfo = mDatabases.Get(aDatabase.Id());
}
MOZ_ASSERT(dbInfo);
if (dbInfo->mConnection) {
dbInfo->AssertIsOnConnectionThread();
return dbInfo->mConnection;
}
MOZ_ASSERT(!dbInfo->mDEBUGConnectionEventTarget);
QM_TRY_UNWRAP(
MovingNotNull<nsCOMPtr<mozIStorageConnection>> storageConnection,
GetStorageConnection(aDatabase.FilePath(), aDatabase.DirectoryLockId(),
aDatabase.TelemetryId(), aDatabase.MaybeKeyRef()));
RefPtr<DatabaseConnection> connection = new DatabaseConnection(
std::move(storageConnection), aDatabase.GetFileManagerPtr());
QM_TRY(MOZ_TO_RESULT(connection->Init()));
dbInfo->mConnection = connection;
IDB_DEBUG_LOG(("ConnectionPool created connection 0x%p for '%s'",
dbInfo->mConnection.get(),
NS_ConvertUTF16toUTF8(aDatabase.FilePath()).get()));
#ifdef DEBUG
dbInfo->mDEBUGConnectionEventTarget = GetCurrentSerialEventTarget();
#endif
return connection;
}
uint64_t ConnectionPool::Start(
const nsID& aBackgroundChildLoggingId, const nsACString& aDatabaseId,
int64_t aLoggingSerialNumber, const nsTArray<nsString>& aObjectStoreNames,
bool aIsWriteTransaction,
TransactionDatabaseOperationBase* aTransactionOp) {
AssertIsOnOwningThread();
MOZ_ASSERT(!aDatabaseId.IsEmpty());
MOZ_ASSERT(mNextTransactionId < UINT64_MAX);
MOZ_ASSERT(!mShutdownRequested);
AUTO_PROFILER_LABEL("ConnectionPool::Start", DOM);
const uint64_t transactionId = ++mNextTransactionId;
// To avoid always acquiring a lock, we don't use WithEntryHandle here, which
// would require a lock in any case.
DatabaseInfo* dbInfo = mDatabases.Get(aDatabaseId);
const bool databaseInfoIsNew = !dbInfo;
if (databaseInfoIsNew) {
MutexAutoLock lock(mDatabasesMutex);
dbInfo = mDatabases
.InsertOrUpdate(aDatabaseId,
MakeUnique<DatabaseInfo>(this, aDatabaseId))
.get();
}
MOZ_ASSERT(!mTransactions.Contains(transactionId));
auto& transactionInfo = *mTransactions.InsertOrUpdate(
transactionId, MakeUnique<TransactionInfo>(
*dbInfo, aBackgroundChildLoggingId, aDatabaseId,
transactionId, aLoggingSerialNumber, aObjectStoreNames,
aIsWriteTransaction, aTransactionOp));
if (aIsWriteTransaction) {
MOZ_ASSERT(dbInfo->mWriteTransactionCount < UINT32_MAX);
dbInfo->mWriteTransactionCount++;
} else {
MOZ_ASSERT(dbInfo->mReadTransactionCount < UINT32_MAX);
dbInfo->mReadTransactionCount++;
}
auto& blockingTransactions = dbInfo->mBlockingTransactions;
for (const nsAString& objectStoreName : aObjectStoreNames) {
TransactionInfoPair* blockInfo =
blockingTransactions.GetOrInsertNew(objectStoreName);
// Mark what we are blocking on.
if (const auto maybeBlockingRead = blockInfo->mLastBlockingReads) {
transactionInfo.mBlockedOn.Insert(&maybeBlockingRead.ref());
maybeBlockingRead->AddBlockingTransaction(transactionInfo);
}
if (aIsWriteTransaction) {
for (const auto blockingWrite : blockInfo->mLastBlockingWrites) {
transactionInfo.mBlockedOn.Insert(blockingWrite);
blockingWrite->AddBlockingTransaction(transactionInfo);
}
blockInfo->mLastBlockingReads = SomeRef(transactionInfo);
blockInfo->mLastBlockingWrites.Clear();
} else {
blockInfo->mLastBlockingWrites.AppendElement(
WrapNotNullUnchecked(&transactionInfo));
}
}
if (!transactionInfo.mBlockedOn.Count()) {
Unused << ScheduleTransaction(transactionInfo,
/* aFromQueuedTransactions */ false);
}
if (!databaseInfoIsNew &&
(mIdleDatabases.RemoveElement(dbInfo) ||
mDatabasesPerformingIdleMaintenance.RemoveElement(dbInfo))) {
AdjustIdleTimer();
}
return transactionId;
}
void ConnectionPool::StartOp(uint64_t aTransactionId,
nsCOMPtr<nsIRunnable> aRunnable) {
AssertIsOnOwningThread();
AUTO_PROFILER_LABEL("ConnectionPool::StartOp", DOM);
auto* const transactionInfo = mTransactions.Get(aTransactionId);
MOZ_ASSERT(transactionInfo);
transactionInfo->StartOp(std::move(aRunnable));
}
void ConnectionPool::FinishOp(uint64_t aTransactionId) {
AssertIsOnOwningThread();
AUTO_PROFILER_LABEL("ConnectionPool::FinishOp", DOM);
auto* const transactionInfo = mTransactions.Get(aTransactionId);
MOZ_ASSERT(transactionInfo);
transactionInfo->FinishOp();
}
void ConnectionPool::Finish(uint64_t aTransactionId,
FinishCallback* aCallback) {
AssertIsOnOwningThread();
#ifdef DEBUG
auto* const transactionInfo = mTransactions.Get(aTransactionId);
MOZ_ASSERT(transactionInfo);
MOZ_ASSERT(!transactionInfo->mFinished);
#endif
AUTO_PROFILER_LABEL("ConnectionPool::Finish", DOM);
nsCOMPtr<nsIRunnable> wrapper =
new FinishCallbackWrapper(this, aTransactionId, aCallback);
StartOp(aTransactionId, std::move(wrapper));
#ifdef DEBUG
transactionInfo->mFinished.Flip();
#endif
}
void ConnectionPool::WaitForDatabaseToComplete(const nsCString& aDatabaseId,
nsIRunnable* aCallback) {
AssertIsOnOwningThread();
MOZ_ASSERT(!aDatabaseId.IsEmpty());
MOZ_ASSERT(aCallback);
AUTO_PROFILER_LABEL("ConnectionPool::WaitForDatabaseToComplete", DOM);
if (!CloseDatabaseWhenIdleInternal(aDatabaseId)) {
Unused << aCallback->Run();
return;
}
mCompleteCallbacks.EmplaceBack(
MakeUnique<DatabaseCompleteCallback>(aDatabaseId, aCallback));
}
void ConnectionPool::Shutdown() {
AssertIsOnOwningThread();
MOZ_ASSERT(!mShutdownComplete);
AUTO_PROFILER_LABEL("ConnectionPool::Shutdown", DOM);
mShutdownRequested.Flip();
CancelIdleTimer();
MOZ_ASSERT(mTargetIdleTime.IsNull());
mIdleTimer = nullptr;
CloseIdleDatabases();
if (!mDatabases.Count()) {
MOZ_ASSERT(!mTransactions.Count());
Cleanup();
MOZ_ASSERT(mShutdownComplete);
mIOTarget->Shutdown();
return;
}
MOZ_ALWAYS_TRUE(SpinEventLoopUntil("ConnectionPool::Shutdown"_ns, [&]() {
return static_cast<bool>(mShutdownComplete);
}));
mIOTarget->Shutdown();
}
void ConnectionPool::Cleanup() {
AssertIsOnOwningThread();
MOZ_ASSERT(mShutdownRequested);
MOZ_ASSERT(!mShutdownComplete);
MOZ_ASSERT(!mDatabases.Count());
MOZ_ASSERT(!mTransactions.Count());
AUTO_PROFILER_LABEL("ConnectionPool::Cleanup", DOM);
if (!mCompleteCallbacks.IsEmpty()) {
// Run all callbacks manually now.
{
auto completeCallbacks = std::move(mCompleteCallbacks);
for (const auto& completeCallback : completeCallbacks) {
MOZ_ASSERT(completeCallback);
MOZ_ASSERT(completeCallback->mCallback);
Unused << completeCallback->mCallback->Run();
}
// We expect no new callbacks being completed by running the existing
// ones.
MOZ_ASSERT(mCompleteCallbacks.IsEmpty());
}
// And make sure they get processed.
nsIThread* currentThread = NS_GetCurrentThread();
MOZ_ASSERT(currentThread);
MOZ_ALWAYS_SUCCEEDS(NS_ProcessPendingEvents(currentThread));
}
mShutdownComplete.Flip();
}
void ConnectionPool::AdjustIdleTimer() {
AssertIsOnOwningThread();
MOZ_ASSERT(mIdleTimer);
AUTO_PROFILER_LABEL("ConnectionPool::AdjustIdleTimer", DOM);
// Figure out the next time at which we should release idle resources. This
// includes both databases and threads.
TimeStamp newTargetIdleTime;
MOZ_ASSERT(newTargetIdleTime.IsNull());
if (!mIdleDatabases.IsEmpty()) {
newTargetIdleTime = mIdleDatabases[0].mIdleTime;
}
MOZ_ASSERT_IF(newTargetIdleTime.IsNull(), mIdleDatabases.IsEmpty());
// Cancel the timer if it was running and the new target time is different.
if (!mTargetIdleTime.IsNull() &&
(newTargetIdleTime.IsNull() || mTargetIdleTime != newTargetIdleTime)) {
CancelIdleTimer();
MOZ_ASSERT(mTargetIdleTime.IsNull());
}
// Schedule the timer if we have a target time different than before.
if (!newTargetIdleTime.IsNull() &&
(mTargetIdleTime.IsNull() || mTargetIdleTime != newTargetIdleTime)) {
double delta = (newTargetIdleTime - TimeStamp::NowLoRes()).ToMilliseconds();
uint32_t delay;
if (delta > 0) {
delay = uint32_t(std::min(delta, double(UINT32_MAX)));
} else {
delay = 0;
}
MOZ_ALWAYS_SUCCEEDS(mIdleTimer->InitWithNamedFuncCallback(
IdleTimerCallback, this, delay, nsITimer::TYPE_ONE_SHOT,
"ConnectionPool::IdleTimerCallback"));
mTargetIdleTime = newTargetIdleTime;
}
}
void ConnectionPool::CancelIdleTimer() {
AssertIsOnOwningThread();
MOZ_ASSERT(mIdleTimer);
if (!mTargetIdleTime.IsNull()) {
MOZ_ALWAYS_SUCCEEDS(mIdleTimer->Cancel());
mTargetIdleTime = TimeStamp();
MOZ_ASSERT(mTargetIdleTime.IsNull());
}
}
void ConnectionPool::CloseIdleDatabases() {
AssertIsOnOwningThread();
MOZ_ASSERT(mShutdownRequested);
AUTO_PROFILER_LABEL("ConnectionPool::CloseIdleDatabases", DOM);
if (!mIdleDatabases.IsEmpty()) {
for (IdleDatabaseInfo& idleInfo : mIdleDatabases) {
CloseDatabase(*idleInfo.mDatabaseInfo.ref());
}
mIdleDatabases.Clear();
}
if (!mDatabasesPerformingIdleMaintenance.IsEmpty()) {
for (PerformingIdleMaintenanceDatabaseInfo& performingIdleMaintenanceInfo :
mDatabasesPerformingIdleMaintenance) {
CloseDatabase(*performingIdleMaintenanceInfo.mDatabaseInfo);
}
mDatabasesPerformingIdleMaintenance.Clear();
}
}
bool ConnectionPool::ScheduleTransaction(TransactionInfo& aTransactionInfo,
bool aFromQueuedTransactions) {
AssertIsOnOwningThread();
AUTO_PROFILER_LABEL("ConnectionPool::ScheduleTransaction", DOM);
DatabaseInfo& dbInfo = aTransactionInfo.mDatabaseInfo;
dbInfo.mIdle = false;
if (dbInfo.mClosing) {
MOZ_ASSERT(!mIdleDatabases.Contains(&dbInfo));
MOZ_ASSERT(
!dbInfo.mTransactionsScheduledDuringClose.Contains(&aTransactionInfo));
dbInfo.mTransactionsScheduledDuringClose.AppendElement(
WrapNotNullUnchecked(&aTransactionInfo));
return true;
}
if (!dbInfo.mEventTarget) {
const uint32_t serialNumber = SerialNumber();
const nsCString serialName =
nsPrintfCString("IndexedDB #%" PRIu32, serialNumber);
dbInfo.mEventTarget =
TaskQueue::Create(do_AddRef(mIOTarget), serialName.get());
MOZ_ASSERT(dbInfo.mEventTarget);
IDB_DEBUG_LOG(("ConnectionPool created task queue %" PRIu32, serialNumber));
}
// The number of active operations equals the number of databases minus idle
// databases. The maximum number of database operations which can make
// progress at the same time is kMaxConnectionThreadCount. If we are at this
// limit, all idle processing is interrupted to make room for user
// transactions.
if (mDatabases.Count() >=
(mIdleDatabases.Length() + kMaxConnectionThreadCount) &&
!mDatabasesPerformingIdleMaintenance.IsEmpty()) {
const auto& busyDbs = mDatabasesPerformingIdleMaintenance;
for (auto dbInfo = busyDbs.rbegin(); dbInfo != busyDbs.rend(); ++dbInfo) {
(*dbInfo).mIdleConnectionRunnable->Interrupt();
}
}
if (aTransactionInfo.mIsWriteTransaction) {
if (dbInfo.mRunningWriteTransaction) {
// SQLite only allows one write transaction at a time so queue this
// transaction for later.
MOZ_ASSERT(
!dbInfo.mScheduledWriteTransactions.Contains(&aTransactionInfo));
dbInfo.mScheduledWriteTransactions.AppendElement(
WrapNotNullUnchecked(&aTransactionInfo));
return true;
}
dbInfo.mRunningWriteTransaction = SomeRef(aTransactionInfo);
dbInfo.mNeedsCheckpoint = true;
}
aTransactionInfo.SetRunning();
return true;
}
void ConnectionPool::NoteFinishedTransaction(uint64_t aTransactionId) {
AssertIsOnOwningThread();
AUTO_PROFILER_LABEL("ConnectionPool::NoteFinishedTransaction", DOM);
auto* const transactionInfo = mTransactions.Get(aTransactionId);
MOZ_ASSERT(transactionInfo);
MOZ_ASSERT(transactionInfo->mRunning);
MOZ_ASSERT(transactionInfo->mFinished);
transactionInfo->mRunning = false;
DatabaseInfo& dbInfo = transactionInfo->mDatabaseInfo;
MOZ_ASSERT(mDatabases.Get(transactionInfo->mDatabaseId) == &dbInfo);
MOZ_ASSERT(dbInfo.mEventTarget);
// Schedule the next write transaction if there are any queued.
if (dbInfo.mRunningWriteTransaction &&
dbInfo.mRunningWriteTransaction.refEquals(*transactionInfo)) {
MOZ_ASSERT(transactionInfo->mIsWriteTransaction);
MOZ_ASSERT(dbInfo.mNeedsCheckpoint);
dbInfo.mRunningWriteTransaction = Nothing();
if (!dbInfo.mScheduledWriteTransactions.IsEmpty()) {
const auto nextWriteTransaction = dbInfo.mScheduledWriteTransactions[0];
dbInfo.mScheduledWriteTransactions.RemoveElementAt(0);
MOZ_ALWAYS_TRUE(ScheduleTransaction(*nextWriteTransaction,
/* aFromQueuedTransactions */ false));
}
}
for (const auto& objectStoreName : transactionInfo->mObjectStoreNames) {
TransactionInfoPair* blockInfo =
dbInfo.mBlockingTransactions.Get(objectStoreName);
MOZ_ASSERT(blockInfo);
if (transactionInfo->mIsWriteTransaction && blockInfo->mLastBlockingReads &&
blockInfo->mLastBlockingReads.refEquals(*transactionInfo)) {
blockInfo->mLastBlockingReads = Nothing();
}
blockInfo->mLastBlockingWrites.RemoveElement(transactionInfo);
}
transactionInfo->RemoveBlockingTransactions();
if (transactionInfo->mIsWriteTransaction) {
MOZ_ASSERT(dbInfo.mWriteTransactionCount);
dbInfo.mWriteTransactionCount--;
} else {
MOZ_ASSERT(dbInfo.mReadTransactionCount);
dbInfo.mReadTransactionCount--;
}
mTransactions.Remove(aTransactionId);
if (!dbInfo.TotalTransactionCount()) {
MOZ_ASSERT(!dbInfo.mIdle);
dbInfo.mIdle = true;
NoteIdleDatabase(dbInfo);
}
}
void ConnectionPool::ScheduleQueuedTransactions() {
AssertIsOnOwningThread();
MOZ_ASSERT(!mQueuedTransactions.IsEmpty());
AUTO_PROFILER_LABEL("ConnectionPool::ScheduleQueuedTransactions", DOM);
const auto foundIt = std::find_if(
mQueuedTransactions.begin(), mQueuedTransactions.end(),
[&me = *this](const auto& queuedTransaction) {
return !me.ScheduleTransaction(*queuedTransaction,
/* aFromQueuedTransactions */ true);
});
mQueuedTransactions.RemoveElementsRange(mQueuedTransactions.begin(), foundIt);
AdjustIdleTimer();
}
void ConnectionPool::NoteIdleDatabase(DatabaseInfo& aDatabaseInfo) {
AssertIsOnOwningThread();
MOZ_ASSERT(!aDatabaseInfo.TotalTransactionCount());
MOZ_ASSERT(aDatabaseInfo.mEventTarget);
MOZ_ASSERT(!mIdleDatabases.Contains(&aDatabaseInfo));
AUTO_PROFILER_LABEL("ConnectionPool::NoteIdleDatabase", DOM);
const bool otherDatabasesWaiting = !mQueuedTransactions.IsEmpty();
// We check mShutdownRequested because when it is true, mIdleTimer is null.
if (mShutdownRequested || otherDatabasesWaiting ||
aDatabaseInfo.mCloseOnIdle) {
// Make sure we close the connection if we're shutting down or giving the
// thread to another database.
CloseDatabase(aDatabaseInfo);
if (otherDatabasesWaiting) {
ScheduleQueuedTransactions();
}
return;
}
mIdleDatabases.InsertElementSorted(IdleDatabaseInfo{aDatabaseInfo});
AdjustIdleTimer();
}
void ConnectionPool::NoteClosedDatabase(DatabaseInfo& aDatabaseInfo) {
AssertIsOnOwningThread();
MOZ_ASSERT(aDatabaseInfo.mClosing);
MOZ_ASSERT(!mIdleDatabases.Contains(&aDatabaseInfo));
AUTO_PROFILER_LABEL("ConnectionPool::NoteClosedDatabase", DOM);
aDatabaseInfo.mClosing = false;
// Schedule any transactions that were started while we were closing the
// connection.
if (!mQueuedTransactions.IsEmpty()) {
ScheduleQueuedTransactions();
} else if (!aDatabaseInfo.TotalTransactionCount() && !mShutdownRequested) {
AdjustIdleTimer();
}
// Schedule any transactions that were started while we were closing the
// connection.
if (aDatabaseInfo.TotalTransactionCount()) {
auto& scheduledTransactions =
aDatabaseInfo.mTransactionsScheduledDuringClose;
MOZ_ASSERT(!scheduledTransactions.IsEmpty());
for (const auto& scheduledTransaction : scheduledTransactions) {
Unused << ScheduleTransaction(*scheduledTransaction,
/* aFromQueuedTransactions */ false);
}
scheduledTransactions.Clear();
return;
}
// There are no more transactions and the connection has been closed. We're
// done with this database.
{
MutexAutoLock lock(mDatabasesMutex);
mDatabases.Remove(aDatabaseInfo.mDatabaseId);
}
// That just deleted |aDatabaseInfo|, we must not access that below.
// See if we need to fire any complete callbacks now that the database is
// finished.
mCompleteCallbacks.RemoveLastElements(
mCompleteCallbacks.end() -
std::remove_if(mCompleteCallbacks.begin(), mCompleteCallbacks.end(),
[&me = *this](const auto& completeCallback) {
return me.MaybeFireCallback(completeCallback.get());
}));
// If that was the last database and we're supposed to be shutting down then
// we are finished.
if (mShutdownRequested && !mDatabases.Count()) {
MOZ_ASSERT(!mTransactions.Count());
Cleanup();
}
}
bool ConnectionPool::MaybeFireCallback(DatabaseCompleteCallback* aCallback) {
AssertIsOnOwningThread();
MOZ_ASSERT(aCallback);
MOZ_ASSERT(!aCallback->mDatabaseId.IsEmpty());
MOZ_ASSERT(aCallback->mCallback);
AUTO_PROFILER_LABEL("ConnectionPool::MaybeFireCallback", DOM);
if (mDatabases.Get(aCallback->mDatabaseId)) {
return false;
}
Unused << aCallback->mCallback->Run();
return true;
}
void ConnectionPool::PerformIdleDatabaseMaintenance(
DatabaseInfo& aDatabaseInfo) {
AssertIsOnOwningThread();
MOZ_ASSERT(!aDatabaseInfo.TotalTransactionCount());
MOZ_ASSERT(aDatabaseInfo.mEventTarget);
MOZ_ASSERT(aDatabaseInfo.mIdle);
MOZ_ASSERT(!aDatabaseInfo.mCloseOnIdle);
MOZ_ASSERT(!aDatabaseInfo.mClosing);
MOZ_ASSERT(mIdleDatabases.Contains(&aDatabaseInfo));
MOZ_ASSERT(!mDatabasesPerformingIdleMaintenance.Contains(&aDatabaseInfo));
const bool neededCheckpoint = aDatabaseInfo.mNeedsCheckpoint;
aDatabaseInfo.mNeedsCheckpoint = false;
aDatabaseInfo.mIdle = false;
auto idleConnectionRunnable =
MakeRefPtr<IdleConnectionRunnable>(aDatabaseInfo, neededCheckpoint);
mDatabasesPerformingIdleMaintenance.AppendElement(
PerformingIdleMaintenanceDatabaseInfo{aDatabaseInfo,
idleConnectionRunnable});
MOZ_ALWAYS_SUCCEEDS(aDatabaseInfo.mEventTarget->Dispatch(
idleConnectionRunnable.forget(), NS_DISPATCH_NORMAL));
}
void ConnectionPool::CloseDatabase(DatabaseInfo& aDatabaseInfo) const {
AssertIsOnOwningThread();
MOZ_DIAGNOSTIC_ASSERT(!aDatabaseInfo.TotalTransactionCount());
MOZ_ASSERT(aDatabaseInfo.mEventTarget);
MOZ_ASSERT(!aDatabaseInfo.mClosing);
aDatabaseInfo.mIdle = false;
aDatabaseInfo.mNeedsCheckpoint = false;
aDatabaseInfo.mClosing = true;
MOZ_ALWAYS_SUCCEEDS(aDatabaseInfo.Dispatch(
MakeAndAddRef<CloseConnectionRunnable>(aDatabaseInfo)));
}
bool ConnectionPool::CloseDatabaseWhenIdleInternal(
const nsACString& aDatabaseId) {
AssertIsOnOwningThread();
MOZ_ASSERT(!aDatabaseId.IsEmpty());
AUTO_PROFILER_LABEL("ConnectionPool::CloseDatabaseWhenIdleInternal", DOM);
if (DatabaseInfo* dbInfo = mDatabases.Get(aDatabaseId)) {
if (mIdleDatabases.RemoveElement(dbInfo) ||
mDatabasesPerformingIdleMaintenance.RemoveElement(dbInfo)) {
CloseDatabase(*dbInfo);
AdjustIdleTimer();
} else {
dbInfo->mCloseOnIdle.EnsureFlipped();
}
return true;
}
return false;
}
ConnectionPool::ConnectionRunnable::ConnectionRunnable(
DatabaseInfo& aDatabaseInfo)
: Runnable("dom::indexedDB::ConnectionPool::ConnectionRunnable"),
mDatabaseInfo(aDatabaseInfo),
mOwningEventTarget(GetCurrentSerialEventTarget()) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aDatabaseInfo.mConnectionPool);
aDatabaseInfo.mConnectionPool->AssertIsOnOwningThread();
MOZ_ASSERT(mOwningEventTarget);
}
NS_IMETHODIMP
ConnectionPool::IdleConnectionRunnable::Run() {
MOZ_ASSERT(!mDatabaseInfo.mIdle);
const nsCOMPtr<nsIEventTarget> owningThread = std::move(mOwningEventTarget);
if (owningThread) {
mDatabaseInfo.AssertIsOnConnectionThread();
// The connection could be null if EnsureConnection() didn't run or was not
// successful in TransactionDatabaseOperationBase::RunOnConnectionThread().
if (mDatabaseInfo.mConnection) {
mDatabaseInfo.mConnection->DoIdleProcessing(mNeedsCheckpoint,
mInterrupted);
}
MOZ_ALWAYS_SUCCEEDS(owningThread->Dispatch(this, NS_DISPATCH_NORMAL));
return NS_OK;
}
AssertIsOnBackgroundThread();
RefPtr<ConnectionPool> connectionPool = mDatabaseInfo.mConnectionPool;
MOZ_ASSERT(connectionPool);
if (mDatabaseInfo.mClosing || mDatabaseInfo.TotalTransactionCount()) {
MOZ_ASSERT(!connectionPool->mDatabasesPerformingIdleMaintenance.Contains(
&mDatabaseInfo));
} else {
MOZ_ALWAYS_TRUE(
connectionPool->mDatabasesPerformingIdleMaintenance.RemoveElement(
&mDatabaseInfo));
connectionPool->NoteIdleDatabase(mDatabaseInfo);
}
return NS_OK;
}
NS_IMETHODIMP
ConnectionPool::CloseConnectionRunnable::Run() {
AUTO_PROFILER_LABEL("ConnectionPool::CloseConnectionRunnable::Run", DOM);
if (mOwningEventTarget) {
MOZ_ASSERT(mDatabaseInfo.mClosing);
const nsCOMPtr<nsIEventTarget> owningThread = std::move(mOwningEventTarget);
// The connection could be null if EnsureConnection() didn't run or was not
// successful in TransactionDatabaseOperationBase::RunOnConnectionThread().
if (mDatabaseInfo.mConnection) {
mDatabaseInfo.AssertIsOnConnectionThread();
mDatabaseInfo.mConnection->Close();
IDB_DEBUG_LOG(("ConnectionPool closed connection 0x%p",
mDatabaseInfo.mConnection.get()));
mDatabaseInfo.mConnection = nullptr;
#ifdef DEBUG
mDatabaseInfo.mDEBUGConnectionEventTarget = nullptr;
#endif
}
MOZ_ALWAYS_SUCCEEDS(owningThread->Dispatch(this, NS_DISPATCH_NORMAL));
return NS_OK;
}
RefPtr<ConnectionPool> connectionPool = mDatabaseInfo.mConnectionPool;
MOZ_ASSERT(connectionPool);
connectionPool->NoteClosedDatabase(mDatabaseInfo);
return NS_OK;
}
ConnectionPool::DatabaseInfo::DatabaseInfo(ConnectionPool* aConnectionPool,
const nsACString& aDatabaseId)
: mConnectionPool(aConnectionPool),
mDatabaseId(aDatabaseId),
mReadTransactionCount(0),
mWriteTransactionCount(0),
mNeedsCheckpoint(false),
mIdle(false),
mClosing(false)
#ifdef DEBUG
,
mDEBUGConnectionEventTarget(nullptr)
#endif
{
AssertIsOnBackgroundThread();
MOZ_ASSERT(aConnectionPool);
aConnectionPool->AssertIsOnOwningThread();
MOZ_ASSERT(!aDatabaseId.IsEmpty());
MOZ_COUNT_CTOR(ConnectionPool::DatabaseInfo);
}
ConnectionPool::DatabaseInfo::~DatabaseInfo() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mConnection);
MOZ_ASSERT(mScheduledWriteTransactions.IsEmpty());
MOZ_ASSERT(!mRunningWriteTransaction);
MOZ_ASSERT(!TotalTransactionCount());
MOZ_COUNT_DTOR(ConnectionPool::DatabaseInfo);
}
nsresult ConnectionPool::DatabaseInfo::Dispatch(
already_AddRefed<nsIRunnable> aRunnable) {
nsCOMPtr<nsIRunnable> runnable = aRunnable;
#ifdef DEBUG
if (kDEBUGTransactionThreadSleepMS) {
runnable = MakeRefPtr<TransactionRunnable>(std::move(runnable));
}
#endif
return mEventTarget->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL);
}
ConnectionPool::DatabaseCompleteCallback::DatabaseCompleteCallback(
const nsCString& aDatabaseId, nsIRunnable* aCallback)
: mDatabaseId(aDatabaseId), mCallback(aCallback) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mDatabaseId.IsEmpty());
MOZ_ASSERT(aCallback);
MOZ_COUNT_CTOR(ConnectionPool::DatabaseCompleteCallback);
}
ConnectionPool::DatabaseCompleteCallback::~DatabaseCompleteCallback() {
AssertIsOnBackgroundThread();
MOZ_COUNT_DTOR(ConnectionPool::DatabaseCompleteCallback);
}
ConnectionPool::FinishCallbackWrapper::FinishCallbackWrapper(
ConnectionPool* aConnectionPool, uint64_t aTransactionId,
FinishCallback* aCallback)
: Runnable("dom::indexedDB::ConnectionPool::FinishCallbackWrapper"),
mConnectionPool(aConnectionPool),
mCallback(aCallback),
mOwningEventTarget(GetCurrentSerialEventTarget()),
mTransactionId(aTransactionId),
mHasRunOnce(false) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aConnectionPool);
MOZ_ASSERT(aCallback);
MOZ_ASSERT(mOwningEventTarget);
}
ConnectionPool::FinishCallbackWrapper::~FinishCallbackWrapper() {
MOZ_ASSERT(!mConnectionPool);
MOZ_ASSERT(!mCallback);
}
nsresult ConnectionPool::FinishCallbackWrapper::Run() {
MOZ_ASSERT(mConnectionPool);
MOZ_ASSERT(mCallback);
MOZ_ASSERT(mOwningEventTarget);
AUTO_PROFILER_LABEL("ConnectionPool::FinishCallbackWrapper::Run", DOM);
if (!mHasRunOnce) {
MOZ_ASSERT(!IsOnBackgroundThread());
mHasRunOnce = true;
Unused << mCallback->Run();
MOZ_ALWAYS_SUCCEEDS(mOwningEventTarget->Dispatch(this, NS_DISPATCH_NORMAL));
return NS_OK;
}
mConnectionPool->AssertIsOnOwningThread();
MOZ_ASSERT(mHasRunOnce);
RefPtr<ConnectionPool> connectionPool = std::move(mConnectionPool);
connectionPool->FinishOp(mTransactionId);
RefPtr<FinishCallback> callback = std::move(mCallback);
callback->TransactionFinishedBeforeUnblock();
connectionPool->NoteFinishedTransaction(mTransactionId);
callback->TransactionFinishedAfterUnblock();
return NS_OK;
}
uint32_t ConnectionPool::sSerialNumber = 0u;
#ifdef DEBUG
ConnectionPool::TransactionRunnable::TransactionRunnable(
nsCOMPtr<nsIRunnable> aRunnable)
: Runnable("dom::indexedDB::ConnectionPool::TransactionRunnable"),
mRunnable(std::move(aRunnable)) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(kDEBUGTransactionThreadSleepMS);
}
nsresult ConnectionPool::TransactionRunnable::Run() {
MOZ_ASSERT(!IsOnBackgroundThread());
QM_TRY(MOZ_TO_RESULT(mRunnable->Run()));
MOZ_ALWAYS_TRUE(PR_Sleep(PR_MillisecondsToInterval(
kDEBUGTransactionThreadSleepMS)) == PR_SUCCESS);
return NS_OK;
}
#endif
ConnectionPool::IdleResource::IdleResource(const TimeStamp& aIdleTime)
: mIdleTime(aIdleTime) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!aIdleTime.IsNull());
MOZ_COUNT_CTOR(ConnectionPool::IdleResource);
}
ConnectionPool::IdleResource::~IdleResource() {
AssertIsOnBackgroundThread();
MOZ_COUNT_DTOR(ConnectionPool::IdleResource);
}
ConnectionPool::IdleDatabaseInfo::IdleDatabaseInfo(DatabaseInfo& aDatabaseInfo)
: IdleResource(
TimeStamp::NowLoRes() +
(aDatabaseInfo.mIdle
? TimeDuration::FromMilliseconds(kConnectionIdleMaintenanceMS)
: TimeDuration::FromMilliseconds(kConnectionIdleCloseMS))),
mDatabaseInfo(WrapNotNullUnchecked(&aDatabaseInfo)) {
AssertIsOnBackgroundThread();
MOZ_COUNT_CTOR(ConnectionPool::IdleDatabaseInfo);
}
ConnectionPool::IdleDatabaseInfo::~IdleDatabaseInfo() {
AssertIsOnBackgroundThread();
MOZ_COUNT_DTOR(ConnectionPool::IdleDatabaseInfo);
}
ConnectionPool::PerformingIdleMaintenanceDatabaseInfo::
PerformingIdleMaintenanceDatabaseInfo(
DatabaseInfo& aDatabaseInfo,
RefPtr<IdleConnectionRunnable> aIdleConnectionRunnable)
: mDatabaseInfo(WrapNotNullUnchecked(&aDatabaseInfo)),
mIdleConnectionRunnable(std::move(aIdleConnectionRunnable)) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mIdleConnectionRunnable);
MOZ_COUNT_CTOR(ConnectionPool::PerformingIdleMaintenanceDatabaseInfo);
}
ConnectionPool::PerformingIdleMaintenanceDatabaseInfo::
~PerformingIdleMaintenanceDatabaseInfo() {
AssertIsOnBackgroundThread();
MOZ_COUNT_DTOR(ConnectionPool::PerformingIdleMaintenanceDatabaseInfo);
}
ConnectionPool::TransactionInfo::TransactionInfo(
DatabaseInfo& aDatabaseInfo, const nsID& aBackgroundChildLoggingId,
const nsACString& aDatabaseId, uint64_t aTransactionId,
int64_t aLoggingSerialNumber, const nsTArray<nsString>& aObjectStoreNames,
bool aIsWriteTransaction, TransactionDatabaseOperationBase* aTransactionOp)
: mDatabaseInfo(aDatabaseInfo),
mBackgroundChildLoggingId(aBackgroundChildLoggingId),
mDatabaseId(aDatabaseId),
mTransactionId(aTransactionId),
mLoggingSerialNumber(aLoggingSerialNumber),
mObjectStoreNames(aObjectStoreNames.Clone()),
mIsWriteTransaction(aIsWriteTransaction),
mRunning(false),
mRunningOp(false) {
AssertIsOnBackgroundThread();
aDatabaseInfo.mConnectionPool->AssertIsOnOwningThread();
MOZ_COUNT_CTOR(ConnectionPool::TransactionInfo);
if (aTransactionOp) {
mQueuedOps.Push(aTransactionOp);
}
}
ConnectionPool::TransactionInfo::~TransactionInfo() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mBlockedOn.Count());
MOZ_ASSERT(mQueuedOps.IsEmpty());
MOZ_ASSERT(!mRunning);
MOZ_ASSERT(!mRunningOp);
MOZ_ASSERT(mFinished);
MOZ_COUNT_DTOR(ConnectionPool::TransactionInfo);
}
void ConnectionPool::TransactionInfo::AddBlockingTransaction(
TransactionInfo& aTransactionInfo) {
AssertIsOnBackgroundThread();
// XXX Does it really make sense to have both mBlocking and mBlockingOrdered,
// just to reduce the algorithmic complexity of this Contains check? This was
// mentioned in the context of Bug 1290853, but no real justification was
// given. There was the suggestion of encapsulating this in an
// insertion-ordered hashtable implementation, which seems like a good idea.
// If we had that, this would be the appropriate data structure to use here.
if (mBlocking.EnsureInserted(&aTransactionInfo)) {
mBlockingOrdered.AppendElement(WrapNotNullUnchecked(&aTransactionInfo));
}
}
void ConnectionPool::TransactionInfo::RemoveBlockingTransactions() {
AssertIsOnBackgroundThread();
for (const auto blockedInfo : mBlockingOrdered) {
blockedInfo->MaybeUnblock(*this);
}
mBlocking.Clear();
mBlockingOrdered.Clear();
}
void ConnectionPool::TransactionInfo::SetRunning() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mRunning);
AUTO_PROFILER_LABEL("ConnectionPool::FinishOp", DOM);
mRunning = true;
if (!mQueuedOps.IsEmpty()) {
mRunningOp = true;
nsCOMPtr<nsIRunnable> runnable = mQueuedOps.Pop();
MOZ_ALWAYS_SUCCEEDS(mDatabaseInfo.Dispatch(runnable.forget()));
}
}
void ConnectionPool::TransactionInfo::StartOp(nsCOMPtr<nsIRunnable> aRunnable) {
AssertIsOnBackgroundThread();
if (mRunning) {
MOZ_ASSERT(mDatabaseInfo.mEventTarget);
MOZ_ASSERT(!mDatabaseInfo.mClosing);
MOZ_ASSERT_IF(mIsWriteTransaction,
mDatabaseInfo.mRunningWriteTransaction &&
mDatabaseInfo.mRunningWriteTransaction.refEquals(*this));
if (!mRunningOp) {
mRunningOp = true;
MOZ_ALWAYS_SUCCEEDS(mDatabaseInfo.Dispatch(aRunnable.forget()));
} else {
mQueuedOps.Push(std::move(aRunnable));
}
} else {
mQueuedOps.Push(std::move(aRunnable));
}
}
void ConnectionPool::TransactionInfo::FinishOp() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mRunning);
MOZ_ASSERT(mRunningOp);
if (mQueuedOps.IsEmpty()) {
mRunningOp = false;
} else {
nsCOMPtr<nsIRunnable> runnable = mQueuedOps.Pop();
MOZ_ALWAYS_SUCCEEDS(mDatabaseInfo.Dispatch(runnable.forget()));
}
}
void ConnectionPool::TransactionInfo::MaybeUnblock(
TransactionInfo& aTransactionInfo) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mBlockedOn.Contains(&aTransactionInfo));
mBlockedOn.Remove(&aTransactionInfo);
if (mBlockedOn.IsEmpty()) {
ConnectionPool* connectionPool = mDatabaseInfo.mConnectionPool;
MOZ_ASSERT(connectionPool);
connectionPool->AssertIsOnOwningThread();
Unused << connectionPool->ScheduleTransaction(
*this,
/* aFromQueuedTransactions */ false);
}
}
#if defined(DEBUG) || defined(NS_BUILD_REFCNT_LOGGING)
ConnectionPool::TransactionInfoPair::TransactionInfoPair() {
AssertIsOnBackgroundThread();
MOZ_COUNT_CTOR(ConnectionPool::TransactionInfoPair);
}
ConnectionPool::TransactionInfoPair::~TransactionInfoPair() {
AssertIsOnBackgroundThread();
MOZ_COUNT_DTOR(ConnectionPool::TransactionInfoPair);
}
#endif
/*******************************************************************************
* Metadata classes
******************************************************************************/
bool FullObjectStoreMetadata::HasLiveIndexes() const {
AssertIsOnBackgroundThread();
return std::any_of(mIndexes.Values().cbegin(), mIndexes.Values().cend(),
[](const auto& entry) { return !entry->mDeleted; });
}
SafeRefPtr<FullDatabaseMetadata> FullDatabaseMetadata::Duplicate() const {
AssertIsOnBackgroundThread();
// FullDatabaseMetadata contains two hash tables of pointers that we need to
// duplicate so we can't just use the copy constructor.
auto newMetadata = MakeSafeRefPtr<FullDatabaseMetadata>(mCommonMetadata);
newMetadata->mDatabaseId = mDatabaseId;
newMetadata->mFilePath = mFilePath;
newMetadata->mNextObjectStoreId = mNextObjectStoreId;
newMetadata->mNextIndexId = mNextIndexId;
for (const auto& objectStoreEntry : mObjectStores) {
const auto& objectStoreValue = objectStoreEntry.GetData();
auto newOSMetadata = MakeSafeRefPtr<FullObjectStoreMetadata>(
objectStoreValue->mCommonMetadata, [&objectStoreValue] {
const auto&& srcLocked = objectStoreValue->mAutoIncrementIds.Lock();
return *srcLocked;
}());
for (const auto& indexEntry : objectStoreValue->mIndexes) {
const auto& value = indexEntry.GetData();
auto newIndexMetadata = MakeSafeRefPtr<FullIndexMetadata>();
newIndexMetadata->mCommonMetadata = value->mCommonMetadata;
if (NS_WARN_IF(!newOSMetadata->mIndexes.InsertOrUpdate(
indexEntry.GetKey(), std::move(newIndexMetadata), fallible))) {
return nullptr;
}
}
MOZ_ASSERT(objectStoreValue->mIndexes.Count() ==
newOSMetadata->mIndexes.Count());
if (NS_WARN_IF(!newMetadata->mObjectStores.InsertOrUpdate(
objectStoreEntry.GetKey(), std::move(newOSMetadata), fallible))) {
return nullptr;
}
}
MOZ_ASSERT(mObjectStores.Count() == newMetadata->mObjectStores.Count());
return newMetadata;
}
DatabaseLoggingInfo::~DatabaseLoggingInfo() {
AssertIsOnBackgroundThread();
if (gLoggingInfoHashtable) {
const nsID& backgroundChildLoggingId =
mLoggingInfo.backgroundChildLoggingId();
MOZ_ASSERT(gLoggingInfoHashtable->Get(backgroundChildLoggingId) == this);
gLoggingInfoHashtable->Remove(backgroundChildLoggingId);
}
}
/*******************************************************************************
* Factory
******************************************************************************/
Factory::Factory(RefPtr<DatabaseLoggingInfo> aLoggingInfo,
const nsACString& aSystemLocale)
: mSystemLocale(aSystemLocale),
mLoggingInfo(std::move(aLoggingInfo))
#ifdef DEBUG
,
mActorDestroyed(false)
#endif
{
AssertIsOnBackgroundThread();
MOZ_ASSERT(!QuotaClient::IsShuttingDownOnBackgroundThread());
}
Factory::~Factory() { MOZ_ASSERT(mActorDestroyed); }
// static
SafeRefPtr<Factory> Factory::Create(const LoggingInfo& aLoggingInfo,
const nsACString& aSystemLocale) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!QuotaClient::IsShuttingDownOnBackgroundThread());
// Balanced in ActoryDestroy().
IncreaseBusyCount();
MOZ_ASSERT(gLoggingInfoHashtable);
RefPtr<DatabaseLoggingInfo> loggingInfo =
gLoggingInfoHashtable->WithEntryHandle(
aLoggingInfo.backgroundChildLoggingId(), [&](auto&& entry) {
if (entry) {
[[maybe_unused]] const auto& loggingInfo = entry.Data();
MOZ_ASSERT(aLoggingInfo.backgroundChildLoggingId() ==
loggingInfo->Id());
#if !FUZZING
NS_WARNING_ASSERTION(
aLoggingInfo.nextTransactionSerialNumber() ==
loggingInfo->mLoggingInfo.nextTransactionSerialNumber(),
"NextTransactionSerialNumber doesn't match!");
NS_WARNING_ASSERTION(
aLoggingInfo.nextVersionChangeTransactionSerialNumber() ==
loggingInfo->mLoggingInfo
.nextVersionChangeTransactionSerialNumber(),
"NextVersionChangeTransactionSerialNumber doesn't match!");
NS_WARNING_ASSERTION(
aLoggingInfo.nextRequestSerialNumber() ==
loggingInfo->mLoggingInfo.nextRequestSerialNumber(),
"NextRequestSerialNumber doesn't match!");
#endif // !FUZZING
} else {
entry.Insert(new DatabaseLoggingInfo(aLoggingInfo));
}
return do_AddRef(entry.Data());
});
return MakeSafeRefPtr<Factory>(std::move(loggingInfo), aSystemLocale);
}
void Factory::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mActorDestroyed);
#ifdef DEBUG
mActorDestroyed = true;
#endif
// Match the IncreaseBusyCount in Create().
DecreaseBusyCount();
}
mozilla::ipc::IPCResult Factory::RecvDeleteMe() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mActorDestroyed);
QM_WARNONLY_TRY(OkIf(PBackgroundIDBFactoryParent::Send__delete__(this)));
return IPC_OK();
}
PBackgroundIDBFactoryRequestParent*
Factory::AllocPBackgroundIDBFactoryRequestParent(
const FactoryRequestParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() != FactoryRequestParams::T__None);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread())) {
return nullptr;
}
const CommonFactoryRequestParams* commonParams;
switch (aParams.type()) {
case FactoryRequestParams::TOpenDatabaseRequestParams: {
const OpenDatabaseRequestParams& params =
aParams.get_OpenDatabaseRequestParams();
commonParams = ¶ms.commonParams();
break;
}
case FactoryRequestParams::TDeleteDatabaseRequestParams: {
const DeleteDatabaseRequestParams& params =
aParams.get_DeleteDatabaseRequestParams();
commonParams = ¶ms.commonParams();
break;
}
default:
MOZ_CRASH("Should never get here!");
}
MOZ_ASSERT(commonParams);
const DatabaseMetadata& metadata = commonParams->metadata();
if (NS_AUUF_OR_WARN_IF(!IsValidPersistenceType(metadata.persistenceType()))) {
return nullptr;
}
const PrincipalInfo& principalInfo = commonParams->principalInfo();
if (NS_AUUF_OR_WARN_IF(!quota::IsPrincipalInfoValid(principalInfo))) {
IPC_FAIL(this, "Invalid principal!");
return nullptr;
}
MOZ_ASSERT(principalInfo.type() == PrincipalInfo::TSystemPrincipalInfo ||
principalInfo.type() == PrincipalInfo::TContentPrincipalInfo);
if (NS_AUUF_OR_WARN_IF(
principalInfo.type() == PrincipalInfo::TSystemPrincipalInfo &&
metadata.persistenceType() != PERSISTENCE_TYPE_PERSISTENT)) {
return nullptr;
}
if (NS_AUUF_OR_WARN_IF(
principalInfo.type() == PrincipalInfo::TContentPrincipalInfo &&
QuotaManager::IsOriginInternal(
principalInfo.get_ContentPrincipalInfo().originNoSuffix()) &&
metadata.persistenceType() != PERSISTENCE_TYPE_PERSISTENT)) {
return nullptr;
}
Maybe<ContentParentId> contentParentId = GetContentParentId();
auto actor = [&]() -> RefPtr<FactoryRequestOp> {
if (aParams.type() == FactoryRequestParams::TOpenDatabaseRequestParams) {
return MakeRefPtr<OpenDatabaseOp>(SafeRefPtrFromThis(), contentParentId,
*commonParams);
} else {
return MakeRefPtr<DeleteDatabaseOp>(SafeRefPtrFromThis(), contentParentId,
*commonParams);
}
}();
gFactoryOps->insertBack(actor);
// Balanced in CleanupMetadata() which is/must always called by SendResults().
IncreaseBusyCount();
// Transfer ownership to IPDL.
return actor.forget().take();
}
mozilla::ipc::IPCResult Factory::RecvPBackgroundIDBFactoryRequestConstructor(
PBackgroundIDBFactoryRequestParent* aActor,
const FactoryRequestParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
MOZ_ASSERT(aParams.type() != FactoryRequestParams::T__None);
MOZ_ASSERT(!QuotaClient::IsShuttingDownOnBackgroundThread());
auto* op = static_cast<FactoryRequestOp*>(aActor);
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(op));
return IPC_OK();
}
bool Factory::DeallocPBackgroundIDBFactoryRequestParent(
PBackgroundIDBFactoryRequestParent* aActor) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
// Transfer ownership back from IPDL.
RefPtr<FactoryRequestOp> op =
dont_AddRef(static_cast<FactoryRequestOp*>(aActor));
return true;
}
mozilla::ipc::IPCResult Factory::RecvGetDatabases(
const PersistenceType& aPersistenceType,
const PrincipalInfo& aPrincipalInfo, GetDatabasesResolver&& aResolve) {
AssertIsOnBackgroundThread();
auto ResolveGetDatabasesAndReturn = [&aResolve](const nsresult rv) {
aResolve(rv);
return IPC_OK();
};
QM_TRY(MOZ_TO_RESULT(!QuotaClient::IsShuttingDownOnBackgroundThread()),
ResolveGetDatabasesAndReturn);
QM_TRY(MOZ_TO_RESULT(IsValidPersistenceType(aPersistenceType)),
QM_IPC_FAIL(this));
QM_TRY(MOZ_TO_RESULT(quota::IsPrincipalInfoValid(aPrincipalInfo)),
QM_IPC_FAIL(this));
MOZ_ASSERT(aPrincipalInfo.type() == PrincipalInfo::TSystemPrincipalInfo ||
aPrincipalInfo.type() == PrincipalInfo::TContentPrincipalInfo);
PersistenceType persistenceType =
IDBFactory::GetPersistenceType(aPrincipalInfo);
QM_TRY(MOZ_TO_RESULT(aPersistenceType == persistenceType), QM_IPC_FAIL(this));
Maybe<ContentParentId> contentParentId = GetContentParentId();
auto op = MakeRefPtr<GetDatabasesOp>(SafeRefPtrFromThis(), contentParentId,
aPersistenceType, aPrincipalInfo,
std::move(aResolve));
gFactoryOps->insertBack(op);
// Balanced in CleanupMetadata() which is/must always called by SendResults().
IncreaseBusyCount();
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(op));
return IPC_OK();
}
Maybe<ContentParentId> Factory::GetContentParentId() const {
uint64_t childID = BackgroundParent::GetChildID(Manager());
if (childID) {
// If childID is not zero we are dealing with an other-process actor. We
// want to initialize OpenDatabaseOp/DeleteDatabaseOp here with the ID
// (and later also Database) in that case, so Database::IsOwnedByProcess
// can find Databases belonging to a particular content process when
// QuotaClient::AbortOperationsForProcess is called which is currently used
// to abort operations for content processes only.
return Some(ContentParentId(childID));
}
return Nothing();
}
/*******************************************************************************
* WaitForTransactionsHelper
******************************************************************************/
void WaitForTransactionsHelper::WaitForTransactions() {
MOZ_ASSERT(mState == State::Initial);
Unused << this->Run();
}
void WaitForTransactionsHelper::MaybeWaitForTransactions() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::Initial);
RefPtr<ConnectionPool> connectionPool = gConnectionPool.get();
if (connectionPool) {
mState = State::WaitingForTransactions;
connectionPool->WaitForDatabaseToComplete(mDatabaseId, this);
return;
}
CallCallback();
}
void WaitForTransactionsHelper::CallCallback() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::Initial ||
mState == State::WaitingForTransactions);
const nsCOMPtr<nsIRunnable> callback = std::move(mCallback);
callback->Run();
mState = State::Complete;
}
NS_IMETHODIMP
WaitForTransactionsHelper::Run() {
MOZ_ASSERT(mState != State::Complete);
MOZ_ASSERT(mCallback);
switch (mState) {
case State::Initial:
MaybeWaitForTransactions();
break;
case State::WaitingForTransactions:
CallCallback();
break;
default:
MOZ_CRASH("Should never get here!");
}
return NS_OK;
}
/*******************************************************************************
* Database
******************************************************************************/
Database::Database(SafeRefPtr<Factory> aFactory,
const PrincipalInfo& aPrincipalInfo,
const Maybe<ContentParentId>& aOptionalContentParentId,
const quota::OriginMetadata& aOriginMetadata,
uint32_t aTelemetryId,
SafeRefPtr<FullDatabaseMetadata> aMetadata,
SafeRefPtr<DatabaseFileManager> aFileManager,
ClientDirectoryLockHandle aDirectoryLockHandle,
bool aInPrivateBrowsing,
const Maybe<const CipherKey>& aMaybeKey)
: mFactory(std::move(aFactory)),
mMetadata(std::move(aMetadata)),
mFileManager(std::move(aFileManager)),
mDirectoryLockHandle(std::move(aDirectoryLockHandle)),
mPrincipalInfo(aPrincipalInfo),
mOptionalContentParentId(aOptionalContentParentId),
mOriginMetadata(aOriginMetadata),
mId(mMetadata->mDatabaseId),
mFilePath(mMetadata->mFilePath),
mKey(aMaybeKey),
mTelemetryId(aTelemetryId),
mPersistenceType(mMetadata->mCommonMetadata.persistenceType()),
mInPrivateBrowsing(aInPrivateBrowsing),
mBackgroundThread(GetCurrentSerialEventTarget())
#ifdef DEBUG
,
mAllBlobsUnmapped(false)
#endif
{
AssertIsOnBackgroundThread();
MOZ_ASSERT(mFactory);
MOZ_ASSERT(mMetadata);
MOZ_ASSERT(mFileManager);
MOZ_ASSERT(mDirectoryLockHandle);
MOZ_ASSERT(mDirectoryLockHandle->Id() >= 0);
mDirectoryLockId = mDirectoryLockHandle->Id();
}
template <typename T>
bool Database::InvalidateAll(const nsTBaseHashSet<nsPtrHashKey<T>>& aTable) {
AssertIsOnBackgroundThread();
const uint32_t count = aTable.Count();
if (!count) {
return true;
}
// XXX Does this really need to be fallible?
QM_TRY_INSPECT(const auto& elementsToInvalidate,
TransformIntoNewArray(
aTable, [](const auto& entry) { return entry; }, fallible),
false);
IDB_REPORT_INTERNAL_ERR();
for (const auto& elementToInvalidate : elementsToInvalidate) {
MOZ_ASSERT(elementToInvalidate);
elementToInvalidate->Invalidate();
}
return true;
}
void Database::Invalidate() {
AssertIsOnBackgroundThread();
if (mInvalidated) {
return;
}
mInvalidated.Flip();
if (mActorWasAlive && !mActorDestroyed) {
Unused << SendInvalidate();
}
QM_WARNONLY_TRY(OkIf(InvalidateAll(mTransactions)));
MOZ_ALWAYS_TRUE(CloseInternal());
}
nsresult Database::EnsureConnection() {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
AUTO_PROFILER_LABEL("Database::EnsureConnection", DOM);
if (!mConnection || !mConnection->HasStorageConnection()) {
QM_TRY_UNWRAP(mConnection, gConnectionPool->GetOrCreateConnection(*this));
}
AssertIsOnConnectionThread();
return NS_OK;
}
bool Database::RegisterTransaction(TransactionBase& aTransaction) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mTransactions.Contains(&aTransaction));
MOZ_ASSERT(mDirectoryLockHandle);
MOZ_ASSERT(!mInvalidated);
MOZ_ASSERT(!mClosed);
if (NS_WARN_IF(!mTransactions.Insert(&aTransaction, fallible))) {
return false;
}
return true;
}
void Database::UnregisterTransaction(TransactionBase& aTransaction) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mTransactions.Contains(&aTransaction));
mTransactions.Remove(&aTransaction);
MaybeCloseConnection();
}
void Database::SetActorAlive() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mActorDestroyed);
mActorWasAlive.Flip();
}
void Database::MapBlob(const IPCBlob& aIPCBlob,
SafeRefPtr<DatabaseFileInfo> aFileInfo) {
AssertIsOnBackgroundThread();
const RemoteLazyStream& stream = aIPCBlob.inputStream();
MOZ_ASSERT(stream.type() == RemoteLazyStream::TRemoteLazyInputStream);
nsID id{};
MOZ_ALWAYS_SUCCEEDS(
stream.get_RemoteLazyInputStream()->GetInternalStreamID(id));
MOZ_ASSERT(!mMappedBlobs.Contains(id));
mMappedBlobs.InsertOrUpdate(id, std::move(aFileInfo));
RefPtr<UnmapBlobCallback> callback =
new UnmapBlobCallback(SafeRefPtrFromThis());
auto storage = RemoteLazyInputStreamStorage::Get();
MOZ_ASSERT(storage.isOk());
storage.inspect()->StoreCallback(id, callback);
}
void Database::Stringify(nsACString& aResult) const {
AssertIsOnBackgroundThread();
constexpr auto kQuotaGenericDelimiterString = "|"_ns;
aResult.Append(
"DirectoryLock:"_ns + IntToCString(!!mDirectoryLockHandle) +
kQuotaGenericDelimiterString +
//
"Transactions:"_ns + IntToCString(mTransactions.Count()) +
kQuotaGenericDelimiterString +
//
"OtherProcessActor:"_ns +
IntToCString(
BackgroundParent::IsOtherProcessActor(GetBackgroundParent())) +
kQuotaGenericDelimiterString +
//
"Origin:"_ns + AnonymizedOriginString(mOriginMetadata.mOrigin) +
kQuotaGenericDelimiterString +
//
"PersistenceType:"_ns + PersistenceTypeToString(mPersistenceType) +
kQuotaGenericDelimiterString +
//
"Closed:"_ns + IntToCString(static_cast<bool>(mClosed)) +
kQuotaGenericDelimiterString +
//
"Invalidated:"_ns + IntToCString(static_cast<bool>(mInvalidated)) +
kQuotaGenericDelimiterString +
//
"ActorWasAlive:"_ns + IntToCString(static_cast<bool>(mActorWasAlive)) +
kQuotaGenericDelimiterString +
//
"ActorDestroyed:"_ns + IntToCString(static_cast<bool>(mActorDestroyed)));
}
SafeRefPtr<DatabaseFileInfo> Database::GetBlob(const IPCBlob& aIPCBlob) {
AssertIsOnBackgroundThread();
RefPtr<RemoteLazyInputStream> lazyStream;
switch (aIPCBlob.inputStream().type()) {
case RemoteLazyStream::TIPCStream: {
const InputStreamParams& inputStreamParams =
aIPCBlob.inputStream().get_IPCStream().stream();
if (inputStreamParams.type() !=
InputStreamParams::TRemoteLazyInputStreamParams) {
return nullptr;
}
lazyStream = inputStreamParams.get_RemoteLazyInputStreamParams().stream();
break;
}
case RemoteLazyStream::TRemoteLazyInputStream:
lazyStream = aIPCBlob.inputStream().get_RemoteLazyInputStream();
break;
default:
MOZ_ASSERT_UNREACHABLE("Unknown RemoteLazyStream type");
return nullptr;
}
if (!lazyStream) {
MOZ_ASSERT_UNREACHABLE("Unexpected null stream");
return nullptr;
}
nsID id{};
nsresult rv = lazyStream->GetInternalStreamID(id);
if (NS_FAILED(rv)) {
MOZ_ASSERT_UNREACHABLE(
"Received RemoteLazyInputStream doesn't have an actor connection");
return nullptr;
}
const auto fileInfo = mMappedBlobs.Lookup(id);
return fileInfo ? fileInfo->clonePtr() : nullptr;
}
void Database::UnmapBlob(const nsID& aID) {
AssertIsOnBackgroundThread();
MOZ_ASSERT_IF(!mAllBlobsUnmapped, mMappedBlobs.Contains(aID));
mMappedBlobs.Remove(aID);
}
void Database::UnmapAllBlobs() {
AssertIsOnBackgroundThread();
#ifdef DEBUG
mAllBlobsUnmapped = true;
#endif
mMappedBlobs.Clear();
}
bool Database::CloseInternal() {
AssertIsOnBackgroundThread();
if (mClosed) {
if (NS_WARN_IF(!IsInvalidated())) {
// Signal misbehaving child for sending the close message twice.
return false;
}
// Ignore harmless race when we just invalidated the database.
return true;
}
mClosed.Flip();
if (gConnectionPool) {
gConnectionPool->CloseDatabaseWhenIdle(Id());
}
DatabaseActorInfo* info;
MOZ_ALWAYS_TRUE(gLiveDatabaseHashtable->Get(Id(), &info));
MOZ_ASSERT(info->mLiveDatabases.contains(this));
if (info->mWaitingFactoryOp) {
info->mWaitingFactoryOp->NoteDatabaseClosed(this);
}
MaybeCloseConnection();
return true;
}
void Database::MaybeCloseConnection() {
AssertIsOnBackgroundThread();
if (!mTransactions.Count() && IsClosed() && mDirectoryLockHandle) {
nsCOMPtr<nsIRunnable> callback =
NewRunnableMethod("dom::indexedDB::Database::ConnectionClosedCallback",
this, &Database::ConnectionClosedCallback);
RefPtr<WaitForTransactionsHelper> helper =
new WaitForTransactionsHelper(Id(), callback);
helper->WaitForTransactions();
}
}
void Database::ConnectionClosedCallback() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mClosed);
MOZ_ASSERT(!mTransactions.Count());
{
auto destroyingDirectoryLockHandle = std::move(mDirectoryLockHandle);
}
CleanupMetadata();
UnmapAllBlobs();
if (IsInvalidated() && IsActorAlive()) {
// Step 3 and 4 of "5.2 Closing a Database":
// 1. Wait for all transactions to complete.
// 2. Fire a close event if forced flag is set, i.e., IsInvalidated() in our
// implementation.
Unused << SendCloseAfterInvalidationComplete();
}
}
void Database::CleanupMetadata() {
AssertIsOnBackgroundThread();
DatabaseActorInfo* info;
MOZ_ALWAYS_TRUE(gLiveDatabaseHashtable->Get(Id(), &info));
removeFrom(info->mLiveDatabases);
QuotaManager::MaybeRecordQuotaClientShutdownStep(
quota::Client::IDB, "Live database entry removed"_ns);
if (info->mLiveDatabases.isEmpty()) {
MOZ_ASSERT(!info->mWaitingFactoryOp ||
!info->mWaitingFactoryOp->HasBlockedDatabases());
gLiveDatabaseHashtable->Remove(Id());
QuotaManager::MaybeRecordQuotaClientShutdownStep(
quota::Client::IDB, "gLiveDatabaseHashtable entry removed"_ns);
}
// Match the IncreaseBusyCount in OpenDatabaseOp::EnsureDatabaseActor().
DecreaseBusyCount();
}
void Database::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnBackgroundThread();
mActorDestroyed.Flip();
if (!IsInvalidated()) {
Invalidate();
}
}
PBackgroundIDBDatabaseFileParent*
Database::AllocPBackgroundIDBDatabaseFileParent(const IPCBlob& aIPCBlob) {
AssertIsOnBackgroundThread();
SafeRefPtr<DatabaseFileInfo> fileInfo = GetBlob(aIPCBlob);
RefPtr<DatabaseFile> actor;
if (fileInfo) {
actor = new DatabaseFile(std::move(fileInfo));
} else {
// This is a blob we haven't seen before.
fileInfo = mFileManager->CreateFileInfo();
if (NS_WARN_IF(!fileInfo)) {
return nullptr;
}
actor = new DatabaseFile(IPCBlobUtils::Deserialize(aIPCBlob),
std::move(fileInfo));
}
MOZ_ASSERT(actor);
return actor.forget().take();
}
bool Database::DeallocPBackgroundIDBDatabaseFileParent(
PBackgroundIDBDatabaseFileParent* aActor) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
RefPtr<DatabaseFile> actor = dont_AddRef(static_cast<DatabaseFile*>(aActor));
return true;
}
already_AddRefed<PBackgroundIDBTransactionParent>
Database::AllocPBackgroundIDBTransactionParent(
const nsTArray<nsString>& aObjectStoreNames, const Mode& aMode,
const Durability& aDurability) {
AssertIsOnBackgroundThread();
// Once a database is closed it must not try to open new transactions.
if (NS_WARN_IF(mClosed)) {
MOZ_ASSERT_UNLESS_FUZZING(mInvalidated);
return nullptr;
}
if (NS_AUUF_OR_WARN_IF(aObjectStoreNames.IsEmpty())) {
return nullptr;
}
if (NS_AUUF_OR_WARN_IF(aMode != IDBTransaction::Mode::ReadOnly &&
aMode != IDBTransaction::Mode::ReadWrite &&
aMode != IDBTransaction::Mode::ReadWriteFlush &&
aMode != IDBTransaction::Mode::Cleanup)) {
return nullptr;
}
if (NS_AUUF_OR_WARN_IF(aDurability != IDBTransaction::Durability::Default &&
aDurability != IDBTransaction::Durability::Strict &&
aDurability != IDBTransaction::Durability::Relaxed)) {
return nullptr;
}
const ObjectStoreTable& objectStores = mMetadata->mObjectStores;
const uint32_t nameCount = aObjectStoreNames.Length();
if (NS_AUUF_OR_WARN_IF(nameCount > objectStores.Count())) {
return nullptr;
}
QM_TRY_UNWRAP(
auto objectStoreMetadatas,
TransformIntoNewArrayAbortOnErr(
aObjectStoreNames,
[lastName = Maybe<const nsString&>{},
&objectStores](const nsString& name) mutable
-> mozilla::Result<SafeRefPtr<FullObjectStoreMetadata>,
nsresult> {
if (lastName) {
// Make sure that this name is sorted properly and not a
// duplicate.
if (NS_AUUF_OR_WARN_IF(name <= lastName.ref())) {
return Err(NS_ERROR_FAILURE);
}
}
lastName = SomeRef(name);
const auto foundIt =
std::find_if(objectStores.cbegin(), objectStores.cend(),
[&name](const auto& entry) {
const auto& value = entry.GetData();
MOZ_ASSERT(entry.GetKey());
return name == value->mCommonMetadata.name() &&
!value->mDeleted;
});
if (foundIt == objectStores.cend()) {
MOZ_ASSERT_UNLESS_FUZZING(false, "ObjectStore not found.");
return Err(NS_ERROR_FAILURE);
}
return foundIt->GetData().clonePtr();
},
fallible),
nullptr);
return MakeSafeRefPtr<NormalTransaction>(SafeRefPtrFromThis(), aMode,
aDurability,
std::move(objectStoreMetadatas))
.forget();
}
mozilla::ipc::IPCResult Database::RecvPBackgroundIDBTransactionConstructor(
PBackgroundIDBTransactionParent* aActor,
nsTArray<nsString>&& aObjectStoreNames, const Mode& aMode,
const Durability& aDurability) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
MOZ_ASSERT(!aObjectStoreNames.IsEmpty());
MOZ_ASSERT(aMode == IDBTransaction::Mode::ReadOnly ||
aMode == IDBTransaction::Mode::ReadWrite ||
aMode == IDBTransaction::Mode::ReadWriteFlush ||
aMode == IDBTransaction::Mode::Cleanup);
MOZ_ASSERT(aDurability == IDBTransaction::Durability::Default ||
aDurability == IDBTransaction::Durability::Strict ||
aDurability == IDBTransaction::Durability::Relaxed);
MOZ_ASSERT(!mClosed);
if (IsInvalidated()) {
// This is an expected race. We don't want the child to die here, just don't
// actually do any work.
return IPC_OK();
}
if (!gConnectionPool) {
gConnectionPool = new ConnectionPool();
}
auto* transaction = static_cast<NormalTransaction*>(aActor);
RefPtr<StartTransactionOp> startOp = new StartTransactionOp(
SafeRefPtr{transaction, AcquireStrongRefFromRawPtr{}});
uint64_t transactionId = startOp->StartOnConnectionPool(
GetLoggingInfo()->Id(), mMetadata->mDatabaseId,
transaction->LoggingSerialNumber(), aObjectStoreNames,
aMode != IDBTransaction::Mode::ReadOnly);
transaction->Init(transactionId);
if (NS_WARN_IF(!RegisterTransaction(*transaction))) {
IDB_REPORT_INTERNAL_ERR();
transaction->Abort(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR, /* aForce */ false);
return IPC_OK();
}
return IPC_OK();
}
mozilla::ipc::IPCResult Database::RecvDeleteMe() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mActorDestroyed);
QM_WARNONLY_TRY(OkIf(PBackgroundIDBDatabaseParent::Send__delete__(this)));
return IPC_OK();
}
mozilla::ipc::IPCResult Database::RecvBlocked() {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(mClosed)) {
// Even though the sender checks the DB for not being closed, too,
// there is a potential race with an ongoing origin clearing which
// might have invalidated the DB in the meantime. Just ignore.
return IPC_OK();
}
DatabaseActorInfo* info;
MOZ_ALWAYS_TRUE(gLiveDatabaseHashtable->Get(Id(), &info));
MOZ_ASSERT(info->mLiveDatabases.contains(this));
if (NS_WARN_IF(!info->mWaitingFactoryOp)) {
return IPC_FAIL(this, "Database info has no mWaitingFactoryOp!");
}
info->mWaitingFactoryOp->NoteDatabaseBlocked(this);
return IPC_OK();
}
mozilla::ipc::IPCResult Database::RecvClose() {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(!CloseInternal())) {
return IPC_FAIL(this, "CloseInternal failed!");
}
return IPC_OK();
}
void Database::StartTransactionOp::RunOnConnectionThread() {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(!HasFailed());
IDB_LOG_MARK_PARENT_TRANSACTION("Beginning database work", "DB Start",
IDB_LOG_ID_STRING(mBackgroundChildLoggingId),
mTransactionLoggingSerialNumber);
TransactionDatabaseOperationBase::RunOnConnectionThread();
}
nsresult Database::StartTransactionOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
Transaction().SetActiveOnConnectionThread();
if (Transaction().GetMode() == IDBTransaction::Mode::Cleanup) {
DebugOnly<nsresult> rv = aConnection->DisableQuotaChecks();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"DisableQuotaChecks failed, trying to continue "
"cleanup transaction with quota checks enabled");
}
if (Transaction().GetMode() != IDBTransaction::Mode::ReadOnly) {
QM_TRY(MOZ_TO_RESULT(
aConnection->BeginWriteTransaction(Transaction().GetDurability())));
}
return NS_OK;
}
nsresult Database::StartTransactionOp::SendSuccessResult() {
// We don't need to do anything here.
return NS_OK;
}
bool Database::StartTransactionOp::SendFailureResult(
nsresult /* aResultCode */) {
IDB_REPORT_INTERNAL_ERR();
// Abort the transaction.
return false;
}
void Database::StartTransactionOp::Cleanup() {
#ifdef DEBUG
// StartTransactionOp is not a normal database operation that is tied to an
// actor. Do this to make our assertions happy.
NoteActorDestroyed();
#endif
TransactionDatabaseOperationBase::Cleanup();
}
/*******************************************************************************
* TransactionBase
******************************************************************************/
TransactionBase::TransactionBase(SafeRefPtr<Database> aDatabase, Mode aMode,
Durability aDurability)
: mDatabase(std::move(aDatabase)),
mDatabaseId(mDatabase->Id()),
mLoggingSerialNumber(
mDatabase->GetLoggingInfo()->NextTransactionSN(aMode)),
mActiveRequestCount(0),
mInvalidatedOnAnyThread(false),
mMode(aMode),
mDurability(aDurability),
mResultCode(NS_OK) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mDatabase);
MOZ_ASSERT(mLoggingSerialNumber);
}
TransactionBase::~TransactionBase() {
MOZ_ASSERT(!mActiveRequestCount);
MOZ_ASSERT(mActorDestroyed);
MOZ_ASSERT_IF(mInitialized, mCommittedOrAborted);
}
void TransactionBase::Abort(nsresult aResultCode, bool aForce) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(NS_FAILED(aResultCode));
if (NS_SUCCEEDED(mResultCode)) {
mResultCode = aResultCode;
}
if (aForce) {
mForceAborted.EnsureFlipped();
}
MaybeCommitOrAbort();
}
mozilla::ipc::IPCResult TransactionBase::RecvCommit(
IProtocol* aActor, const Maybe<int64_t> aLastRequest) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(mCommitOrAbortReceived)) {
return IPC_FAIL(
aActor, "Attempt to commit an already comitted/aborted transaction!");
}
mCommitOrAbortReceived.Flip();
mLastRequestBeforeCommit.init(aLastRequest);
MaybeCommitOrAbort();
return IPC_OK();
}
mozilla::ipc::IPCResult TransactionBase::RecvAbort(IProtocol* aActor,
nsresult aResultCode) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(NS_SUCCEEDED(aResultCode))) {
return IPC_FAIL(aActor, "aResultCode must not be a success code!");
}
if (NS_WARN_IF(NS_ERROR_GET_MODULE(aResultCode) !=
NS_ERROR_MODULE_DOM_INDEXEDDB)) {
return IPC_FAIL(aActor, "aResultCode does not refer to IndexedDB!");
}
if (NS_WARN_IF(mCommitOrAbortReceived)) {
return IPC_FAIL(
aActor, "Attempt to abort an already comitted/aborted transaction!");
}
mCommitOrAbortReceived.Flip();
Abort(aResultCode, /* aForce */ false);
return IPC_OK();
}
void TransactionBase::CommitOrAbort() {
AssertIsOnBackgroundThread();
mCommittedOrAborted.Flip();
if (!mInitialized) {
return;
}
// In case of a failed request and explicitly committed transaction, abort
// (cf. https://w3c.github.io/IndexedDB/#async-execute-request step 5.3
// vs. 5.4). It's worth emphasizing this can only happen here when we are
// committing explicitly, otherwise the decision is made by the child.
if (NS_SUCCEEDED(mResultCode) && mLastFailedRequest &&
*mLastRequestBeforeCommit &&
*mLastFailedRequest == **mLastRequestBeforeCommit) {
mResultCode = NS_ERROR_DOM_INDEXEDDB_ABORT_ERR;
}
RefPtr<CommitOp> commitOp =
new CommitOp(SafeRefPtrFromThis(), ClampResultCode(mResultCode));
gConnectionPool->Finish(TransactionId(), commitOp);
}
SafeRefPtr<FullObjectStoreMetadata>
TransactionBase::GetMetadataForObjectStoreId(
IndexOrObjectStoreId aObjectStoreId) const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aObjectStoreId);
if (!aObjectStoreId) {
return nullptr;
}
auto metadata = mDatabase->Metadata().mObjectStores.Lookup(aObjectStoreId);
if (!metadata || (*metadata)->mDeleted) {
return nullptr;
}
MOZ_ASSERT((*metadata)->mCommonMetadata.id() == aObjectStoreId);
return metadata->clonePtr();
}
SafeRefPtr<FullIndexMetadata> TransactionBase::GetMetadataForIndexId(
FullObjectStoreMetadata& aObjectStoreMetadata,
IndexOrObjectStoreId aIndexId) const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aIndexId);
if (!aIndexId) {
return nullptr;
}
auto metadata = aObjectStoreMetadata.mIndexes.Lookup(aIndexId);
if (!metadata || (*metadata)->mDeleted) {
return nullptr;
}
MOZ_ASSERT((*metadata)->mCommonMetadata.id() == aIndexId);
return metadata->clonePtr();
}
void TransactionBase::NoteModifiedAutoIncrementObjectStore(
const SafeRefPtr<FullObjectStoreMetadata>& aMetadata) {
AssertIsOnConnectionThread();
if (!mModifiedAutoIncrementObjectStoreMetadataArray.Contains(aMetadata)) {
mModifiedAutoIncrementObjectStoreMetadataArray.AppendElement(
aMetadata.clonePtr());
}
}
void TransactionBase::ForgetModifiedAutoIncrementObjectStore(
FullObjectStoreMetadata& aMetadata) {
AssertIsOnConnectionThread();
mModifiedAutoIncrementObjectStoreMetadataArray.RemoveElement(&aMetadata);
}
bool TransactionBase::VerifyRequestParams(const RequestParams& aParams) const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() != RequestParams::T__None);
switch (aParams.type()) {
case RequestParams::TObjectStoreAddParams: {
const ObjectStoreAddPutParams& params =
aParams.get_ObjectStoreAddParams().commonParams();
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params))) {
return false;
}
break;
}
case RequestParams::TObjectStorePutParams: {
const ObjectStoreAddPutParams& params =
aParams.get_ObjectStorePutParams().commonParams();
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params))) {
return false;
}
break;
}
case RequestParams::TObjectStoreGetParams: {
const ObjectStoreGetParams& params = aParams.get_ObjectStoreGetParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.keyRange()))) {
return false;
}
break;
}
case RequestParams::TObjectStoreGetKeyParams: {
const ObjectStoreGetKeyParams& params =
aParams.get_ObjectStoreGetKeyParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.keyRange()))) {
return false;
}
break;
}
case RequestParams::TObjectStoreGetAllParams: {
const ObjectStoreGetAllParams& params =
aParams.get_ObjectStoreGetAllParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.optionalKeyRange()))) {
return false;
}
break;
}
case RequestParams::TObjectStoreGetAllKeysParams: {
const ObjectStoreGetAllKeysParams& params =
aParams.get_ObjectStoreGetAllKeysParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.optionalKeyRange()))) {
return false;
}
break;
}
case RequestParams::TObjectStoreDeleteParams: {
if (NS_AUUF_OR_WARN_IF(mMode != IDBTransaction::Mode::ReadWrite &&
mMode != IDBTransaction::Mode::ReadWriteFlush &&
mMode != IDBTransaction::Mode::Cleanup &&
mMode != IDBTransaction::Mode::VersionChange)) {
return false;
}
const ObjectStoreDeleteParams& params =
aParams.get_ObjectStoreDeleteParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.keyRange()))) {
return false;
}
break;
}
case RequestParams::TObjectStoreClearParams: {
if (NS_AUUF_OR_WARN_IF(mMode != IDBTransaction::Mode::ReadWrite &&
mMode != IDBTransaction::Mode::ReadWriteFlush &&
mMode != IDBTransaction::Mode::Cleanup &&
mMode != IDBTransaction::Mode::VersionChange)) {
return false;
}
const ObjectStoreClearParams& params =
aParams.get_ObjectStoreClearParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
break;
}
case RequestParams::TObjectStoreCountParams: {
const ObjectStoreCountParams& params =
aParams.get_ObjectStoreCountParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.optionalKeyRange()))) {
return false;
}
break;
}
case RequestParams::TIndexGetParams: {
const IndexGetParams& params = aParams.get_IndexGetParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
const SafeRefPtr<FullIndexMetadata> indexMetadata =
GetMetadataForIndexId(*objectStoreMetadata, params.indexId());
if (NS_AUUF_OR_WARN_IF(!indexMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.keyRange()))) {
return false;
}
break;
}
case RequestParams::TIndexGetKeyParams: {
const IndexGetKeyParams& params = aParams.get_IndexGetKeyParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
const SafeRefPtr<FullIndexMetadata> indexMetadata =
GetMetadataForIndexId(*objectStoreMetadata, params.indexId());
if (NS_AUUF_OR_WARN_IF(!indexMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.keyRange()))) {
return false;
}
break;
}
case RequestParams::TIndexGetAllParams: {
const IndexGetAllParams& params = aParams.get_IndexGetAllParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
const SafeRefPtr<FullIndexMetadata> indexMetadata =
GetMetadataForIndexId(*objectStoreMetadata, params.indexId());
if (NS_AUUF_OR_WARN_IF(!indexMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.optionalKeyRange()))) {
return false;
}
break;
}
case RequestParams::TIndexGetAllKeysParams: {
const IndexGetAllKeysParams& params = aParams.get_IndexGetAllKeysParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
const SafeRefPtr<FullIndexMetadata> indexMetadata =
GetMetadataForIndexId(*objectStoreMetadata, params.indexId());
if (NS_AUUF_OR_WARN_IF(!indexMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.optionalKeyRange()))) {
return false;
}
break;
}
case RequestParams::TIndexCountParams: {
const IndexCountParams& params = aParams.get_IndexCountParams();
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
GetMetadataForObjectStoreId(params.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return false;
}
const SafeRefPtr<FullIndexMetadata> indexMetadata =
GetMetadataForIndexId(*objectStoreMetadata, params.indexId());
if (NS_AUUF_OR_WARN_IF(!indexMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(params.optionalKeyRange()))) {
return false;
}
break;
}
default:
MOZ_CRASH("Should never get here!");
}
return true;
}
bool TransactionBase::VerifyRequestParams(
const SerializedKeyRange& aParams) const {
AssertIsOnBackgroundThread();
// XXX Check more here?
if (aParams.isOnly()) {
if (NS_AUUF_OR_WARN_IF(aParams.lower().IsUnset())) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!aParams.upper().IsUnset())) {
return false;
}
if (NS_AUUF_OR_WARN_IF(aParams.lowerOpen())) {
return false;
}
if (NS_AUUF_OR_WARN_IF(aParams.upperOpen())) {
return false;
}
} else if (NS_AUUF_OR_WARN_IF(aParams.lower().IsUnset() &&
aParams.upper().IsUnset())) {
return false;
}
return true;
}
bool TransactionBase::VerifyRequestParams(
const ObjectStoreAddPutParams& aParams) const {
AssertIsOnBackgroundThread();
if (NS_AUUF_OR_WARN_IF(mMode != IDBTransaction::Mode::ReadWrite &&
mMode != IDBTransaction::Mode::ReadWriteFlush &&
mMode != IDBTransaction::Mode::VersionChange)) {
return false;
}
SafeRefPtr<FullObjectStoreMetadata> objMetadata =
GetMetadataForObjectStoreId(aParams.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(!aParams.cloneInfo().data().data.Size())) {
return false;
}
if (objMetadata->mCommonMetadata.autoIncrement() &&
objMetadata->mCommonMetadata.keyPath().IsValid() &&
aParams.key().IsUnset()) {
const SerializedStructuredCloneWriteInfo& cloneInfo = aParams.cloneInfo();
if (NS_AUUF_OR_WARN_IF(!cloneInfo.offsetToKeyProp())) {
return false;
}
if (NS_AUUF_OR_WARN_IF(cloneInfo.data().data.Size() < sizeof(uint64_t))) {
return false;
}
if (NS_AUUF_OR_WARN_IF(cloneInfo.offsetToKeyProp() >
(cloneInfo.data().data.Size() - sizeof(uint64_t)))) {
return false;
}
} else if (NS_AUUF_OR_WARN_IF(aParams.cloneInfo().offsetToKeyProp())) {
return false;
}
for (const auto& updateInfo : aParams.indexUpdateInfos()) {
SafeRefPtr<FullIndexMetadata> indexMetadata =
GetMetadataForIndexId(*objMetadata, updateInfo.indexId());
if (NS_AUUF_OR_WARN_IF(!indexMetadata)) {
return false;
}
if (NS_AUUF_OR_WARN_IF(updateInfo.value().IsUnset())) {
return false;
}
MOZ_ASSERT(!updateInfo.value().GetBuffer().IsEmpty());
}
for (const FileAddInfo& fileAddInfo : aParams.fileAddInfos()) {
const PBackgroundIDBDatabaseFileParent* file =
fileAddInfo.file().AsParent();
switch (fileAddInfo.type()) {
case StructuredCloneFileBase::eBlob:
if (NS_AUUF_OR_WARN_IF(!file)) {
return false;
}
break;
case StructuredCloneFileBase::eMutableFile: {
return false;
}
case StructuredCloneFileBase::eStructuredClone:
case StructuredCloneFileBase::eWasmBytecode:
case StructuredCloneFileBase::eWasmCompiled:
case StructuredCloneFileBase::eEndGuard:
MOZ_ASSERT_UNLESS_FUZZING(false, "Unsupported.");
return false;
default:
MOZ_CRASH("Should never get here!");
}
}
return true;
}
bool TransactionBase::VerifyRequestParams(
const Maybe<SerializedKeyRange>& aParams) const {
AssertIsOnBackgroundThread();
if (aParams.isSome()) {
if (NS_AUUF_OR_WARN_IF(!VerifyRequestParams(aParams.ref()))) {
return false;
}
}
return true;
}
void TransactionBase::NoteActiveRequest() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mActiveRequestCount < UINT64_MAX);
mActiveRequestCount++;
}
void TransactionBase::NoteFinishedRequest(const int64_t aRequestId,
const nsresult aResultCode) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mActiveRequestCount);
mActiveRequestCount--;
if (NS_FAILED(aResultCode)) {
mLastFailedRequest = Some(aRequestId);
}
MaybeCommitOrAbort();
}
void TransactionBase::Invalidate() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mInvalidated == mInvalidatedOnAnyThread);
if (!mInvalidated) {
mInvalidated.Flip();
mInvalidatedOnAnyThread = true;
Abort(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR, /* aForce */ false);
}
}
PBackgroundIDBRequestParent* TransactionBase::AllocRequest(
const int64_t aRequestId, RequestParams&& aParams, bool aTrustParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() != RequestParams::T__None);
#ifdef DEBUG
// Always verify parameters in DEBUG builds!
aTrustParams = false;
#endif
if (NS_AUUF_OR_WARN_IF(!aTrustParams && !VerifyRequestParams(aParams))) {
return nullptr;
}
if (NS_AUUF_OR_WARN_IF(mCommitOrAbortReceived)) {
return nullptr;
}
RefPtr<NormalTransactionOp> actor;
switch (aParams.type()) {
case RequestParams::TObjectStoreAddParams:
case RequestParams::TObjectStorePutParams:
actor = new ObjectStoreAddOrPutRequestOp(SafeRefPtrFromThis(), aRequestId,
std::move(aParams));
break;
case RequestParams::TObjectStoreGetParams:
actor =
new ObjectStoreGetRequestOp(SafeRefPtrFromThis(), aRequestId, aParams,
/* aGetAll */ false);
break;
case RequestParams::TObjectStoreGetAllParams:
actor =
new ObjectStoreGetRequestOp(SafeRefPtrFromThis(), aRequestId, aParams,
/* aGetAll */ true);
break;
case RequestParams::TObjectStoreGetKeyParams:
actor = new ObjectStoreGetKeyRequestOp(SafeRefPtrFromThis(), aRequestId,
aParams,
/* aGetAll */ false);
break;
case RequestParams::TObjectStoreGetAllKeysParams:
actor = new ObjectStoreGetKeyRequestOp(SafeRefPtrFromThis(), aRequestId,
aParams,
/* aGetAll */ true);
break;
case RequestParams::TObjectStoreDeleteParams:
actor =
new ObjectStoreDeleteRequestOp(SafeRefPtrFromThis(), aRequestId,
aParams.get_ObjectStoreDeleteParams());
break;
case RequestParams::TObjectStoreClearParams:
actor =
new ObjectStoreClearRequestOp(SafeRefPtrFromThis(), aRequestId,
aParams.get_ObjectStoreClearParams());
break;
case RequestParams::TObjectStoreCountParams:
actor =
new ObjectStoreCountRequestOp(SafeRefPtrFromThis(), aRequestId,
aParams.get_ObjectStoreCountParams());
break;
case RequestParams::TIndexGetParams:
actor = new IndexGetRequestOp(SafeRefPtrFromThis(), aRequestId, aParams,
/* aGetAll */ false);
break;
case RequestParams::TIndexGetKeyParams:
actor =
new IndexGetKeyRequestOp(SafeRefPtrFromThis(), aRequestId, aParams,
/* aGetAll */ false);
break;
case RequestParams::TIndexGetAllParams:
actor = new IndexGetRequestOp(SafeRefPtrFromThis(), aRequestId, aParams,
/* aGetAll */ true);
break;
case RequestParams::TIndexGetAllKeysParams:
actor =
new IndexGetKeyRequestOp(SafeRefPtrFromThis(), aRequestId, aParams,
/* aGetAll */ true);
break;
case RequestParams::TIndexCountParams:
actor =
new IndexCountRequestOp(SafeRefPtrFromThis(), aRequestId, aParams);
break;
default:
MOZ_CRASH("Should never get here!");
}
MOZ_ASSERT(actor);
// Transfer ownership to IPDL.
return actor.forget().take();
}
bool TransactionBase::StartRequest(PBackgroundIDBRequestParent* aActor) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
auto* op = static_cast<NormalTransactionOp*>(aActor);
if (NS_WARN_IF(!op->Init(*this))) {
op->Cleanup();
return false;
}
op->DispatchToConnectionPool();
return true;
}
bool TransactionBase::DeallocRequest(
PBackgroundIDBRequestParent* const aActor) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
// Transfer ownership back from IPDL.
const RefPtr<NormalTransactionOp> actor =
dont_AddRef(static_cast<NormalTransactionOp*>(aActor));
return true;
}
already_AddRefed<PBackgroundIDBCursorParent> TransactionBase::AllocCursor(
const OpenCursorParams& aParams, bool aTrustParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() != OpenCursorParams::T__None);
#ifdef DEBUG
// Always verify parameters in DEBUG builds!
aTrustParams = false;
#endif
const OpenCursorParams::Type type = aParams.type();
SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata;
SafeRefPtr<FullIndexMetadata> indexMetadata;
CursorBase::Direction direction;
// First extract the parameters common to all open cursor variants.
const auto& commonParams = GetCommonOpenCursorParams(aParams);
objectStoreMetadata =
GetMetadataForObjectStoreId(commonParams.objectStoreId());
if (NS_AUUF_OR_WARN_IF(!objectStoreMetadata)) {
return nullptr;
}
if (aTrustParams && NS_AUUF_OR_WARN_IF(!VerifyRequestParams(
commonParams.optionalKeyRange()))) {
return nullptr;
}
direction = commonParams.direction();
// Now, for the index open cursor variants, extract the additional parameter.
if (type == OpenCursorParams::TIndexOpenCursorParams ||
type == OpenCursorParams::TIndexOpenKeyCursorParams) {
const auto& commonIndexParams = GetCommonIndexOpenCursorParams(aParams);
indexMetadata = GetMetadataForIndexId(*objectStoreMetadata,
commonIndexParams.indexId());
if (NS_AUUF_OR_WARN_IF(!indexMetadata)) {
return nullptr;
}
}
if (NS_AUUF_OR_WARN_IF(mCommitOrAbortReceived)) {
return nullptr;
}
// Create Cursor and transfer ownership to IPDL.
switch (type) {
case OpenCursorParams::TObjectStoreOpenCursorParams:
MOZ_ASSERT(!indexMetadata);
return MakeAndAddRef<Cursor<IDBCursorType::ObjectStore>>(
SafeRefPtrFromThis(), std::move(objectStoreMetadata), direction,
CursorBase::ConstructFromTransactionBase{});
case OpenCursorParams::TObjectStoreOpenKeyCursorParams:
MOZ_ASSERT(!indexMetadata);
return MakeAndAddRef<Cursor<IDBCursorType::ObjectStoreKey>>(
SafeRefPtrFromThis(), std::move(objectStoreMetadata), direction,
CursorBase::ConstructFromTransactionBase{});
case OpenCursorParams::TIndexOpenCursorParams:
return MakeAndAddRef<Cursor<IDBCursorType::Index>>(
SafeRefPtrFromThis(), std::move(objectStoreMetadata),
std::move(indexMetadata), direction,
CursorBase::ConstructFromTransactionBase{});
case OpenCursorParams::TIndexOpenKeyCursorParams:
return MakeAndAddRef<Cursor<IDBCursorType::IndexKey>>(
SafeRefPtrFromThis(), std::move(objectStoreMetadata),
std::move(indexMetadata), direction,
CursorBase::ConstructFromTransactionBase{});
default:
MOZ_CRASH("Cannot get here.");
}
}
bool TransactionBase::StartCursor(PBackgroundIDBCursorParent* const aActor,
const int64_t aRequestId,
const OpenCursorParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
MOZ_ASSERT(aParams.type() != OpenCursorParams::T__None);
auto* const op = static_cast<CursorBase*>(aActor);
if (NS_WARN_IF(!op->Start(aRequestId, aParams))) {
return false;
}
return true;
}
/*******************************************************************************
* NormalTransaction
******************************************************************************/
NormalTransaction::NormalTransaction(
SafeRefPtr<Database> aDatabase, TransactionBase::Mode aMode,
TransactionBase::Durability aDurability,
nsTArray<SafeRefPtr<FullObjectStoreMetadata>>&& aObjectStores)
: TransactionBase(std::move(aDatabase), aMode, aDurability),
mObjectStores{std::move(aObjectStores)} {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mObjectStores.IsEmpty());
}
bool NormalTransaction::IsSameProcessActor() {
AssertIsOnBackgroundThread();
PBackgroundParent* const actor = Manager()->Manager()->Manager();
MOZ_ASSERT(actor);
return !BackgroundParent::IsOtherProcessActor(actor);
}
void NormalTransaction::SendCompleteNotification(nsresult aResult) {
AssertIsOnBackgroundThread();
if (!IsActorDestroyed()) {
Unused << SendComplete(aResult);
}
}
void NormalTransaction::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnBackgroundThread();
NoteActorDestroyed();
if (!mCommittedOrAborted) {
if (NS_SUCCEEDED(mResultCode)) {
IDB_REPORT_INTERNAL_ERR();
mResultCode = NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
mForceAborted.EnsureFlipped();
MaybeCommitOrAbort();
}
}
mozilla::ipc::IPCResult NormalTransaction::RecvDeleteMe() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!IsActorDestroyed());
QM_WARNONLY_TRY(OkIf(PBackgroundIDBTransactionParent::Send__delete__(this)));
return IPC_OK();
}
mozilla::ipc::IPCResult NormalTransaction::RecvCommit(
const Maybe<int64_t>& aLastRequest) {
AssertIsOnBackgroundThread();
return TransactionBase::RecvCommit(this, aLastRequest);
}
mozilla::ipc::IPCResult NormalTransaction::RecvAbort(
const nsresult& aResultCode) {
AssertIsOnBackgroundThread();
return TransactionBase::RecvAbort(this, aResultCode);
}
PBackgroundIDBRequestParent*
NormalTransaction::AllocPBackgroundIDBRequestParent(
const int64_t& aRequestId, const RequestParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() != RequestParams::T__None);
return AllocRequest(aRequestId,
std::move(const_cast<RequestParams&>(aParams)),
IsSameProcessActor());
}
mozilla::ipc::IPCResult NormalTransaction::RecvPBackgroundIDBRequestConstructor(
PBackgroundIDBRequestParent* const aActor, const int64_t& aRequestId,
const RequestParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
MOZ_ASSERT(aParams.type() != RequestParams::T__None);
if (!StartRequest(aActor)) {
return IPC_FAIL(this, "StartRequest failed!");
}
return IPC_OK();
}
bool NormalTransaction::DeallocPBackgroundIDBRequestParent(
PBackgroundIDBRequestParent* const aActor) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
return DeallocRequest(aActor);
}
already_AddRefed<PBackgroundIDBCursorParent>
NormalTransaction::AllocPBackgroundIDBCursorParent(
const int64_t& aRequestId, const OpenCursorParams& aParams) {
AssertIsOnBackgroundThread();
return AllocCursor(aParams, IsSameProcessActor());
}
mozilla::ipc::IPCResult NormalTransaction::RecvPBackgroundIDBCursorConstructor(
PBackgroundIDBCursorParent* const aActor, const int64_t& aRequestId,
const OpenCursorParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
MOZ_ASSERT(aParams.type() != OpenCursorParams::T__None);
if (!StartCursor(aActor, aRequestId, aParams)) {
return IPC_FAIL(this, "StartCursor failed!");
}
return IPC_OK();
}
/*******************************************************************************
* VersionChangeTransaction
******************************************************************************/
VersionChangeTransaction::VersionChangeTransaction(
OpenDatabaseOp* aOpenDatabaseOp)
: TransactionBase(aOpenDatabaseOp->mDatabase.clonePtr(),
IDBTransaction::Mode::VersionChange,
// VersionChange must not change durability.
IDBTransaction::Durability::Default), // Not used.
mOpenDatabaseOp(aOpenDatabaseOp) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aOpenDatabaseOp);
}
VersionChangeTransaction::~VersionChangeTransaction() {
#ifdef DEBUG
// Silence the base class' destructor assertion if we never made this actor
// live.
FakeActorDestroyed();
#endif
}
bool VersionChangeTransaction::IsSameProcessActor() {
AssertIsOnBackgroundThread();
PBackgroundParent* actor = Manager()->Manager()->Manager();
MOZ_ASSERT(actor);
return !BackgroundParent::IsOtherProcessActor(actor);
}
void VersionChangeTransaction::SetActorAlive() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!IsActorDestroyed());
mActorWasAlive.Flip();
}
bool VersionChangeTransaction::CopyDatabaseMetadata() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mOldMetadata);
const auto& origMetadata = GetDatabase().Metadata();
SafeRefPtr<FullDatabaseMetadata> newMetadata = origMetadata.Duplicate();
if (NS_WARN_IF(!newMetadata)) {
return false;
}
// Replace the live metadata with the new mutable copy.
DatabaseActorInfo* info;
MOZ_ALWAYS_TRUE(gLiveDatabaseHashtable->Get(origMetadata.mDatabaseId, &info));
MOZ_ASSERT(!info->mLiveDatabases.isEmpty());
MOZ_ASSERT(info->mMetadata == &origMetadata);
mOldMetadata = std::move(info->mMetadata);
info->mMetadata = std::move(newMetadata);
// Replace metadata pointers for all live databases.
for (Database* const liveDatabase : info->mLiveDatabases) {
liveDatabase->mMetadata = info->mMetadata.clonePtr();
}
return true;
}
void VersionChangeTransaction::UpdateMetadata(nsresult aResult) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mOpenDatabaseOp);
MOZ_ASSERT(!!mActorWasAlive == !!mOpenDatabaseOp->mDatabase);
MOZ_ASSERT_IF(mActorWasAlive, !mOpenDatabaseOp->mDatabaseId.ref().IsEmpty());
if (IsActorDestroyed() || !mActorWasAlive) {
return;
}
SafeRefPtr<FullDatabaseMetadata> oldMetadata = std::move(mOldMetadata);
DatabaseActorInfo* info;
if (!gLiveDatabaseHashtable->Get(oldMetadata->mDatabaseId, &info)) {
return;
}
MOZ_ASSERT(!info->mLiveDatabases.isEmpty());
if (NS_SUCCEEDED(aResult)) {
// Remove all deleted objectStores and indexes, then mark immutable.
info->mMetadata->mObjectStores.RemoveIf([](const auto& objectStoreIter) {
MOZ_ASSERT(objectStoreIter.Key());
const SafeRefPtr<FullObjectStoreMetadata>& metadata =
objectStoreIter.Data();
MOZ_ASSERT(metadata);
if (metadata->mDeleted) {
return true;
}
metadata->mIndexes.RemoveIf([](const auto& indexIter) -> bool {
MOZ_ASSERT(indexIter.Key());
const SafeRefPtr<FullIndexMetadata>& index = indexIter.Data();
MOZ_ASSERT(index);
return index->mDeleted;
});
metadata->mIndexes.MarkImmutable();
return false;
});
info->mMetadata->mObjectStores.MarkImmutable();
} else {
// Replace metadata pointers for all live databases.
info->mMetadata = std::move(oldMetadata);
for (Database* const liveDatabase : info->mLiveDatabases) {
liveDatabase->mMetadata = info->mMetadata.clonePtr();
}
}
}
void VersionChangeTransaction::SendCompleteNotification(nsresult aResult) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mOpenDatabaseOp);
MOZ_ASSERT(!mOpenDatabaseOp->mCompleteCallback);
MOZ_ASSERT_IF(!mActorWasAlive, mOpenDatabaseOp->HasFailed());
MOZ_ASSERT_IF(!mActorWasAlive, mOpenDatabaseOp->mState >
OpenDatabaseOp::State::SendingResults);
const RefPtr<OpenDatabaseOp> openDatabaseOp = std::move(mOpenDatabaseOp);
if (!mActorWasAlive) {
return;
}
openDatabaseOp->mCompleteCallback =
[self = SafeRefPtr{this, AcquireStrongRefFromRawPtr{}}, aResult]() {
if (!self->IsActorDestroyed()) {
Unused << self->SendComplete(aResult);
}
};
auto handleError = [openDatabaseOp](const nsresult rv) {
openDatabaseOp->SetFailureCodeIfUnset(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
openDatabaseOp->mState = OpenDatabaseOp::State::SendingResults;
MOZ_ALWAYS_SUCCEEDS(openDatabaseOp->Run());
};
if (NS_FAILED(aResult)) {
// 3.3.1 Opening a database:
// "If the upgrade transaction was aborted, run the steps for closing a
// database connection with connection, create and return a new AbortError
// exception and abort these steps."
handleError(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
return;
}
openDatabaseOp->mState = OpenDatabaseOp::State::DatabaseWorkVersionUpdate;
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
QM_TRY(MOZ_TO_RESULT(quotaManager->IOThread()->Dispatch(openDatabaseOp,
NS_DISPATCH_NORMAL))
.mapErr(
[](const auto) { return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR; }),
QM_VOID, handleError);
}
void VersionChangeTransaction::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnBackgroundThread();
NoteActorDestroyed();
if (!mCommittedOrAborted) {
if (NS_SUCCEEDED(mResultCode)) {
IDB_REPORT_INTERNAL_ERR();
mResultCode = NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
mForceAborted.EnsureFlipped();
MaybeCommitOrAbort();
}
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvDeleteMe() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!IsActorDestroyed());
QM_WARNONLY_TRY(
OkIf(PBackgroundIDBVersionChangeTransactionParent::Send__delete__(this)));
return IPC_OK();
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvCommit(
const Maybe<int64_t>& aLastRequest) {
AssertIsOnBackgroundThread();
return TransactionBase::RecvCommit(this, aLastRequest);
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvAbort(
const nsresult& aResultCode) {
AssertIsOnBackgroundThread();
return TransactionBase::RecvAbort(this, aResultCode);
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvCreateObjectStore(
const ObjectStoreMetadata& aMetadata) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(!aMetadata.id())) {
return IPC_FAIL(this, "No metadata ID!");
}
const SafeRefPtr<FullDatabaseMetadata> dbMetadata =
GetDatabase().MetadataPtr();
if (NS_WARN_IF(aMetadata.id() != dbMetadata->mNextObjectStoreId)) {
return IPC_FAIL(this, "Requested metadata ID does not match next ID!");
}
if (NS_WARN_IF(
MatchMetadataNameOrId(dbMetadata->mObjectStores, aMetadata.id(),
SomeRef<const nsAString&>(aMetadata.name()))
.isSome())) {
return IPC_FAIL(this, "MatchMetadataNameOrId failed!");
}
if (NS_WARN_IF(mCommitOrAbortReceived)) {
return IPC_FAIL(this, "Transaction is already committed/aborted!");
}
const int64_t initialAutoIncrementId = aMetadata.autoIncrement() ? 1 : 0;
auto newMetadata = MakeSafeRefPtr<FullObjectStoreMetadata>(
aMetadata, FullObjectStoreMetadata::AutoIncrementIds{
initialAutoIncrementId, initialAutoIncrementId});
if (NS_WARN_IF(!dbMetadata->mObjectStores.InsertOrUpdate(
aMetadata.id(), std::move(newMetadata), fallible))) {
return IPC_FAIL(this, "mObjectStores.InsertOrUpdate failed!");
}
dbMetadata->mNextObjectStoreId++;
RefPtr<CreateObjectStoreOp> op = new CreateObjectStoreOp(
SafeRefPtrFromThis().downcast<VersionChangeTransaction>(), aMetadata);
if (NS_WARN_IF(!op->Init(*this))) {
op->Cleanup();
return IPC_FAIL(this, "ObjectStoreOp initialization failed!");
}
op->DispatchToConnectionPool();
return IPC_OK();
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvDeleteObjectStore(
const IndexOrObjectStoreId& aObjectStoreId) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(!aObjectStoreId)) {
return IPC_FAIL(this, "No ObjectStoreId!");
}
const auto& dbMetadata = GetDatabase().Metadata();
MOZ_ASSERT(dbMetadata.mNextObjectStoreId > 0);
if (NS_WARN_IF(aObjectStoreId >= dbMetadata.mNextObjectStoreId)) {
return IPC_FAIL(this, "Invalid ObjectStoreId!");
}
SafeRefPtr<FullObjectStoreMetadata> foundMetadata =
GetMetadataForObjectStoreId(aObjectStoreId);
if (NS_WARN_IF(!foundMetadata)) {
return IPC_FAIL(this, "No metadata found for ObjectStoreId!");
}
if (NS_WARN_IF(mCommitOrAbortReceived)) {
return IPC_FAIL(this, "Transaction is already committed/aborted!");
}
foundMetadata->mDeleted.Flip();
DebugOnly<bool> foundTargetId = false;
const bool isLastObjectStore = std::all_of(
dbMetadata.mObjectStores.begin(), dbMetadata.mObjectStores.end(),
[&foundTargetId, aObjectStoreId](const auto& objectStoreEntry) -> bool {
if (uint64_t(aObjectStoreId) == objectStoreEntry.GetKey()) {
foundTargetId = true;
return true;
}
return objectStoreEntry.GetData()->mDeleted;
});
MOZ_ASSERT_IF(isLastObjectStore, foundTargetId);
RefPtr<DeleteObjectStoreOp> op = new DeleteObjectStoreOp(
SafeRefPtrFromThis().downcast<VersionChangeTransaction>(),
std::move(foundMetadata), isLastObjectStore);
if (NS_WARN_IF(!op->Init(*this))) {
op->Cleanup();
return IPC_FAIL(this, "ObjectStoreOp initialization failed!");
}
op->DispatchToConnectionPool();
return IPC_OK();
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvRenameObjectStore(
const IndexOrObjectStoreId& aObjectStoreId, const nsAString& aName) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(!aObjectStoreId)) {
return IPC_FAIL(this, "No ObjectStoreId!");
}
{
const auto& dbMetadata = GetDatabase().Metadata();
MOZ_ASSERT(dbMetadata.mNextObjectStoreId > 0);
if (NS_WARN_IF(aObjectStoreId >= dbMetadata.mNextObjectStoreId)) {
return IPC_FAIL(this, "Invalid ObjectStoreId!");
}
}
SafeRefPtr<FullObjectStoreMetadata> foundMetadata =
GetMetadataForObjectStoreId(aObjectStoreId);
if (NS_WARN_IF(!foundMetadata)) {
return IPC_FAIL(this, "No metadata found for ObjectStoreId!");
}
if (NS_WARN_IF(mCommitOrAbortReceived)) {
return IPC_FAIL(this, "Transaction is already committed/aborted!");
}
foundMetadata->mCommonMetadata.name() = aName;
RefPtr<RenameObjectStoreOp> renameOp = new RenameObjectStoreOp(
SafeRefPtrFromThis().downcast<VersionChangeTransaction>(),
*foundMetadata);
if (NS_WARN_IF(!renameOp->Init(*this))) {
renameOp->Cleanup();
return IPC_FAIL(this, "ObjectStoreOp initialization failed!");
}
renameOp->DispatchToConnectionPool();
return IPC_OK();
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvCreateIndex(
const IndexOrObjectStoreId& aObjectStoreId,
const IndexMetadata& aMetadata) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(!aObjectStoreId)) {
return IPC_FAIL(this, "No ObjectStoreId!");
}
if (NS_WARN_IF(!aMetadata.id())) {
return IPC_FAIL(this, "No Metadata id!");
}
const auto dbMetadata = GetDatabase().MetadataPtr();
if (NS_WARN_IF(aMetadata.id() != dbMetadata->mNextIndexId)) {
return IPC_FAIL(this, "Requested metadata ID does not match next ID!");
}
SafeRefPtr<FullObjectStoreMetadata> foundObjectStoreMetadata =
GetMetadataForObjectStoreId(aObjectStoreId);
if (NS_WARN_IF(!foundObjectStoreMetadata)) {
return IPC_FAIL(this, "GetMetadataForObjectStoreId failed!");
}
if (NS_WARN_IF(MatchMetadataNameOrId(
foundObjectStoreMetadata->mIndexes, aMetadata.id(),
SomeRef<const nsAString&>(aMetadata.name()))
.isSome())) {
return IPC_FAIL(this, "MatchMetadataNameOrId failed!");
}
if (NS_WARN_IF(mCommitOrAbortReceived)) {
return IPC_FAIL(this, "Transaction is already committed/aborted!");
}
auto newMetadata = MakeSafeRefPtr<FullIndexMetadata>();
newMetadata->mCommonMetadata = aMetadata;
if (NS_WARN_IF(!foundObjectStoreMetadata->mIndexes.InsertOrUpdate(
aMetadata.id(), std::move(newMetadata), fallible))) {
return IPC_FAIL(this, "mIndexes.InsertOrUpdate failed!");
}
dbMetadata->mNextIndexId++;
RefPtr<CreateIndexOp> op = new CreateIndexOp(
SafeRefPtrFromThis().downcast<VersionChangeTransaction>(), aObjectStoreId,
aMetadata);
if (NS_WARN_IF(!op->Init(*this))) {
op->Cleanup();
return IPC_FAIL(this, "ObjectStoreOp initialization failed!");
}
op->DispatchToConnectionPool();
return IPC_OK();
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvDeleteIndex(
const IndexOrObjectStoreId& aObjectStoreId,
const IndexOrObjectStoreId& aIndexId) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(!aObjectStoreId)) {
return IPC_FAIL(this, "No ObjectStoreId!");
}
if (NS_WARN_IF(!aIndexId)) {
return IPC_FAIL(this, "No Index id!");
}
{
const auto& dbMetadata = GetDatabase().Metadata();
MOZ_ASSERT(dbMetadata.mNextObjectStoreId > 0);
MOZ_ASSERT(dbMetadata.mNextIndexId > 0);
if (NS_WARN_IF(aObjectStoreId >= dbMetadata.mNextObjectStoreId)) {
return IPC_FAIL(this, "Requested ObjectStoreId does not match next ID!");
}
if (NS_WARN_IF(aIndexId >= dbMetadata.mNextIndexId)) {
return IPC_FAIL(this, "Requested IndexId does not match next ID!");
}
}
SafeRefPtr<FullObjectStoreMetadata> foundObjectStoreMetadata =
GetMetadataForObjectStoreId(aObjectStoreId);
if (NS_WARN_IF(!foundObjectStoreMetadata)) {
return IPC_FAIL(this, "GetMetadataForObjectStoreId failed!");
}
SafeRefPtr<FullIndexMetadata> foundIndexMetadata =
GetMetadataForIndexId(*foundObjectStoreMetadata, aIndexId);
if (NS_WARN_IF(!foundIndexMetadata)) {
return IPC_FAIL(this, "GetMetadataForIndexId failed!");
}
if (NS_WARN_IF(mCommitOrAbortReceived)) {
return IPC_FAIL(this, "Transaction is already committed/aborted!");
}
foundIndexMetadata->mDeleted.Flip();
DebugOnly<bool> foundTargetId = false;
const bool isLastIndex =
std::all_of(foundObjectStoreMetadata->mIndexes.cbegin(),
foundObjectStoreMetadata->mIndexes.cend(),
[&foundTargetId, aIndexId](const auto& indexEntry) -> bool {
if (uint64_t(aIndexId) == indexEntry.GetKey()) {
foundTargetId = true;
return true;
}
return indexEntry.GetData()->mDeleted;
});
MOZ_ASSERT_IF(isLastIndex, foundTargetId);
RefPtr<DeleteIndexOp> op = new DeleteIndexOp(
SafeRefPtrFromThis().downcast<VersionChangeTransaction>(), aObjectStoreId,
aIndexId, foundIndexMetadata->mCommonMetadata.unique(), isLastIndex);
if (NS_WARN_IF(!op->Init(*this))) {
op->Cleanup();
return IPC_FAIL(this, "ObjectStoreOp initialization failed!");
}
op->DispatchToConnectionPool();
return IPC_OK();
}
mozilla::ipc::IPCResult VersionChangeTransaction::RecvRenameIndex(
const IndexOrObjectStoreId& aObjectStoreId,
const IndexOrObjectStoreId& aIndexId, const nsAString& aName) {
AssertIsOnBackgroundThread();
if (NS_WARN_IF(!aObjectStoreId)) {
return IPC_FAIL(this, "No ObjectStoreId!");
}
if (NS_WARN_IF(!aIndexId)) {
return IPC_FAIL(this, "No Index id!");
}
const SafeRefPtr<FullDatabaseMetadata> dbMetadata =
GetDatabase().MetadataPtr();
MOZ_ASSERT(dbMetadata);
MOZ_ASSERT(dbMetadata->mNextObjectStoreId > 0);
MOZ_ASSERT(dbMetadata->mNextIndexId > 0);
if (NS_WARN_IF(aObjectStoreId >= dbMetadata->mNextObjectStoreId)) {
return IPC_FAIL(this, "Requested ObjectStoreId does not match next ID!");
}
if (NS_WARN_IF(aIndexId >= dbMetadata->mNextIndexId)) {
return IPC_FAIL(this, "Requested IndexId does not match next ID!");
}
SafeRefPtr<FullObjectStoreMetadata> foundObjectStoreMetadata =
GetMetadataForObjectStoreId(aObjectStoreId);
if (NS_WARN_IF(!foundObjectStoreMetadata)) {
return IPC_FAIL(this, "GetMetadataForObjectStoreId failed!");
}
SafeRefPtr<FullIndexMetadata> foundIndexMetadata =
GetMetadataForIndexId(*foundObjectStoreMetadata, aIndexId);
if (NS_WARN_IF(!foundIndexMetadata)) {
return IPC_FAIL(this, "GetMetadataForIndexId failed!");
}
if (NS_WARN_IF(mCommitOrAbortReceived)) {
return IPC_FAIL(this, "Transaction is already committed/aborted!");
}
foundIndexMetadata->mCommonMetadata.name() = aName;
RefPtr<RenameIndexOp> renameOp = new RenameIndexOp(
SafeRefPtrFromThis().downcast<VersionChangeTransaction>(),
*foundIndexMetadata, aObjectStoreId);
if (NS_WARN_IF(!renameOp->Init(*this))) {
renameOp->Cleanup();
return IPC_FAIL(this, "ObjectStoreOp initialization failed!");
}
renameOp->DispatchToConnectionPool();
return IPC_OK();
}
PBackgroundIDBRequestParent*
VersionChangeTransaction::AllocPBackgroundIDBRequestParent(
const int64_t& aRequestId, const RequestParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() != RequestParams::T__None);
return AllocRequest(aRequestId,
std::move(const_cast<RequestParams&>(aParams)),
IsSameProcessActor());
}
mozilla::ipc::IPCResult
VersionChangeTransaction::RecvPBackgroundIDBRequestConstructor(
PBackgroundIDBRequestParent* aActor, const int64_t& aRequestId,
const RequestParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
MOZ_ASSERT(aParams.type() != RequestParams::T__None);
if (!StartRequest(aActor)) {
return IPC_FAIL(this, "StartRequest failed!");
}
return IPC_OK();
}
bool VersionChangeTransaction::DeallocPBackgroundIDBRequestParent(
PBackgroundIDBRequestParent* aActor) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
return DeallocRequest(aActor);
}
already_AddRefed<PBackgroundIDBCursorParent>
VersionChangeTransaction::AllocPBackgroundIDBCursorParent(
const int64_t& aRequestId, const OpenCursorParams& aParams) {
AssertIsOnBackgroundThread();
return AllocCursor(aParams, IsSameProcessActor());
}
mozilla::ipc::IPCResult
VersionChangeTransaction::RecvPBackgroundIDBCursorConstructor(
PBackgroundIDBCursorParent* aActor, const int64_t& aRequestId,
const OpenCursorParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aActor);
MOZ_ASSERT(aParams.type() != OpenCursorParams::T__None);
if (!StartCursor(aActor, aRequestId, aParams)) {
return IPC_FAIL(this, "StartCursor failed!");
}
return IPC_OK();
}
/*******************************************************************************
* CursorBase
******************************************************************************/
CursorBase::CursorBase(SafeRefPtr<TransactionBase> aTransaction,
SafeRefPtr<FullObjectStoreMetadata> aObjectStoreMetadata,
const Direction aDirection,
const ConstructFromTransactionBase /*aConstructionTag*/)
: mTransaction(std::move(aTransaction)),
mObjectStoreMetadata(WrapNotNull(std::move(aObjectStoreMetadata))),
mObjectStoreId((*mObjectStoreMetadata)->mCommonMetadata.id()),
mDirection(aDirection),
mMaxExtraCount(IndexedDatabaseManager::MaxPreloadExtraRecords()),
mIsSameProcessActor(!BackgroundParent::IsOtherProcessActor(
mTransaction->GetBackgroundParent())) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mTransaction);
static_assert(
OpenCursorParams::T__None == 0 && OpenCursorParams::T__Last == 4,
"Lots of code here assumes only four types of cursors!");
}
template <IDBCursorType CursorType>
bool Cursor<CursorType>::VerifyRequestParams(
const CursorRequestParams& aParams,
const CursorPosition<CursorType>& aPosition) const {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() != CursorRequestParams::T__None);
MOZ_ASSERT(this->mObjectStoreMetadata);
if constexpr (IsIndexCursor) {
MOZ_ASSERT(this->mIndexMetadata);
}
#ifdef DEBUG
{
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
mTransaction->GetMetadataForObjectStoreId(mObjectStoreId);
if (objectStoreMetadata) {
MOZ_ASSERT(objectStoreMetadata == (*this->mObjectStoreMetadata));
} else {
MOZ_ASSERT((*this->mObjectStoreMetadata)->mDeleted);
}
if constexpr (IsIndexCursor) {
if (objectStoreMetadata) {
const SafeRefPtr<FullIndexMetadata> indexMetadata =
mTransaction->GetMetadataForIndexId(*objectStoreMetadata,
this->mIndexId);
if (indexMetadata) {
MOZ_ASSERT(indexMetadata == *this->mIndexMetadata);
} else {
MOZ_ASSERT((*this->mIndexMetadata)->mDeleted);
}
}
}
}
#endif
if (NS_AUUF_OR_WARN_IF((*this->mObjectStoreMetadata)->mDeleted)) {
return false;
}
if constexpr (IsIndexCursor) {
if (NS_AUUF_OR_WARN_IF(this->mIndexMetadata &&
(*this->mIndexMetadata)->mDeleted)) {
return false;
}
}
const Key& sortKey = aPosition.GetSortKey(this->IsLocaleAware());
switch (aParams.type()) {
case CursorRequestParams::TContinueParams: {
const Key& key = aParams.get_ContinueParams().key();
if (!key.IsUnset()) {
switch (mDirection) {
case IDBCursorDirection::Next:
case IDBCursorDirection::Nextunique:
if (NS_AUUF_OR_WARN_IF(key <= sortKey)) {
return false;
}
break;
case IDBCursorDirection::Prev:
case IDBCursorDirection::Prevunique:
if (NS_AUUF_OR_WARN_IF(key >= sortKey)) {
return false;
}
break;
default:
MOZ_CRASH("Should never get here!");
}
}
break;
}
case CursorRequestParams::TContinuePrimaryKeyParams: {
if constexpr (IsIndexCursor) {
const Key& key = aParams.get_ContinuePrimaryKeyParams().key();
const Key& primaryKey =
aParams.get_ContinuePrimaryKeyParams().primaryKey();
MOZ_ASSERT(!key.IsUnset());
MOZ_ASSERT(!primaryKey.IsUnset());
switch (mDirection) {
case IDBCursorDirection::Next:
if (NS_AUUF_OR_WARN_IF(key < sortKey ||
(key == sortKey &&
primaryKey <= aPosition.mObjectStoreKey))) {
return false;
}
break;
case IDBCursorDirection::Prev:
if (NS_AUUF_OR_WARN_IF(key > sortKey ||
(key == sortKey &&
primaryKey >= aPosition.mObjectStoreKey))) {
return false;
}
break;
default:
MOZ_CRASH("Should never get here!");
}
}
break;
}
case CursorRequestParams::TAdvanceParams:
if (NS_AUUF_OR_WARN_IF(!aParams.get_AdvanceParams().count())) {
return false;
}
break;
default:
MOZ_CRASH("Should never get here!");
}
return true;
}
template <IDBCursorType CursorType>
bool Cursor<CursorType>::Start(const int64_t aRequestId,
const OpenCursorParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() == ToOpenCursorParamsType(CursorType));
MOZ_ASSERT(this->mObjectStoreMetadata);
if (NS_AUUF_OR_WARN_IF(mCurrentlyRunningOp)) {
return false;
}
const Maybe<SerializedKeyRange>& optionalKeyRange =
GetCommonOpenCursorParams(aParams).optionalKeyRange();
const RefPtr<OpenOp> openOp = new OpenOp(this, aRequestId, optionalKeyRange);
if (NS_WARN_IF(!openOp->Init(*mTransaction))) {
openOp->Cleanup();
return false;
}
openOp->DispatchToConnectionPool();
mCurrentlyRunningOp = openOp;
return true;
}
void ValueCursorBase::ProcessFiles(CursorResponse& aResponse,
const FilesArray& aFiles) {
MOZ_ASSERT_IF(
aResponse.type() == CursorResponse::Tnsresult ||
aResponse.type() == CursorResponse::Tvoid_t ||
aResponse.type() ==
CursorResponse::TArrayOfObjectStoreKeyCursorResponse ||
aResponse.type() == CursorResponse::TArrayOfIndexKeyCursorResponse,
aFiles.IsEmpty());
for (size_t i = 0; i < aFiles.Length(); ++i) {
const auto& files = aFiles[i];
if (!files.IsEmpty()) {
// TODO: Replace this assertion by one that checks if the response type
// matches the cursor type, at a more generic location.
MOZ_ASSERT(aResponse.type() ==
CursorResponse::TArrayOfObjectStoreCursorResponse ||
aResponse.type() ==
CursorResponse::TArrayOfIndexCursorResponse);
SerializedStructuredCloneReadInfo* serializedInfo = nullptr;
switch (aResponse.type()) {
case CursorResponse::TArrayOfObjectStoreCursorResponse: {
auto& responses = aResponse.get_ArrayOfObjectStoreCursorResponse();
MOZ_ASSERT(i < responses.Length());
serializedInfo = &responses[i].cloneInfo();
break;
}
case CursorResponse::TArrayOfIndexCursorResponse: {
auto& responses = aResponse.get_ArrayOfIndexCursorResponse();
MOZ_ASSERT(i < responses.Length());
serializedInfo = &responses[i].cloneInfo();
break;
}
default:
MOZ_CRASH("Should never get here!");
}
MOZ_ASSERT(serializedInfo);
MOZ_ASSERT(serializedInfo->files().IsEmpty());
MOZ_ASSERT(this->mDatabase);
QM_TRY_UNWRAP(serializedInfo->files(),
SerializeStructuredCloneFiles(this->mDatabase, files,
/* aForPreprocess */ false),
QM_VOID, [&aResponse](const nsresult result) {
aResponse = ClampResultCode(result);
});
}
}
}
template <IDBCursorType CursorType>
void Cursor<CursorType>::SendResponseInternal(
CursorResponse& aResponse, const FilesArrayT<CursorType>& aFiles) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aResponse.type() != CursorResponse::T__None);
MOZ_ASSERT_IF(aResponse.type() == CursorResponse::Tnsresult,
NS_FAILED(aResponse.get_nsresult()));
MOZ_ASSERT_IF(aResponse.type() == CursorResponse::Tnsresult,
NS_ERROR_GET_MODULE(aResponse.get_nsresult()) ==
NS_ERROR_MODULE_DOM_INDEXEDDB);
MOZ_ASSERT(this->mObjectStoreMetadata);
MOZ_ASSERT(mCurrentlyRunningOp);
KeyValueBase::ProcessFiles(aResponse, aFiles);
// Work around the deleted function by casting to the base class.
QM_WARNONLY_TRY(OkIf(
static_cast<PBackgroundIDBCursorParent*>(this)->SendResponse(aResponse)));
mCurrentlyRunningOp = nullptr;
}
template <IDBCursorType CursorType>
void Cursor<CursorType>::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnBackgroundThread();
if (mCurrentlyRunningOp) {
mCurrentlyRunningOp->NoteActorDestroyed();
}
if constexpr (IsValueCursor) {
this->mBackgroundParent.destroy();
}
this->mObjectStoreMetadata.destroy();
if constexpr (IsIndexCursor) {
this->mIndexMetadata.destroy();
}
}
template <IDBCursorType CursorType>
mozilla::ipc::IPCResult Cursor<CursorType>::RecvDeleteMe() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(this->mObjectStoreMetadata);
if (NS_WARN_IF(mCurrentlyRunningOp)) {
return IPC_FAIL(
this,
"Attempt to delete a cursor with a non-null mCurrentlyRunningOp!");
}
QM_WARNONLY_TRY(OkIf(PBackgroundIDBCursorParent::Send__delete__(this)));
return IPC_OK();
}
template <IDBCursorType CursorType>
mozilla::ipc::IPCResult Cursor<CursorType>::RecvContinue(
const int64_t& aRequestId, const CursorRequestParams& aParams,
const Key& aCurrentKey, const Key& aCurrentObjectStoreKey) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() != CursorRequestParams::T__None);
MOZ_ASSERT(this->mObjectStoreMetadata);
if constexpr (IsIndexCursor) {
MOZ_ASSERT(this->mIndexMetadata);
}
const bool trustParams =
#ifdef DEBUG
// Always verify parameters in DEBUG builds!
false
#else
this->mIsSameProcessActor
#endif
;
MOZ_ASSERT(!aCurrentKey.IsUnset());
QM_TRY_UNWRAP(
auto position,
([&]() -> Result<CursorPosition<CursorType>, mozilla::ipc::IPCResult> {
if constexpr (IsIndexCursor) {
auto localeAwarePosition = Key{};
if (this->IsLocaleAware()) {
QM_TRY_UNWRAP(
localeAwarePosition,
aCurrentKey.ToLocaleAwareKey(this->mLocale),
Err(IPC_FAIL(this, "aCurrentKey.ToLocaleAwareKey failed!")));
}
return CursorPosition<CursorType>{aCurrentKey, localeAwarePosition,
aCurrentObjectStoreKey};
} else {
return CursorPosition<CursorType>{aCurrentKey};
}
}()));
if (!trustParams && !VerifyRequestParams(aParams, position)) {
return IPC_FAIL(this, "VerifyRequestParams failed!");
}
if (NS_WARN_IF(mCurrentlyRunningOp)) {
return IPC_FAIL(this, "Cursor is CurrentlyRunningOp!");
}
if (NS_WARN_IF(mTransaction->mCommitOrAbortReceived)) {
return IPC_FAIL(this, "Transaction is already committed/aborted!");
}
const RefPtr<ContinueOp> continueOp =
new ContinueOp(this, aRequestId, aParams, std::move(position));
if (NS_WARN_IF(!continueOp->Init(*mTransaction))) {
continueOp->Cleanup();
return IPC_FAIL(this, "ContinueOp initialization failed!");
}
continueOp->DispatchToConnectionPool();
mCurrentlyRunningOp = continueOp;
return IPC_OK();
}
/*******************************************************************************
* DatabaseFileManager
******************************************************************************/
DatabaseFileManager::MutexType DatabaseFileManager::sMutex;
DatabaseFileManager::DatabaseFileManager(
PersistenceType aPersistenceType,
const quota::OriginMetadata& aOriginMetadata,
const nsAString& aDatabaseName, const nsCString& aDatabaseID,
const nsAString& aDatabaseFilePath, bool aEnforcingQuota,
bool aIsInPrivateBrowsingMode)
: mPersistenceType(aPersistenceType),
mOriginMetadata(aOriginMetadata),
mDatabaseName(aDatabaseName),
mDatabaseID(aDatabaseID),
mDatabaseFilePath(aDatabaseFilePath),
mCipherKeyManager(
aIsInPrivateBrowsingMode
? new IndexedDBCipherKeyManager("IndexedDBCipherKeyManager")
: nullptr),
mDatabaseVersion(0),
mEnforcingQuota(aEnforcingQuota),
mIsInPrivateBrowsingMode(aIsInPrivateBrowsingMode) {}
uint64_t DatabaseFileManager::DatabaseVersion() const {
AssertIsOnIOThread();
return mDatabaseVersion;
}
void DatabaseFileManager::UpdateDatabaseVersion(uint64_t aDatabaseVersion) {
AssertIsOnIOThread();
mDatabaseVersion = aDatabaseVersion;
}
nsresult DatabaseFileManager::Init(nsIFile* aDirectory,
const uint64_t aDatabaseVersion,
mozIStorageConnection& aConnection) {
AssertIsOnIOThread();
MOZ_ASSERT(aDirectory);
{
QM_TRY_INSPECT(const bool& existsAsDirectory,
ExistsAsDirectory(*aDirectory));
if (!existsAsDirectory) {
QM_TRY(MOZ_TO_RESULT(aDirectory->Create(nsIFile::DIRECTORY_TYPE, 0755)));
}
QM_TRY_UNWRAP(auto path, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, aDirectory, GetPath));
mDirectoryPath.init(std::move(path));
}
QM_TRY_INSPECT(const auto& journalDirectory,
CloneFileAndAppend(*aDirectory, kJournalDirectoryName));
// We don't care if it doesn't exist at all, but if it does exist, make sure
// it's a directory.
QM_TRY_INSPECT(const bool& existsAsDirectory,
ExistsAsDirectory(*journalDirectory));
Unused << existsAsDirectory;
{
QM_TRY_UNWRAP(auto path, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, journalDirectory, GetPath));
mJournalDirectoryPath.init(std::move(path));
}
mDatabaseVersion = aDatabaseVersion;
QM_TRY_INSPECT(const auto& stmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>, aConnection,
CreateStatement, "SELECT id, refcount FROM file"_ns));
QM_TRY(
CollectWhileHasResult(*stmt, [this](auto& stmt) -> Result<Ok, nsresult> {
QM_TRY_INSPECT(const int64_t& id,
MOZ_TO_RESULT_INVOKE_MEMBER(stmt, GetInt64, 0));
QM_TRY_INSPECT(const int32_t& dbRefCnt,
MOZ_TO_RESULT_INVOKE_MEMBER(stmt, GetInt32, 1));
// We put a raw pointer into the hash table, so the memory refcount will
// be 0, but the dbRefCnt is non-zero, which will keep the
// DatabaseFileInfo object alive.
MOZ_ASSERT(dbRefCnt > 0);
DebugOnly ok = static_cast<bool>(CreateFileInfo(Some(id), dbRefCnt));
MOZ_ASSERT(ok);
return Ok{};
}));
mInitialized.Flip();
return NS_OK;
}
nsCOMPtr<nsIFile> DatabaseFileManager::GetDirectory() {
if (!this->AssertValid()) {
return nullptr;
}
return GetFileForPath(*mDirectoryPath);
}
nsCOMPtr<nsIFile> DatabaseFileManager::GetCheckedDirectory() {
auto directory = GetDirectory();
if (NS_WARN_IF(!directory)) {
return nullptr;
}
DebugOnly<bool> exists;
MOZ_ASSERT(NS_SUCCEEDED(directory->Exists(&exists)));
MOZ_ASSERT(exists);
DebugOnly<bool> isDirectory;
MOZ_ASSERT(NS_SUCCEEDED(directory->IsDirectory(&isDirectory)));
MOZ_ASSERT(isDirectory);
return directory;
}
nsCOMPtr<nsIFile> DatabaseFileManager::GetJournalDirectory() {
if (!this->AssertValid()) {
return nullptr;
}
return GetFileForPath(*mJournalDirectoryPath);
}
nsCOMPtr<nsIFile> DatabaseFileManager::EnsureJournalDirectory() {
// This can happen on the IO or on a transaction thread.
MOZ_ASSERT(!NS_IsMainThread());
auto journalDirectory = GetFileForPath(*mJournalDirectoryPath);
QM_TRY(OkIf(journalDirectory), nullptr);
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(journalDirectory, Exists),
nullptr);
if (exists) {
QM_TRY_INSPECT(const bool& isDirectory,
MOZ_TO_RESULT_INVOKE_MEMBER(journalDirectory, IsDirectory),
nullptr);
QM_TRY(OkIf(isDirectory), nullptr);
} else {
QM_TRY(
MOZ_TO_RESULT(journalDirectory->Create(nsIFile::DIRECTORY_TYPE, 0755)),
nullptr);
}
return journalDirectory;
}
// static
nsCOMPtr<nsIFile> DatabaseFileManager::GetFileForId(nsIFile* aDirectory,
int64_t aId) {
MOZ_ASSERT(aDirectory);
MOZ_ASSERT(aId > 0);
QM_TRY_RETURN(CloneFileAndAppend(*aDirectory, IntToString(aId)), nullptr);
}
// static
nsCOMPtr<nsIFile> DatabaseFileManager::GetCheckedFileForId(nsIFile* aDirectory,
int64_t aId) {
auto file = GetFileForId(aDirectory, aId);
if (NS_WARN_IF(!file)) {
return nullptr;
}
DebugOnly<bool> exists;
MOZ_ASSERT(NS_SUCCEEDED(file->Exists(&exists)));
MOZ_ASSERT(exists);
DebugOnly<bool> isFile;
MOZ_ASSERT(NS_SUCCEEDED(file->IsFile(&isFile)));
MOZ_ASSERT(isFile);
return file;
}
// static
nsresult DatabaseFileManager::InitDirectory(nsIFile& aDirectory,
nsIFile& aDatabaseFile,
const nsACString& aOrigin,
uint32_t aTelemetryId) {
AssertIsOnIOThread();
{
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(aDirectory, Exists));
if (!exists) {
return NS_OK;
}
QM_TRY_INSPECT(const bool& isDirectory,
MOZ_TO_RESULT_INVOKE_MEMBER(aDirectory, IsDirectory));
QM_TRY(OkIf(isDirectory), NS_ERROR_FAILURE);
}
QM_TRY_INSPECT(const auto& journalDirectory,
CloneFileAndAppend(aDirectory, kJournalDirectoryName));
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(journalDirectory, Exists));
if (exists) {
QM_TRY_INSPECT(const bool& isDirectory,
MOZ_TO_RESULT_INVOKE_MEMBER(journalDirectory, IsDirectory));
QM_TRY(OkIf(isDirectory), NS_ERROR_FAILURE);
bool hasJournals = false;
QM_TRY(CollectEachFile(
*journalDirectory,
[&hasJournals](const nsCOMPtr<nsIFile>& file) -> Result<Ok, nsresult> {
QM_TRY_INSPECT(
const auto& leafName,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsString, file, GetLeafName));
nsresult rv;
leafName.ToInteger64(&rv);
if (NS_SUCCEEDED(rv)) {
hasJournals = true;
} else {
UNKNOWN_FILE_WARNING(leafName);
}
return Ok{};
}));
if (hasJournals) {
QM_TRY_UNWRAP(const NotNull<nsCOMPtr<mozIStorageConnection>> connection,
CreateStorageConnection(
aDatabaseFile, aDirectory, VoidString(), aOrigin,
/* aDirectoryLockId */ -1, aTelemetryId, Nothing{}));
mozStorageTransaction transaction(connection.get(), false);
QM_TRY(MOZ_TO_RESULT(transaction.Start()))
QM_TRY(MOZ_TO_RESULT(connection->ExecuteSimpleSQL(
"CREATE VIRTUAL TABLE fs USING filesystem;"_ns)));
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(
const auto& stmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>, *connection, CreateStatement,
"SELECT name, (name IN (SELECT id FROM file)) FROM fs WHERE path = :path"_ns));
QM_TRY_INSPECT(const auto& path,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, journalDirectory, GetPath));
QM_TRY(MOZ_TO_RESULT(stmt->BindStringByIndex(0, path)));
QM_TRY(CollectWhileHasResult(
*stmt,
[&aDirectory, &journalDirectory](auto& stmt) -> Result<Ok, nsresult> {
nsString name;
QM_TRY(MOZ_TO_RESULT(stmt.GetString(0, name)));
nsresult rv;
name.ToInteger64(&rv);
if (NS_FAILED(rv)) {
return Ok{};
}
int32_t flag = stmt.AsInt32(1);
if (!flag) {
QM_TRY_INSPECT(const auto& file,
CloneFileAndAppend(aDirectory, name));
if (NS_FAILED(file->Remove(false))) {
NS_WARNING("Failed to remove orphaned file!");
}
}
QM_TRY_INSPECT(const auto& journalFile,
CloneFileAndAppend(*journalDirectory, name));
if (NS_FAILED(journalFile->Remove(false))) {
NS_WARNING("Failed to remove journal file!");
}
return Ok{};
}));
QM_TRY(MOZ_TO_RESULT(connection->ExecuteSimpleSQL("DROP TABLE fs;"_ns)));
QM_TRY(MOZ_TO_RESULT(transaction.Commit()));
}
}
return NS_OK;
}
// static
Result<FileUsageType, nsresult> DatabaseFileManager::GetUsage(
nsIFile* aDirectory) {
AssertIsOnIOThread();
MOZ_ASSERT(aDirectory);
FileUsageType usage;
QM_TRY(TraverseFiles(
*aDirectory,
// KnownDirEntryOp
[&usage](nsIFile& file, const bool isDirectory) -> Result<Ok, nsresult> {
if (isDirectory) {
return Ok{};
}
// Usually we only use QM_OR_ELSE_LOG_VERBOSE(_IF) with Remove and
// NS_ERROR_FILE_NOT_FOUND check, but the file was found by a directory
// traversal and ToInteger on the name succeeded, so it should be our
// file and if the file disappears, the use of QM_OR_ELSE_WARN_IF is ok
// here.
QM_TRY_INSPECT(const auto& thisUsage,
QM_OR_ELSE_WARN_IF(
// Expression.
MOZ_TO_RESULT_INVOKE_MEMBER(file, GetFileSize)
.map([](const int64_t fileSize) {
return FileUsageType(Some(uint64_t(fileSize)));
}),
// Predicate.
([](const nsresult rv) {
return rv == NS_ERROR_FILE_NOT_FOUND;
}),
// Fallback. If the file does no longer exist, treat
// it as 0-sized.
ErrToDefaultOk<FileUsageType>));
usage += thisUsage;
return Ok{};
},
// UnknownDirEntryOp
[](nsIFile&, const bool) -> Result<Ok, nsresult> { return Ok{}; }));
return usage;
}
nsresult DatabaseFileManager::SyncDeleteFile(const int64_t aId) {
MOZ_ASSERT(!ContainsFileInfo(aId));
if (!this->AssertValid()) {
return NS_ERROR_UNEXPECTED;
}
const auto directory = GetDirectory();
QM_TRY(OkIf(directory), NS_ERROR_FAILURE);
const auto journalDirectory = GetJournalDirectory();
QM_TRY(OkIf(journalDirectory), NS_ERROR_FAILURE);
const nsCOMPtr<nsIFile> file = GetFileForId(directory, aId);
QM_TRY(OkIf(file), NS_ERROR_FAILURE);
const nsCOMPtr<nsIFile> journalFile = GetFileForId(journalDirectory, aId);
QM_TRY(OkIf(journalFile), NS_ERROR_FAILURE);
return SyncDeleteFile(*file, *journalFile);
}
nsresult DatabaseFileManager::SyncDeleteFile(nsIFile& aFile,
nsIFile& aJournalFile) const {
QuotaManager* const quotaManager =
EnforcingQuota() ? QuotaManager::Get() : nullptr;
MOZ_ASSERT_IF(EnforcingQuota(), quotaManager);
QM_TRY(MOZ_TO_RESULT(DeleteFile(aFile, quotaManager, Type(), OriginMetadata(),
Idempotency::No)));
QM_TRY(MOZ_TO_RESULT(aJournalFile.Remove(false)));
return NS_OK;
}
nsresult DatabaseFileManager::Invalidate() {
if (mCipherKeyManager) {
mCipherKeyManager->Invalidate();
}
QM_TRY(MOZ_TO_RESULT(FileInfoManager::Invalidate()));
return NS_OK;
}
/*******************************************************************************
* QuotaClient
******************************************************************************/
QuotaClient* QuotaClient::sInstance = nullptr;
QuotaClient::QuotaClient() : mDeleteTimer(NS_NewTimer()) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!sInstance, "We expect this to be a singleton!");
MOZ_ASSERT(!gTelemetryIdMutex);
// Always create this so that later access to gTelemetryIdHashtable can be
// properly synchronized.
gTelemetryIdMutex = new Mutex("IndexedDB gTelemetryIdMutex");
gStorageDatabaseNameMutex = new Mutex("IndexedDB gStorageDatabaseNameMutex");
sInstance = this;
}
QuotaClient::~QuotaClient() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(sInstance == this, "We expect this to be a singleton!");
MOZ_ASSERT(gTelemetryIdMutex);
MOZ_ASSERT(!mMaintenanceThreadPool);
// No one else should be able to touch gTelemetryIdHashtable now that the
// QuotaClient has gone away.
gTelemetryIdHashtable = nullptr;
gTelemetryIdMutex = nullptr;
gStorageDatabaseNameHashtable = nullptr;
gStorageDatabaseNameMutex = nullptr;
sInstance = nullptr;
}
nsresult QuotaClient::AsyncDeleteFile(DatabaseFileManager* aFileManager,
int64_t aFileId) {
AssertIsOnBackgroundThread();
if (IsShuttingDownOnBackgroundThread()) {
// Whoops! We want to delete an IndexedDB disk-backed File but it's too late
// to actually delete the file! This means we're going to "leak" the file
// and leave it around when we shouldn't! (The file will stay around until
// next storage initialization is triggered when the app is started again).
// Fixing this is tracked by bug 1539377.
return NS_OK;
}
MOZ_ASSERT(mDeleteTimer);
MOZ_ALWAYS_SUCCEEDS(mDeleteTimer->Cancel());
QM_TRY(MOZ_TO_RESULT(mDeleteTimer->InitWithNamedFuncCallback(
DeleteTimerCallback, this, kDeleteTimeoutMs, nsITimer::TYPE_ONE_SHOT,
"dom::indexeddb::QuotaClient::AsyncDeleteFile")));
mPendingDeleteInfos.GetOrInsertNew(aFileManager)->AppendElement(aFileId);
return NS_OK;
}
nsresult QuotaClient::FlushPendingFileDeletions() {
AssertIsOnBackgroundThread();
QM_TRY(MOZ_TO_RESULT(mDeleteTimer->Cancel()));
DeleteTimerCallback(mDeleteTimer, this);
return NS_OK;
}
RefPtr<BoolPromise> QuotaClient::DoMaintenance() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!IsShuttingDownOnBackgroundThread());
if (!mBackgroundThread) {
mBackgroundThread = GetCurrentSerialEventTarget();
}
auto maintenance = MakeRefPtr<Maintenance>(this);
mMaintenanceQueue.AppendElement(maintenance);
ProcessMaintenanceQueue();
return maintenance->OnResults();
}
nsThreadPool* QuotaClient::GetOrCreateThreadPool() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!IsShuttingDownOnBackgroundThread());
if (!mMaintenanceThreadPool) {
RefPtr<nsThreadPool> threadPool = new nsThreadPool();
// PR_GetNumberOfProcessors() can return -1 on error, so make sure we
// don't set some huge number here. We add 2 in case some threads block on
// the disk I/O.
const uint32_t threadCount =
std::max(int32_t(PR_GetNumberOfProcessors()), int32_t(1)) + 2;
MOZ_ALWAYS_SUCCEEDS(threadPool->SetThreadLimit(threadCount));
// Don't keep more than one idle thread.
MOZ_ALWAYS_SUCCEEDS(threadPool->SetIdleThreadLimit(1));
// Don't keep idle threads alive very long.
MOZ_ALWAYS_SUCCEEDS(
threadPool->SetIdleThreadMaximumTimeout(5 * PR_MSEC_PER_SEC));
MOZ_ALWAYS_SUCCEEDS(threadPool->SetName("IndexedDB Mnt"_ns));
mMaintenanceThreadPool = std::move(threadPool);
}
return mMaintenanceThreadPool;
}
mozilla::dom::quota::Client::Type QuotaClient::GetType() {
return QuotaClient::IDB;
}
nsresult QuotaClient::UpgradeStorageFrom1_0To2_0(nsIFile* aDirectory) {
AssertIsOnIOThread();
MOZ_ASSERT(aDirectory);
QM_TRY_INSPECT(const auto& databaseFilenamesInfo,
GetDatabaseFilenames(*aDirectory,
/* aCanceled */ AtomicBool{false}));
// FIXME: use structural binding once we support c++20.
const auto& subdirsToProcess = databaseFilenamesInfo.subdirsToProcess;
const auto& databaseFilenames = databaseFilenamesInfo.databaseFilenames;
QM_TRY(CollectEachInRange(
subdirsToProcess,
[&databaseFilenames = databaseFilenames,
aDirectory](const nsAString& subdirName) -> Result<Ok, nsresult> {
// If the directory has the correct suffix then it should exist in
// databaseFilenames.
nsDependentSubstring subdirNameBase;
if (GetFilenameBase(subdirName, kFileManagerDirectoryNameSuffix,
subdirNameBase)) {
QM_WARNONLY_TRY(OkIf(databaseFilenames.Contains(subdirNameBase)));
return Ok{};
}
// The directory didn't have the right suffix but we might need to
// rename it. Check to see if we have a database that references this
// directory.
QM_TRY_INSPECT(
const auto& subdirNameWithSuffix,
([&databaseFilenames,
&subdirName]() -> Result<nsAutoString, NotOk> {
if (databaseFilenames.Contains(subdirName)) {
return nsAutoString{subdirName +
kFileManagerDirectoryNameSuffix};
}
// Windows doesn't allow a directory to end with a dot ('.'), so
// we have to check that possibility here too. We do this on all
// platforms, because the origin directory may have been created
// on Windows and now accessed on different OS.
const nsAutoString subdirNameWithDot = subdirName + u"."_ns;
QM_TRY(OkIf(databaseFilenames.Contains(subdirNameWithDot)),
Err(NotOk{}));
return nsAutoString{subdirNameWithDot +
kFileManagerDirectoryNameSuffix};
}()),
Ok{});
// We do have a database that uses this subdir so we should rename it
// now.
QM_TRY_INSPECT(const auto& subdir,
CloneFileAndAppend(*aDirectory, subdirName));
DebugOnly<bool> isDirectory;
MOZ_ASSERT(NS_SUCCEEDED(subdir->IsDirectory(&isDirectory)));
MOZ_ASSERT(isDirectory);
// Check if the subdir with suffix already exists before renaming.
QM_TRY_INSPECT(const auto& subdirWithSuffix,
CloneFileAndAppend(*aDirectory, subdirNameWithSuffix));
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(subdirWithSuffix, Exists));
if (exists) {
IDB_WARNING("Deleting old %s files directory!",
NS_ConvertUTF16toUTF8(subdirName).get());
QM_TRY(MOZ_TO_RESULT(subdir->Remove(/* aRecursive */ true)));
return Ok{};
}
// Finally, rename the subdir.
QM_TRY(MOZ_TO_RESULT(subdir->RenameTo(nullptr, subdirNameWithSuffix)));
return Ok{};
}));
return NS_OK;
}
nsresult QuotaClient::UpgradeStorageFrom2_1To2_2(nsIFile* aDirectory) {
AssertIsOnIOThread();
MOZ_ASSERT(aDirectory);
QM_TRY(CollectEachFile(
*aDirectory, [](const nsCOMPtr<nsIFile>& file) -> Result<Ok, nsresult> {
QM_TRY_INSPECT(const auto& dirEntryKind, GetDirEntryKind(*file));
switch (dirEntryKind) {
case nsIFileKind::ExistsAsDirectory:
break;
case nsIFileKind::ExistsAsFile: {
QM_TRY_INSPECT(
const auto& leafName,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsString, file, GetLeafName));
// It's reported that files ending with ".tmp" somehow live in the
// indexedDB directories in Bug 1503883. Such files shouldn't exist
// in the indexedDB directory so remove them in this upgrade.
if (StringEndsWith(leafName, u".tmp"_ns)) {
IDB_WARNING("Deleting unknown temporary file!");
QM_TRY(MOZ_TO_RESULT(file->Remove(false)));
}
break;
}
case nsIFileKind::DoesNotExist:
// Ignore files that got removed externally while iterating.
break;
}
return Ok{};
}));
return NS_OK;
}
Result<UsageInfo, nsresult> QuotaClient::InitOrigin(
PersistenceType aPersistenceType, const OriginMetadata& aOriginMetadata,
const AtomicBool& aCanceled) {
AssertIsOnIOThread();
QM_TRY_RETURN(MOZ_TO_RESULT_INVOKE_MEMBER(this, GetUsageForOriginInternal,
aPersistenceType, aOriginMetadata,
aCanceled,
/* aInitializing*/ true));
}
nsresult QuotaClient::InitOriginWithoutTracking(
PersistenceType aPersistenceType, const OriginMetadata& aOriginMetadata,
const AtomicBool& aCanceled) {
AssertIsOnIOThread();
return GetUsageForOriginInternal(aPersistenceType, aOriginMetadata, aCanceled,
/* aInitializing*/ true, nullptr);
}
Result<UsageInfo, nsresult> QuotaClient::GetUsageForOrigin(
PersistenceType aPersistenceType, const OriginMetadata& aOriginMetadata,
const AtomicBool& aCanceled) {
AssertIsOnIOThread();
QM_TRY_RETURN(MOZ_TO_RESULT_INVOKE_MEMBER(this, GetUsageForOriginInternal,
aPersistenceType, aOriginMetadata,
aCanceled,
/* aInitializing*/ false));
}
nsresult QuotaClient::GetUsageForOriginInternal(
PersistenceType aPersistenceType, const OriginMetadata& aOriginMetadata,
const AtomicBool& aCanceled, const bool aInitializing,
UsageInfo* aUsageInfo) {
AssertIsOnIOThread();
MOZ_ASSERT(aOriginMetadata.mPersistenceType == aPersistenceType);
QM_TRY_INSPECT(const nsCOMPtr<nsIFile>& directory,
GetDirectory(aOriginMetadata));
// We need to see if there are any files in the directory already. If they
// are database files then we need to cleanup stored files (if it's needed)
// and also get the usage.
// XXX Can we avoid unwrapping into non-const variables here? (Only
// databaseFilenames is currently modified below)
QM_TRY_UNWRAP((auto [subdirsToProcess, databaseFilenames, obsoleteFilenames]),
GetDatabaseFilenames<ObsoleteFilenamesHandling::Include>(
*directory, aCanceled));
if (aInitializing) {
QM_TRY(CollectEachInRange(
subdirsToProcess,
[&directory, &obsoleteFilenames = obsoleteFilenames,
&databaseFilenames = databaseFilenames, aPersistenceType,
&aOriginMetadata](
const nsAString& subdirName) -> Result<Ok, nsresult> {
// The directory must have the correct suffix.
nsDependentSubstring subdirNameBase;
QM_TRY(QM_OR_ELSE_WARN(
// Expression.
([&subdirName, &subdirNameBase] {
QM_TRY_RETURN(OkIf(GetFilenameBase(
subdirName, kFileManagerDirectoryNameSuffix,
subdirNameBase)));
}()),
// Fallback.
([&directory,
&subdirName](const NotOk) -> Result<Ok, nsresult> {
// If there is an unexpected directory in the idb
// directory, trying to delete at first instead of
// breaking the whole initialization.
QM_TRY(MOZ_TO_RESULT(
DeleteFilesNoQuota(directory, subdirName)),
Err(NS_ERROR_UNEXPECTED));
return Ok{};
})),
Ok{});
if (obsoleteFilenames.Contains(subdirNameBase)) {
// If this fails, it probably means we are in a serious situation.
// e.g. Filesystem corruption. Will handle this in bug 1521541.
QM_TRY(MOZ_TO_RESULT(RemoveDatabaseFilesAndDirectory(
*directory, subdirNameBase, /* aQuotaManager */ nullptr,
aPersistenceType, aOriginMetadata,
/* aDatabaseName */ u""_ns)),
Err(NS_ERROR_UNEXPECTED));
databaseFilenames.Remove(subdirNameBase);
return Ok{};
}
// The directory base must exist in databaseFilenames.
// If there is an unexpected directory in the idb directory, trying to
// delete at first instead of breaking the whole initialization.
// XXX This is still somewhat quirky. It would be nice to make it
// clear that the warning handler is infallible, which would also
// remove the need for the error type conversion.
QM_WARNONLY_TRY(QM_OR_ELSE_WARN(
// Expression.
OkIf(databaseFilenames.Contains(subdirNameBase))
.mapErr([](const NotOk) { return NS_ERROR_FAILURE; }),
// Fallback.
([&directory,
&subdirName](const nsresult) -> Result<Ok, nsresult> {
// XXX It seems if we really got here, we can fail the
// MOZ_ASSERT(!quotaManager->IsTemporaryStorageInitializedInternal());
// assertion in DeleteFilesNoQuota.
QM_TRY(MOZ_TO_RESULT(DeleteFilesNoQuota(directory, subdirName)),
Err(NS_ERROR_UNEXPECTED));
return Ok{};
})));
return Ok{};
}));
}
for (const auto& databaseFilename : databaseFilenames) {
if (aCanceled) {
break;
}
QM_TRY_INSPECT(
const auto& fmDirectory,
CloneFileAndAppend(*directory,
databaseFilename + kFileManagerDirectoryNameSuffix));
QM_TRY_INSPECT(
const auto& databaseFile,
CloneFileAndAppend(*directory, databaseFilename + kSQLiteSuffix));
if (aInitializing) {
QM_TRY(MOZ_TO_RESULT(DatabaseFileManager::InitDirectory(
*fmDirectory, *databaseFile, aOriginMetadata.mOrigin,
TelemetryIdForFile(databaseFile))));
}
if (aUsageInfo) {
{
QM_TRY_INSPECT(const int64_t& fileSize,
MOZ_TO_RESULT_INVOKE_MEMBER(databaseFile, GetFileSize));
MOZ_ASSERT(fileSize >= 0);
*aUsageInfo += DatabaseUsageType(Some(uint64_t(fileSize)));
}
{
QM_TRY_INSPECT(const auto& walFile,
CloneFileAndAppend(*directory,
databaseFilename + kSQLiteWALSuffix));
// QM_OR_ELSE_WARN_IF is not used here since we just want to log
// NS_ERROR_FILE_NOT_FOUND result and not spam the reports (the -wal
// file doesn't have to exist).
QM_TRY_INSPECT(const int64_t& walFileSize,
QM_OR_ELSE_LOG_VERBOSE_IF(
// Expression.
MOZ_TO_RESULT_INVOKE_MEMBER(walFile, GetFileSize),
// Predicate.
([](const nsresult rv) {
return rv == NS_ERROR_FILE_NOT_FOUND;
}),
// Fallback.
(ErrToOk<0, int64_t>)));
MOZ_ASSERT(walFileSize >= 0);
*aUsageInfo += DatabaseUsageType(Some(uint64_t(walFileSize)));
}
{
QM_TRY_INSPECT(const auto& fileUsage,
DatabaseFileManager::GetUsage(fmDirectory));
*aUsageInfo += fileUsage;
}
}
}
return NS_OK;
}
void QuotaClient::OnOriginClearCompleted(
const OriginMetadata& aOriginMetadata) {
AssertIsOnIOThread();
if (IndexedDatabaseManager* mgr = IndexedDatabaseManager::Get()) {
mgr->InvalidateFileManagers(aOriginMetadata.mPersistenceType,
aOriginMetadata.mOrigin);
}
}
void QuotaClient::OnRepositoryClearCompleted(PersistenceType aPersistenceType) {
AssertIsOnIOThread();
if (IndexedDatabaseManager* mgr = IndexedDatabaseManager::Get()) {
mgr->InvalidateFileManagers(aPersistenceType);
}
}
void QuotaClient::ReleaseIOThreadObjects() {
AssertIsOnIOThread();
if (IndexedDatabaseManager* mgr = IndexedDatabaseManager::Get()) {
mgr->InvalidateAllFileManagers();
}
}
void QuotaClient::AbortOperationsForLocks(
const DirectoryLockIdTable& aDirectoryLockIds) {
AssertIsOnBackgroundThread();
InvalidateLiveDatabasesMatching([&aDirectoryLockIds](const auto& database) {
// If the database is registered in gLiveDatabaseHashtable then it must have
// a directory lock.
return IsLockForObjectContainedInLockTable(database, aDirectoryLockIds);
});
}
void QuotaClient::AbortOperationsForProcess(ContentParentId aContentParentId) {
AssertIsOnBackgroundThread();
InvalidateLiveDatabasesMatching([&aContentParentId](const auto& database) {
return database.IsOwnedByProcess(aContentParentId);
});
}
void QuotaClient::AbortAllOperations() {
AssertIsOnBackgroundThread();
AbortAllMaintenances();
InvalidateLiveDatabasesMatching([](const auto&) { return true; });
}
void QuotaClient::StartIdleMaintenance() {
AssertIsOnBackgroundThread();
if (IsShuttingDownOnBackgroundThread()) {
MOZ_ASSERT(false, "!IsShuttingDownOnBackgroundThread()");
return;
}
DoMaintenance();
}
void QuotaClient::StopIdleMaintenance() {
AssertIsOnBackgroundThread();
AbortAllMaintenances();
}
void QuotaClient::InitiateShutdown() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(IsShuttingDownOnBackgroundThread());
if (mDeleteTimer) {
// QuotaClient::AsyncDeleteFile will not schedule new timers beyond
// shutdown. And we expect all critical (PBM) deletions to have been
// triggered before this point via ClearPrivateRepository (w/out using
// DeleteFilesRunnable at all).
mDeleteTimer->Cancel();
mDeleteTimer = nullptr;
mPendingDeleteInfos.Clear();
}
AbortAllOperations();
}
bool QuotaClient::IsShutdownCompleted() const {
return (!gFactoryOps || gFactoryOps->isEmpty()) &&
(!gLiveDatabaseHashtable || !gLiveDatabaseHashtable->Count()) &&
!mCurrentMaintenance && !DeleteFilesRunnable::IsDeletionPending();
}
void QuotaClient::ForceKillActors() {
// Currently we don't implement force killing actors.
}
nsCString QuotaClient::GetShutdownStatus() const {
AssertIsOnBackgroundThread();
nsCString data;
if (gFactoryOps && !gFactoryOps->isEmpty()) {
data.Append("FactoryOperations: "_ns +
IntToCString(static_cast<uint32_t>(gFactoryOps->length())) +
" ("_ns);
// XXX It might be confusing to remove duplicates here, as the actual list
// won't match the count then.
nsTHashSet<nsCString> ids;
std::transform(gFactoryOps->begin(), gFactoryOps->end(), MakeInserter(ids),
[](const FactoryOp* const factoryOp) {
MOZ_ASSERT(factoryOp);
nsCString id;
factoryOp->Stringify(id);
return id;
});
StringJoinAppend(data, ", "_ns, ids);
data.Append(")\n");
}
if (gLiveDatabaseHashtable && gLiveDatabaseHashtable->Count()) {
data.Append("LiveDatabases: "_ns +
IntToCString(gLiveDatabaseHashtable->Count()) + " ("_ns);
// XXX It might be confusing to remove duplicates here, as the actual list
// won't match the count then.
nsTHashSet<nsCString> ids;
for (const auto& entry : gLiveDatabaseHashtable->Values()) {
MOZ_ASSERT(entry);
std::transform(entry->mLiveDatabases.begin(), entry->mLiveDatabases.end(),
MakeInserter(ids), [](const Database* const database) {
nsCString id;
database->Stringify(id);
return id;
});
}
StringJoinAppend(data, ", "_ns, ids);
data.Append(")\n");
}
if (mCurrentMaintenance) {
data.Append("IdleMaintenance: 1 (");
mCurrentMaintenance->Stringify(data);
data.Append(")\n");
}
return data;
}
void QuotaClient::FinalizeShutdown() {
RefPtr<ConnectionPool> connectionPool = gConnectionPool.get();
if (connectionPool) {
connectionPool->Shutdown();
gConnectionPool = nullptr;
}
if (mMaintenanceThreadPool) {
mMaintenanceThreadPool->Shutdown();
mMaintenanceThreadPool = nullptr;
}
}
void QuotaClient::DeleteTimerCallback(nsITimer* aTimer, void* aClosure) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aTimer);
// Even though we do not schedule new timers after shutdown has started,
// an already existing one might fire afterwards (actually we think it
// shouldn't, but there is no reason to enforce this invariant). We can
// just ignore it, the cleanup work is done in InitiateShutdown.
if (NS_WARN_IF(IsShuttingDownOnBackgroundThread())) {
return;
}
auto* const self = static_cast<QuotaClient*>(aClosure);
MOZ_ASSERT(self);
MOZ_ASSERT(self->mDeleteTimer);
MOZ_ASSERT(SameCOMIdentity(self->mDeleteTimer, aTimer));
for (const auto& pendingDeleteInfoEntry : self->mPendingDeleteInfos) {
const auto& key = pendingDeleteInfoEntry.GetKey();
const auto& value = pendingDeleteInfoEntry.GetData();
MOZ_ASSERT(!value->IsEmpty());
RefPtr<DeleteFilesRunnable> runnable = new DeleteFilesRunnable(
SafeRefPtr{key, AcquireStrongRefFromRawPtr{}}, std::move(*value));
MOZ_ASSERT(value->IsEmpty());
runnable->RunImmediately();
}
self->mPendingDeleteInfos.Clear();
}
void QuotaClient::AbortAllMaintenances() {
if (mCurrentMaintenance) {
mCurrentMaintenance->Abort();
}
for (const auto& maintenance : mMaintenanceQueue) {
maintenance->Abort();
}
}
Result<nsCOMPtr<nsIFile>, nsresult> QuotaClient::GetDirectory(
const OriginMetadata& aOriginMetadata) {
QuotaManager* const quotaManager = QuotaManager::Get();
NS_ASSERTION(quotaManager, "This should never fail!");
QM_TRY_INSPECT(const auto& directory,
quotaManager->GetOriginDirectory(aOriginMetadata));
MOZ_ASSERT(directory);
QM_TRY(MOZ_TO_RESULT(
directory->Append(NS_LITERAL_STRING_FROM_CSTRING(IDB_DIRECTORY_NAME))));
return directory;
}
template <QuotaClient::ObsoleteFilenamesHandling ObsoleteFilenames>
Result<QuotaClient::GetDatabaseFilenamesResult<ObsoleteFilenames>, nsresult>
QuotaClient::GetDatabaseFilenames(nsIFile& aDirectory,
const AtomicBool& aCanceled) {
AssertIsOnIOThread();
GetDatabaseFilenamesResult<ObsoleteFilenames> result;
QM_TRY(CollectEachFileAtomicCancelable(
aDirectory, aCanceled,
[&result](const nsCOMPtr<nsIFile>& file) -> Result<Ok, nsresult> {
QM_TRY_INSPECT(const auto& leafName, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, file, GetLeafName));
QM_TRY_INSPECT(const auto& dirEntryKind, GetDirEntryKind(*file));
switch (dirEntryKind) {
case nsIFileKind::ExistsAsDirectory:
result.subdirsToProcess.AppendElement(leafName);
break;
case nsIFileKind::ExistsAsFile: {
if constexpr (ObsoleteFilenames ==
ObsoleteFilenamesHandling::Include) {
if (StringBeginsWith(leafName, kIdbDeletionMarkerFilePrefix)) {
result.obsoleteFilenames.Insert(
Substring(leafName, kIdbDeletionMarkerFilePrefix.Length()));
break;
}
}
// Skip OS metadata files. These files are only used in different
// platforms, but the profile can be shared across different
// operating systems, so we check it on all platforms.
if (QuotaManager::IsOSMetadata(leafName)) {
break;
}
// Skip files starting with ".".
if (QuotaManager::IsDotFile(leafName)) {
break;
}
// Skip SQLite temporary files. These files take up space on disk
// but will be deleted as soon as the database is opened, so we
// don't count them towards quota.
if (StringEndsWith(leafName, kSQLiteJournalSuffix) ||
StringEndsWith(leafName, kSQLiteSHMSuffix)) {
break;
}
// The SQLite WAL file does count towards quota, but it is handled
// below once we find the actual database file.
if (StringEndsWith(leafName, kSQLiteWALSuffix)) {
break;
}
nsDependentSubstring leafNameBase;
if (!GetFilenameBase(leafName, kSQLiteSuffix, leafNameBase)) {
UNKNOWN_FILE_WARNING(leafName);
break;
}
result.databaseFilenames.Insert(leafNameBase);
break;
}
case nsIFileKind::DoesNotExist:
// Ignore files that got removed externally while iterating.
break;
}
return Ok{};
}));
return result;
}
void QuotaClient::ProcessMaintenanceQueue() {
AssertIsOnBackgroundThread();
if (mCurrentMaintenance || mMaintenanceQueue.IsEmpty()) {
return;
}
mCurrentMaintenance = mMaintenanceQueue[0];
mMaintenanceQueue.RemoveElementAt(0);
mCurrentMaintenance->RunImmediately();
}
/*******************************************************************************
* DeleteFilesRunnable
******************************************************************************/
uint64_t DeleteFilesRunnable::sPendingRunnables = 0;
DeleteFilesRunnable::DeleteFilesRunnable(
SafeRefPtr<DatabaseFileManager> aFileManager, nsTArray<int64_t>&& aFileIds)
: Runnable("dom::indexeddb::DeleteFilesRunnable"),
mOwningEventTarget(GetCurrentSerialEventTarget()),
mFileManager(std::move(aFileManager)),
mFileIds(std::move(aFileIds)),
mState(State_Initial) {}
#ifdef DEBUG
DeleteFilesRunnable::~DeleteFilesRunnable() {
MOZ_ASSERT(!mDEBUGCountsAsPending);
}
#endif
void DeleteFilesRunnable::RunImmediately() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State_Initial);
Unused << this->Run();
}
void DeleteFilesRunnable::Open() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State_Initial);
MOZ_ASSERT(!mDEBUGCountsAsPending);
sPendingRunnables++;
DEBUGONLY(mDEBUGCountsAsPending = true);
QuotaManager* const quotaManager = QuotaManager::Get();
if (NS_WARN_IF(!quotaManager)) {
Finish();
return;
}
mState = State_DirectoryOpenPending;
quotaManager
->OpenClientDirectory(
{mFileManager->OriginMetadata(), quota::Client::IDB})
->Then(
GetCurrentSerialEventTarget(), __func__,
[self = RefPtr(this)](QuotaManager::ClientDirectoryLockHandlePromise::
ResolveOrRejectValue&& aValue) {
if (aValue.IsResolve()) {
self->DirectoryLockAcquired(std::move(aValue.ResolveValue()));
} else {
self->DirectoryLockFailed();
}
});
}
void DeleteFilesRunnable::DoDatabaseWork() {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State_DatabaseWorkOpen);
if (!mFileManager->Invalidated()) {
for (int64_t fileId : mFileIds) {
if (NS_FAILED(mFileManager->SyncDeleteFile(fileId))) {
NS_WARNING("Failed to delete file!");
}
}
}
Finish();
}
void DeleteFilesRunnable::Finish() {
MOZ_ASSERT(mState != State_UnblockingOpen);
// Must set mState before dispatching otherwise we will race with the main
// thread.
mState = State_UnblockingOpen;
MOZ_ALWAYS_SUCCEEDS(mOwningEventTarget->Dispatch(this, NS_DISPATCH_NORMAL));
}
void DeleteFilesRunnable::UnblockOpen() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State_UnblockingOpen);
{
auto destroyingDirectoryLockHandle = std::move(mDirectoryLockHandle);
}
MOZ_ASSERT(mDEBUGCountsAsPending);
sPendingRunnables--;
DEBUGONLY(mDEBUGCountsAsPending = false);
mState = State_Completed;
}
NS_IMETHODIMP
DeleteFilesRunnable::Run() {
switch (mState) {
case State_Initial:
Open();
break;
case State_DatabaseWorkOpen:
DoDatabaseWork();
break;
case State_UnblockingOpen:
UnblockOpen();
break;
case State_DirectoryOpenPending:
default:
MOZ_CRASH("Should never get here!");
}
return NS_OK;
}
void DeleteFilesRunnable::DirectoryLockAcquired(
ClientDirectoryLockHandle aLockHandle) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State_DirectoryOpenPending);
MOZ_ASSERT(!mDirectoryLockHandle);
mDirectoryLockHandle = std::move(aLockHandle);
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
// Must set this before dispatching otherwise we will race with the IO thread
mState = State_DatabaseWorkOpen;
QM_TRY(MOZ_TO_RESULT(
quotaManager->IOThread()->Dispatch(this, NS_DISPATCH_NORMAL)),
QM_VOID, [this](const nsresult) { Finish(); });
}
void DeleteFilesRunnable::DirectoryLockFailed() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State_DirectoryOpenPending);
MOZ_ASSERT(!mDirectoryLockHandle);
Finish();
}
void Maintenance::Abort() {
AssertIsOnBackgroundThread();
// Safe because mDatabaseMaintenances is modified
// only in the background thread
for (const auto& aDatabaseMaintenance : mDatabaseMaintenances) {
aDatabaseMaintenance.GetData()->Abort();
}
mAborted = true;
}
void Maintenance::RegisterDatabaseMaintenance(
DatabaseMaintenance* aDatabaseMaintenance) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aDatabaseMaintenance);
MOZ_ASSERT(mState == State::BeginDatabaseMaintenance);
MOZ_ASSERT(
!mDatabaseMaintenances.Contains(aDatabaseMaintenance->DatabasePath()));
mDatabaseMaintenances.InsertOrUpdate(aDatabaseMaintenance->DatabasePath(),
aDatabaseMaintenance);
}
void Maintenance::UnregisterDatabaseMaintenance(
DatabaseMaintenance* aDatabaseMaintenance) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aDatabaseMaintenance);
MOZ_ASSERT(mState == State::WaitingForDatabaseMaintenancesToComplete);
MOZ_ASSERT(mDatabaseMaintenances.Get(aDatabaseMaintenance->DatabasePath()));
mDatabaseMaintenances.Remove(aDatabaseMaintenance->DatabasePath());
if (mDatabaseMaintenances.Count()) {
return;
}
for (const auto& completeCallback : mCompleteCallbacks) {
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(completeCallback));
}
mCompleteCallbacks.Clear();
mState = State::Finishing;
Finish();
}
void Maintenance::Stringify(nsACString& aResult) const {
AssertIsOnBackgroundThread();
aResult.Append("DatabaseMaintenances: "_ns +
IntToCString(mDatabaseMaintenances.Count()) + " ("_ns);
// XXX It might be confusing to remove duplicates here, as the actual list
// won't match the count then.
nsTHashSet<nsCString> ids;
std::transform(mDatabaseMaintenances.Values().cbegin(),
mDatabaseMaintenances.Values().cend(), MakeInserter(ids),
[](const auto& entry) {
MOZ_ASSERT(entry);
nsCString id;
entry->Stringify(id);
return id;
});
StringJoinAppend(aResult, ", "_ns, ids);
aResult.Append(")");
}
nsresult Maintenance::Start() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::Initial);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsAborted()) {
return NS_ERROR_ABORT;
}
// Make sure that the IndexedDatabaseManager is running so that we can check
// for low disk space mode.
if (IndexedDatabaseManager::Get()) {
OpenDirectory();
return NS_OK;
}
mState = State::CreateIndexedDatabaseManager;
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(this));
return NS_OK;
}
nsresult Maintenance::CreateIndexedDatabaseManager() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mState == State::CreateIndexedDatabaseManager);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
IsAborted()) {
return NS_ERROR_ABORT;
}
IndexedDatabaseManager* const mgr = IndexedDatabaseManager::GetOrCreate();
if (NS_WARN_IF(!mgr)) {
return NS_ERROR_FAILURE;
}
mState = State::IndexedDatabaseManagerOpen;
MOZ_ALWAYS_SUCCEEDS(
mQuotaClient->BackgroundThread()->Dispatch(this, NS_DISPATCH_NORMAL));
return NS_OK;
}
RefPtr<UniversalDirectoryLockPromise> Maintenance::OpenStorageDirectory(
const PersistenceScope& aPersistenceScope, bool aInitializeOrigins) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!QuotaClient::IsShuttingDownOnBackgroundThread());
MOZ_ASSERT(!mDirectoryLock);
MOZ_ASSERT(!mAborted);
MOZ_ASSERT(mState == State::DirectoryOpenPending);
QuotaManager* quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
// Return a shared lock for <profile>/storage/repo(aPersistenceScope)/*/idb
return quotaManager->OpenStorageDirectory(
aPersistenceScope, OriginScope::FromNull(),
ClientStorageScope::CreateFromClient(Client::IDB),
/* aExclusive */ false, aInitializeOrigins, DirectoryLockCategory::None,
SomeRef(mPendingDirectoryLock));
}
nsresult Maintenance::OpenDirectory() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::Initial ||
mState == State::IndexedDatabaseManagerOpen);
MOZ_ASSERT(!mDirectoryLock);
MOZ_ASSERT(QuotaManager::Get());
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsAborted()) {
return NS_ERROR_ABORT;
}
mState = State::DirectoryOpenPending;
// Since idle maintenance may occur before persistent or temporary storage is
// initialized, make sure it's initialized here (all persistent and
// non-persistent origins need to be cleaned up and quota info needs to be
// loaded for non-persistent origins).
OpenStorageDirectory(PersistenceScope::CreateFromNull(),
/* aInitializeOrigins */ true)
->Then(
GetCurrentSerialEventTarget(), __func__,
[self = RefPtr(this)](
const UniversalDirectoryLockPromise::ResolveOrRejectValue&
aValue) {
if (aValue.IsResolve()) {
self->DirectoryLockAcquired(aValue.ResolveValue());
return;
}
// Don't fail whole idle maintenance in case of an error, the
// persistent repository can still be processed.
self->mPendingDirectoryLock = nullptr;
self->mOpenStorageForAllRepositoriesFailed = true;
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
self->IsAborted()) {
self->DirectoryLockFailed();
return;
}
self->OpenStorageDirectory(PersistenceScope::CreateFromValue(
PERSISTENCE_TYPE_PERSISTENT),
/* aInitializeOrigins */ true)
->Then(GetCurrentSerialEventTarget(), __func__,
[self](const UniversalDirectoryLockPromise::
ResolveOrRejectValue& aValue) {
if (aValue.IsResolve()) {
self->DirectoryLockAcquired(aValue.ResolveValue());
} else {
self->DirectoryLockFailed();
}
});
});
return NS_OK;
}
nsresult Maintenance::DirectoryOpen() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::DirectoryOpenPending);
MOZ_ASSERT(mDirectoryLock);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsAborted()) {
return NS_ERROR_ABORT;
}
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
mState = State::DirectoryWorkOpen;
QM_TRY(MOZ_TO_RESULT(
quotaManager->IOThread()->Dispatch(this, NS_DISPATCH_NORMAL)),
NS_ERROR_FAILURE);
return NS_OK;
}
nsresult Maintenance::DirectoryWork() {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State::DirectoryWorkOpen);
// The storage directory is structured like this:
//
// <profile>/storage/<persistence>/<origin>/idb/*.sqlite
//
// We have to find all database files that match any persistence type and any
// origin. We ignore anything out of the ordinary for now.
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
IsAborted()) {
return NS_ERROR_ABORT;
}
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
const nsCOMPtr<nsIFile> storageDir =
GetFileForPath(quotaManager->GetStoragePath());
QM_TRY(OkIf(storageDir), NS_ERROR_FAILURE);
{
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(storageDir, Exists));
// XXX No warning here?
if (!exists) {
return NS_ERROR_NOT_AVAILABLE;
}
}
{
QM_TRY_INSPECT(const bool& isDirectory,
MOZ_TO_RESULT_INVOKE_MEMBER(storageDir, IsDirectory));
QM_TRY(OkIf(isDirectory), NS_ERROR_FAILURE);
}
// There are currently only 4 persistence types, and we want to iterate them
// in this order:
static const PersistenceType kPersistenceTypes[] = {
PERSISTENCE_TYPE_PERSISTENT, PERSISTENCE_TYPE_DEFAULT,
PERSISTENCE_TYPE_TEMPORARY, PERSISTENCE_TYPE_PRIVATE};
static_assert(
std::size(kPersistenceTypes) == size_t(PERSISTENCE_TYPE_INVALID),
"Something changed with available persistence types!");
constexpr auto idbDirName =
NS_LITERAL_STRING_FROM_CSTRING(IDB_DIRECTORY_NAME);
for (const PersistenceType persistenceType : kPersistenceTypes) {
// Loop over "<persistence>" directories.
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
IsAborted()) {
return NS_ERROR_ABORT;
}
// Don't do any maintenance for private browsing databases, which are only
// temporary.
if (persistenceType == PERSISTENCE_TYPE_PRIVATE) {
continue;
}
const bool persistent = persistenceType == PERSISTENCE_TYPE_PERSISTENT;
if (!persistent && mOpenStorageForAllRepositoriesFailed) {
// Non-persistent (best effort) repositories can't be processed if
// temporary storage initialization failed.
continue;
}
// For all non-persistent types, temporary storage must already be
// initialized
MOZ_DIAGNOSTIC_ASSERT(
persistent || quotaManager->IsTemporaryStorageInitializedInternal());
// XXX persistenceType == PERSISTENCE_TYPE_PERSISTENT shouldn't be a special
// case...
const auto persistenceTypeString =
persistenceType == PERSISTENCE_TYPE_PERSISTENT
? "permanent"_ns
: PersistenceTypeToString(persistenceType);
QM_TRY_INSPECT(const auto& persistenceDir,
CloneFileAndAppend(*storageDir, NS_ConvertASCIItoUTF16(
persistenceTypeString)));
{
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(persistenceDir, Exists));
if (!exists) {
continue;
}
QM_TRY_INSPECT(const bool& isDirectory,
MOZ_TO_RESULT_INVOKE_MEMBER(persistenceDir, IsDirectory));
if (NS_WARN_IF(!isDirectory)) {
continue;
}
}
// Loop over "<origin>/idb" directories.
QM_TRY(CollectEachFile(
*persistenceDir,
[this, "aManager, persistenceType, persistent, &idbDirName](
const nsCOMPtr<nsIFile>& originDir) -> Result<Ok, nsresult> {
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
IsAborted()) {
return Err(NS_ERROR_ABORT);
}
QM_TRY_INSPECT(const auto& dirEntryKind, GetDirEntryKind(*originDir));
switch (dirEntryKind) {
case nsIFileKind::ExistsAsFile:
break;
case nsIFileKind::ExistsAsDirectory: {
// Get the necessary information about the origin
// (GetOriginMetadata also checks if it's a valid origin).
QM_TRY_UNWRAP(auto metadata,
quotaManager->GetOriginMetadata(originDir),
// Not much we can do here...
Ok{});
if (!persistent &&
!quotaManager->IsTemporaryOriginInitializedInternal(
metadata)) {
glean::idb_maintenance::fallback_fullrestore_metadata.Add();
// XXX GetOriginMetadata, which skips loading the metadata file
// and instead relies on parsing the origin directory name and
// reconstructing the principal, may produce a different origin
// string than the one originally used to create the origin
// directory.
//
// For now, if this mismatch occurs, we fall back to the slower
// LoadFullOriginMetadataWithRestore.
//
// In the future, it would be useful to report anonymized
// origin strings via telemetry to help investigate and
// eventually fix this mismatch.
QM_TRY_INSPECT(
const auto& fullmetadataAndStatus,
quotaManager->LoadFullOriginMetadataWithRestoreAndStatus(
originDir),
Ok{});
metadata = fullmetadataAndStatus.first;
if (fullmetadataAndStatus.second) {
/* metadata was restored */
glean::idb_maintenance::metadata_restored.Add();
}
QM_TRY(OkIf(quotaManager->IsTemporaryOriginInitializedInternal(
metadata)),
/* unexpected but still fine to just skip it */ Ok{},
/* increment telemetry in case of failure */
[](const auto&) {
glean::idb_maintenance::unknown_metadata.Add();
});
}
// We now use a dedicated repository for private browsing
// databases, but there could be some forgotten private browsing
// databases in other repositories, so it's better to check for
// that and don't do any maintenance for such databases.
if (metadata.mIsPrivate) {
return Ok{};
}
QM_TRY_INSPECT(const auto& idbDir,
CloneFileAndAppend(*originDir, idbDirName));
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(idbDir, Exists));
if (!exists) {
return Ok{};
}
QM_TRY_INSPECT(const bool& isDirectory,
MOZ_TO_RESULT_INVOKE_MEMBER(idbDir, IsDirectory));
QM_TRY(OkIf(isDirectory), Ok{});
nsTArray<nsString> databasePaths;
// Loop over files in the "idb" directory.
QM_TRY(CollectEachFile(
*idbDir,
[this, &databasePaths](const nsCOMPtr<nsIFile>& idbDirFile)
-> Result<Ok, nsresult> {
if (NS_WARN_IF(QuotaClient::
IsShuttingDownOnNonBackgroundThread()) ||
IsAborted()) {
return Err(NS_ERROR_ABORT);
}
QM_TRY_UNWRAP(auto idbFilePath,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, idbDirFile, GetPath));
if (!StringEndsWith(idbFilePath, kSQLiteSuffix)) {
return Ok{};
}
QM_TRY_INSPECT(const auto& dirEntryKind,
GetDirEntryKind(*idbDirFile));
switch (dirEntryKind) {
case nsIFileKind::ExistsAsDirectory:
break;
case nsIFileKind::ExistsAsFile:
// Found a database.
MOZ_ASSERT(!databasePaths.Contains(idbFilePath));
databasePaths.AppendElement(std::move(idbFilePath));
break;
case nsIFileKind::DoesNotExist:
// Ignore files that got removed externally while
// iterating.
break;
}
return Ok{};
}));
if (!databasePaths.IsEmpty()) {
if (!persistent) {
auto maybeOriginStateMetadata =
quotaManager->GetOriginStateMetadata(metadata);
auto originStateMetadata = maybeOriginStateMetadata.extract();
// Skip origin maintenance if the origin hasn't been accessed
// since its last recorded maintenance. This avoids
// unnecessary I/O and prevents updating the accessed flag in
// metadata, which helps preserve the effectiveness of the L2
// quota info cache.
//
// This early-out is safe because maintenance is only needed
// when something has changed (e.g., new access or activity).
const Date accessDate =
Date::FromTimestamp(originStateMetadata.mLastAccessTime);
const Date maintenanceDate =
Date::FromDays(originStateMetadata.mLastMaintenanceDate);
if (accessDate <= maintenanceDate) {
return Ok{};
}
originStateMetadata.mLastMaintenanceDate =
Date::Today().ToDays();
originStateMetadata.mAccessed = true;
QM_TRY(MOZ_TO_RESULT(SaveDirectoryMetadataHeader(
*originDir, originStateMetadata)));
quotaManager->UpdateOriginMaintenanceDate(
metadata, originStateMetadata.mLastMaintenanceDate);
quotaManager->UpdateOriginAccessed(metadata);
}
mDirectoryInfos.EmplaceBack(persistenceType, metadata,
std::move(databasePaths));
}
break;
}
case nsIFileKind::DoesNotExist:
// Ignore files that got removed externally while iterating.
break;
}
return Ok{};
}));
}
mState = State::BeginDatabaseMaintenance;
MOZ_ALWAYS_SUCCEEDS(
mQuotaClient->BackgroundThread()->Dispatch(this, NS_DISPATCH_NORMAL));
return NS_OK;
}
nsresult Maintenance::BeginDatabaseMaintenance() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::BeginDatabaseMaintenance);
class MOZ_STACK_CLASS Helper final {
public:
static bool IsSafeToRunMaintenance(const nsAString& aDatabasePath) {
if (gFactoryOps) {
// XXX LinkedList should support reverse iteration via rbegin() and
// rend(), see bug 1964967.
for (const FactoryOp* existingOp = gFactoryOps->getLast(); existingOp;
existingOp = existingOp->getPrevious()) {
if (existingOp->DatabaseNameRef().isNothing()) {
return false;
}
if (!existingOp->DatabaseFilePathIsKnown()) {
continue;
}
if (existingOp->DatabaseFilePath() == aDatabasePath) {
return false;
}
}
}
if (gLiveDatabaseHashtable) {
return std::all_of(gLiveDatabaseHashtable->Values().cbegin(),
gLiveDatabaseHashtable->Values().cend(),
[&aDatabasePath](const auto& liveDatabasesEntry) {
// XXX std::all_of currently doesn't work with
// LinkedList's iterator. See bug 1964969.
for (const Database* const database :
liveDatabasesEntry->mLiveDatabases) {
if (database->FilePath() == aDatabasePath) {
return false;
}
}
return true;
});
}
return true;
}
};
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsAborted()) {
return NS_ERROR_ABORT;
}
RefPtr<nsThreadPool> threadPool;
for (DirectoryInfo& directoryInfo : mDirectoryInfos) {
for (const nsAString& databasePath : *directoryInfo.mDatabasePaths) {
if (Helper::IsSafeToRunMaintenance(databasePath)) {
RefPtr<ClientDirectoryLock> directoryLock =
mDirectoryLock->SpecializeForClient(directoryInfo.mPersistenceType,
*directoryInfo.mOriginMetadata,
Client::IDB);
MOZ_ASSERT(directoryLock);
// No key needs to be passed here, because we skip encrypted databases
// in DoDirectoryWork as long as they are only used in private browsing
// mode.
const auto databaseMaintenance = MakeRefPtr<DatabaseMaintenance>(
this, std::move(directoryLock), directoryInfo.mPersistenceType,
*directoryInfo.mOriginMetadata, databasePath, Nothing{});
if (!threadPool) {
threadPool = mQuotaClient->GetOrCreateThreadPool();
MOZ_ASSERT(threadPool);
}
// Perform database maintenance on a TaskQueue, as database connections
// require a serial event target when being opened in order to allow
// memory pressure notifications to clear caches (bug 1806751).
const auto taskQueue = TaskQueue::Create(
do_AddRef(threadPool), "IndexedDB Database Maintenance");
MOZ_ALWAYS_SUCCEEDS(
taskQueue->Dispatch(databaseMaintenance, NS_DISPATCH_NORMAL));
RegisterDatabaseMaintenance(databaseMaintenance);
}
}
}
mDirectoryInfos.Clear();
DropDirectoryLock(mDirectoryLock);
if (mDatabaseMaintenances.Count()) {
mState = State::WaitingForDatabaseMaintenancesToComplete;
} else {
mState = State::Finishing;
Finish();
}
return NS_OK;
}
void Maintenance::Finish() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::Finishing);
if (NS_SUCCEEDED(mResultCode)) {
mPromiseHolder.ResolveIfExists(true, __func__);
} else {
mPromiseHolder.RejectIfExists(mResultCode, __func__);
nsCString errorName;
GetErrorName(mResultCode, errorName);
IDB_WARNING("Maintenance finished with error: %s", errorName.get());
}
SafeDropDirectoryLock(mDirectoryLock);
// It can happen that we are only referenced by mCurrentMaintenance which is
// cleared in NoteFinishedMaintenance()
const RefPtr<Maintenance> kungFuDeathGrip = this;
mQuotaClient->NoteFinishedMaintenance(this);
mState = State::Complete;
}
NS_IMETHODIMP
Maintenance::Run() {
MOZ_ASSERT(mState != State::Complete);
const auto handleError = [this](const nsresult rv) {
if (mState != State::Finishing) {
if (NS_SUCCEEDED(mResultCode)) {
mResultCode = rv;
}
// Must set mState before dispatching otherwise we will race with the
// owning thread.
mState = State::Finishing;
if (IsOnBackgroundThread()) {
Finish();
} else {
MOZ_ALWAYS_SUCCEEDS(mQuotaClient->BackgroundThread()->Dispatch(
this, NS_DISPATCH_NORMAL));
}
}
};
switch (mState) {
case State::Initial:
QM_TRY(MOZ_TO_RESULT(Start()), NS_OK, handleError);
break;
case State::CreateIndexedDatabaseManager:
QM_TRY(MOZ_TO_RESULT(CreateIndexedDatabaseManager()), NS_OK, handleError);
break;
case State::IndexedDatabaseManagerOpen:
QM_TRY(MOZ_TO_RESULT(OpenDirectory()), NS_OK, handleError);
break;
case State::DirectoryWorkOpen:
QM_TRY(MOZ_TO_RESULT(DirectoryWork()), NS_OK, handleError);
break;
case State::BeginDatabaseMaintenance:
QM_TRY(MOZ_TO_RESULT(BeginDatabaseMaintenance()), NS_OK, handleError);
break;
case State::Finishing:
Finish();
break;
default:
MOZ_CRASH("Bad state!");
}
return NS_OK;
}
void Maintenance::DirectoryLockAcquired(UniversalDirectoryLock* aLock) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::DirectoryOpenPending);
MOZ_ASSERT(!mDirectoryLock);
mDirectoryLock = std::exchange(mPendingDirectoryLock, nullptr);
nsresult rv = DirectoryOpen();
if (NS_WARN_IF(NS_FAILED(rv))) {
if (NS_SUCCEEDED(mResultCode)) {
mResultCode = rv;
}
mState = State::Finishing;
Finish();
return;
}
}
void Maintenance::DirectoryLockFailed() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mState == State::DirectoryOpenPending);
MOZ_ASSERT(!mDirectoryLock);
mPendingDirectoryLock = nullptr;
if (NS_SUCCEEDED(mResultCode)) {
mResultCode = NS_ERROR_FAILURE;
}
mState = State::Finishing;
Finish();
}
void DatabaseMaintenance::Stringify(nsACString& aResult) const {
AssertIsOnBackgroundThread();
aResult.AppendLiteral("Origin:");
aResult.Append(AnonymizedOriginString(mOriginMetadata.mOrigin));
aResult.Append(kQuotaGenericDelimiter);
aResult.AppendLiteral("PersistenceType:");
aResult.Append(PersistenceTypeToString(mPersistenceType));
aResult.Append(kQuotaGenericDelimiter);
aResult.AppendLiteral("Duration:");
aResult.AppendInt((PR_Now() - mMaintenance->StartTime()) / PR_USEC_PER_MSEC);
}
nsresult DatabaseMaintenance::Abort() {
AssertIsOnBackgroundThread();
// StopIdleMaintenance and AbortAllOperations may request abort independently
if (!mAborted.compareExchange(false, true)) {
return NS_OK;
}
{
auto shardStorageConnectionLocked = mSharedStorageConnection.Lock();
if (nsCOMPtr<mozIStorageConnection> connection =
*shardStorageConnectionLocked) {
QM_TRY(MOZ_TO_RESULT(connection->Interrupt()));
}
}
return NS_OK;
}
void DatabaseMaintenance::PerformMaintenanceOnDatabase() {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(mMaintenance);
MOZ_ASSERT(mMaintenance->StartTime());
MOZ_ASSERT(mDirectoryLock);
MOZ_ASSERT(!mDatabasePath.IsEmpty());
MOZ_ASSERT(!mOriginMetadata.mGroup.IsEmpty());
MOZ_ASSERT(!mOriginMetadata.mOrigin.IsEmpty());
if (NS_WARN_IF(IsAborted())) {
return;
}
const nsCOMPtr<nsIFile> databaseFile = GetFileForPath(mDatabasePath);
MOZ_ASSERT(databaseFile);
QM_TRY_UNWRAP(
const NotNull<nsCOMPtr<mozIStorageConnection>> connection,
GetStorageConnection(*databaseFile, mDirectoryLockId,
TelemetryIdForFile(databaseFile), mMaybeKey),
QM_VOID);
auto autoClearConnection = MakeScopeExit([&]() {
auto sharedStorageConnectionLocked = mSharedStorageConnection.Lock();
sharedStorageConnectionLocked.ref() = nullptr;
connection->Close();
});
{
auto sharedStorageConnectionLocked = mSharedStorageConnection.Lock();
sharedStorageConnectionLocked.ref() = connection;
}
auto databaseIsOk = false;
QM_TRY(MOZ_TO_RESULT(CheckIntegrity(*connection, &databaseIsOk)), QM_VOID);
QM_TRY(OkIf(databaseIsOk), QM_VOID, [](auto result) {
// XXX Handle this somehow! Probably need to clear all storage for the
// origin. See Bug 1760612.
MOZ_ASSERT(false, "Database corruption detected!");
});
MaintenanceAction maintenanceAction;
QM_TRY(MOZ_TO_RESULT(DetermineMaintenanceAction(*connection, databaseFile,
&maintenanceAction)),
QM_VOID);
switch (maintenanceAction) {
case MaintenanceAction::Nothing:
break;
case MaintenanceAction::IncrementalVacuum:
IncrementalVacuum(*connection);
break;
case MaintenanceAction::FullVacuum:
FullVacuum(*connection, databaseFile);
break;
default:
MOZ_CRASH("Unknown MaintenanceAction!");
}
}
nsresult DatabaseMaintenance::CheckIntegrity(mozIStorageConnection& aConnection,
bool* aOk) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aOk);
if (NS_WARN_IF(IsAborted())) {
return NS_ERROR_ABORT;
}
// First do a full integrity_check. Scope statements tightly here because
// later operations require zero live statements.
{
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement(
aConnection, "PRAGMA integrity_check(1);"_ns));
QM_TRY_INSPECT(const auto& result, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, *stmt, GetString, 0));
QM_TRY(OkIf(result.EqualsLiteral("ok")), NS_OK,
[&aOk](const auto) { *aOk = false; });
}
// Now enable and check for foreign key constraints.
{
QM_TRY_INSPECT(
const int32_t& foreignKeysWereEnabled,
([&aConnection]() -> Result<int32_t, nsresult> {
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement(
aConnection, "PRAGMA foreign_keys;"_ns));
QM_TRY_RETURN(MOZ_TO_RESULT_INVOKE_MEMBER(*stmt, GetInt32, 0));
}()));
if (!foreignKeysWereEnabled) {
QM_TRY(MOZ_TO_RESULT(
aConnection.ExecuteSimpleSQL("PRAGMA foreign_keys = ON;"_ns)));
}
QM_TRY_INSPECT(const bool& foreignKeyError,
CreateAndExecuteSingleStepStatement<
SingleStepResult::ReturnNullIfNoResult>(
aConnection, "PRAGMA foreign_key_check;"_ns));
if (!foreignKeysWereEnabled) {
QM_TRY(MOZ_TO_RESULT(
aConnection.ExecuteSimpleSQL("PRAGMA foreign_keys = OFF;"_ns)));
}
if (foreignKeyError) {
*aOk = false;
return NS_OK;
}
}
*aOk = true;
return NS_OK;
}
nsresult DatabaseMaintenance::DetermineMaintenanceAction(
mozIStorageConnection& aConnection, nsIFile* aDatabaseFile,
MaintenanceAction* aMaintenanceAction) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aDatabaseFile);
MOZ_ASSERT(aMaintenanceAction);
if (NS_WARN_IF(IsAborted())) {
return NS_ERROR_ABORT;
}
QM_TRY_INSPECT(const int32_t& schemaVersion,
MOZ_TO_RESULT_INVOKE_MEMBER(aConnection, GetSchemaVersion));
// Don't do anything if the schema version is less than 18; before that
// version no databases had |auto_vacuum == INCREMENTAL| set and we didn't
// track the values needed for the heuristics below.
if (schemaVersion < MakeSchemaVersion(18, 0)) {
*aMaintenanceAction = MaintenanceAction::Nothing;
return NS_OK;
}
// This method shouldn't make any permanent changes to the database, so make
// sure everything gets rolled back when we leave.
mozStorageTransaction transaction(&aConnection,
/* aCommitOnComplete */ false);
QM_TRY(MOZ_TO_RESULT(transaction.Start()))
// Check to see when we last vacuumed this database.
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement(
aConnection,
"SELECT last_vacuum_time, last_vacuum_size "
"FROM database;"_ns));
QM_TRY_INSPECT(const PRTime& lastVacuumTime,
MOZ_TO_RESULT_INVOKE_MEMBER(*stmt, GetInt64, 0));
QM_TRY_INSPECT(const int64_t& lastVacuumSize,
MOZ_TO_RESULT_INVOKE_MEMBER(*stmt, GetInt64, 1));
NS_ASSERTION(lastVacuumSize > 0,
"Thy last vacuum size shall be greater than zero, less than "
"zero shall thy last vacuum size not be. Zero is right out.");
const PRTime startTime = mMaintenance->StartTime();
// This shouldn't really be possible...
if (NS_WARN_IF(startTime <= lastVacuumTime)) {
*aMaintenanceAction = MaintenanceAction::Nothing;
return NS_OK;
}
if (startTime - lastVacuumTime < kMinVacuumAge) {
*aMaintenanceAction = MaintenanceAction::IncrementalVacuum;
return NS_OK;
}
// It has been more than a week since the database was vacuumed, so gather
// statistics on its usage to see if vacuuming is worthwhile.
// Create a temporary copy of the dbstat table to speed up the queries that
// come later.
QM_TRY(MOZ_TO_RESULT(aConnection.ExecuteSimpleSQL(
"CREATE VIRTUAL TABLE __stats__ USING dbstat;"
"CREATE TEMP TABLE __temp_stats__ AS SELECT * FROM __stats__;"_ns)));
{ // Calculate the percentage of the database pages that are not in
// contiguous order.
QM_TRY_INSPECT(
const auto& stmt,
CreateAndExecuteSingleStepStatement(
aConnection,
"SELECT SUM(__ts1__.pageno != __ts2__.pageno + 1) * 100.0 / "
"COUNT(*) "
"FROM __temp_stats__ AS __ts1__, __temp_stats__ AS __ts2__ "
"WHERE __ts1__.name = __ts2__.name "
"AND __ts1__.rowid = __ts2__.rowid + 1;"_ns));
QM_TRY_INSPECT(const int32_t& percentUnordered,
MOZ_TO_RESULT_INVOKE_MEMBER(*stmt, GetInt32, 0));
MOZ_ASSERT(percentUnordered >= 0);
MOZ_ASSERT(percentUnordered <= 100);
if (percentUnordered >= kPercentUnorderedThreshold) {
*aMaintenanceAction = MaintenanceAction::FullVacuum;
return NS_OK;
}
}
// Don't try a full vacuum if the file hasn't grown by 10%.
QM_TRY_INSPECT(const int64_t& currentFileSize,
MOZ_TO_RESULT_INVOKE_MEMBER(aDatabaseFile, GetFileSize));
if (currentFileSize <= lastVacuumSize ||
(((currentFileSize - lastVacuumSize) * 100 / currentFileSize) <
kPercentFileSizeGrowthThreshold)) {
*aMaintenanceAction = MaintenanceAction::IncrementalVacuum;
return NS_OK;
}
{ // See if there are any free pages that we can reclaim.
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement(
aConnection, "PRAGMA freelist_count;"_ns));
QM_TRY_INSPECT(const int32_t& freelistCount,
MOZ_TO_RESULT_INVOKE_MEMBER(*stmt, GetInt32, 0));
MOZ_ASSERT(freelistCount >= 0);
// If we have too many free pages then we should try an incremental
// vacuum. If that causes too much fragmentation then we'll try a full
// vacuum later.
if (freelistCount > kMaxFreelistThreshold) {
*aMaintenanceAction = MaintenanceAction::IncrementalVacuum;
return NS_OK;
}
}
{ // Calculate the percentage of unused bytes on pages in the database.
QM_TRY_INSPECT(
const auto& stmt,
CreateAndExecuteSingleStepStatement(
aConnection,
"SELECT SUM(unused) * 100.0 / SUM(pgsize) FROM __temp_stats__;"_ns));
QM_TRY_INSPECT(const int32_t& percentUnused,
MOZ_TO_RESULT_INVOKE_MEMBER(*stmt, GetInt32, 0));
MOZ_ASSERT(percentUnused >= 0);
MOZ_ASSERT(percentUnused <= 100);
*aMaintenanceAction = percentUnused >= kPercentUnusedThreshold
? MaintenanceAction::FullVacuum
: MaintenanceAction::IncrementalVacuum;
}
return NS_OK;
}
void DatabaseMaintenance::IncrementalVacuum(
mozIStorageConnection& aConnection) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
if (NS_WARN_IF(IsAborted())) {
return;
}
nsresult rv = aConnection.ExecuteSimpleSQL("PRAGMA incremental_vacuum;"_ns);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
}
void DatabaseMaintenance::FullVacuum(mozIStorageConnection& aConnection,
nsIFile* aDatabaseFile) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aDatabaseFile);
if (NS_WARN_IF(IsAborted())) {
return;
}
QM_WARNONLY_TRY(([&]() -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(aConnection.ExecuteSimpleSQL("VACUUM;"_ns)));
const PRTime vacuumTime = PR_Now();
MOZ_ASSERT(vacuumTime > 0);
QM_TRY_INSPECT(const int64_t& fileSize,
MOZ_TO_RESULT_INVOKE_MEMBER(aDatabaseFile, GetFileSize));
MOZ_ASSERT(fileSize > 0);
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(const auto& stmt, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>,
aConnection, CreateStatement,
"UPDATE database "
"SET last_vacuum_time = :time"
", last_vacuum_size = :size;"_ns));
QM_TRY(MOZ_TO_RESULT(stmt->BindInt64ByIndex(0, vacuumTime)));
QM_TRY(MOZ_TO_RESULT(stmt->BindInt64ByIndex(1, fileSize)));
QM_TRY(MOZ_TO_RESULT(stmt->Execute()));
return Ok{};
}()));
}
void DatabaseMaintenance::RunOnOwningThread() {
AssertIsOnBackgroundThread();
DropDirectoryLock(mDirectoryLock);
if (mCompleteCallback) {
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(mCompleteCallback.forget()));
}
mMaintenance->UnregisterDatabaseMaintenance(this);
}
void DatabaseMaintenance::RunOnConnectionThread() {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
PerformMaintenanceOnDatabase();
MOZ_ALWAYS_SUCCEEDS(
mMaintenance->BackgroundThread()->Dispatch(this, NS_DISPATCH_NORMAL));
}
NS_IMETHODIMP
DatabaseMaintenance::Run() {
if (IsOnBackgroundThread()) {
RunOnOwningThread();
} else {
RunOnConnectionThread();
}
return NS_OK;
}
/*******************************************************************************
* Local class implementations
******************************************************************************/
// static
nsAutoCString DatabaseOperationBase::MaybeGetBindingClauseForKeyRange(
const Maybe<SerializedKeyRange>& aOptionalKeyRange,
const nsACString& aKeyColumnName) {
return aOptionalKeyRange.isSome()
? GetBindingClauseForKeyRange(aOptionalKeyRange.ref(),
aKeyColumnName)
: nsAutoCString{};
}
// static
nsAutoCString DatabaseOperationBase::GetBindingClauseForKeyRange(
const SerializedKeyRange& aKeyRange, const nsACString& aKeyColumnName) {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(!aKeyColumnName.IsEmpty());
constexpr auto andStr = " AND "_ns;
constexpr auto spacecolon = " :"_ns;
nsAutoCString result;
if (aKeyRange.isOnly()) {
// Both keys equal.
result =
andStr + aKeyColumnName + " ="_ns + spacecolon + kStmtParamNameLowerKey;
} else {
if (!aKeyRange.lower().IsUnset()) {
// Lower key is set.
result.Append(andStr + aKeyColumnName);
result.AppendLiteral(" >");
if (!aKeyRange.lowerOpen()) {
result.AppendLiteral("=");
}
result.Append(spacecolon + kStmtParamNameLowerKey);
}
if (!aKeyRange.upper().IsUnset()) {
// Upper key is set.
result.Append(andStr + aKeyColumnName);
result.AppendLiteral(" <");
if (!aKeyRange.upperOpen()) {
result.AppendLiteral("=");
}
result.Append(spacecolon + kStmtParamNameUpperKey);
}
}
MOZ_ASSERT(!result.IsEmpty());
return result;
}
// static
uint64_t DatabaseOperationBase::ReinterpretDoubleAsUInt64(double aDouble) {
// This is a duplicate of the js engine's byte munging in StructuredClone.cpp
return BitwiseCast<uint64_t>(aDouble);
}
// static
template <typename KeyTransformation>
nsresult DatabaseOperationBase::MaybeBindKeyToStatement(
const Key& aKey, mozIStorageStatement* const aStatement,
const nsACString& aParameterName,
const KeyTransformation& aKeyTransformation) {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aStatement);
if (!aKey.IsUnset()) {
// XXX This case distinction could be avoided if QM_TRY_INSPECT would also
// work with a function not returning a Result<V, E> but simply a V (which
// is const Key& here) and then assuming it is always a success. Or the
// transformation could be changed to return Result<const V&, void> but I
// don't think that Result supports that at the moment.
if constexpr (std::is_reference_v<
std::invoke_result_t<KeyTransformation, Key>>) {
QM_TRY(MOZ_TO_RESULT(aKeyTransformation(aKey).BindToStatement(
aStatement, aParameterName)));
} else {
QM_TRY_INSPECT(const auto& transformedKey, aKeyTransformation(aKey));
QM_TRY(MOZ_TO_RESULT(
transformedKey.BindToStatement(aStatement, aParameterName)));
}
}
return NS_OK;
}
// static
template <typename KeyTransformation>
nsresult DatabaseOperationBase::BindTransformedKeyRangeToStatement(
const SerializedKeyRange& aKeyRange, mozIStorageStatement* const aStatement,
const KeyTransformation& aKeyTransformation) {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aStatement);
QM_TRY(MOZ_TO_RESULT(MaybeBindKeyToStatement(aKeyRange.lower(), aStatement,
kStmtParamNameLowerKey,
aKeyTransformation)));
if (aKeyRange.isOnly()) {
return NS_OK;
}
QM_TRY(MOZ_TO_RESULT(MaybeBindKeyToStatement(aKeyRange.upper(), aStatement,
kStmtParamNameUpperKey,
aKeyTransformation)));
return NS_OK;
}
// static
nsresult DatabaseOperationBase::BindKeyRangeToStatement(
const SerializedKeyRange& aKeyRange,
mozIStorageStatement* const aStatement) {
return BindTransformedKeyRangeToStatement(
aKeyRange, aStatement, [](const Key& key) -> const auto& { return key; });
}
// static
nsresult DatabaseOperationBase::BindKeyRangeToStatement(
const SerializedKeyRange& aKeyRange, mozIStorageStatement* const aStatement,
const nsCString& aLocale) {
MOZ_ASSERT(!aLocale.IsEmpty());
return BindTransformedKeyRangeToStatement(
aKeyRange, aStatement,
[&aLocale](const Key& key) { return key.ToLocaleAwareKey(aLocale); });
}
// static
void CommonOpenOpHelperBase::AppendConditionClause(
const nsACString& aColumnName, const nsACString& aStatementParameterName,
bool aLessThan, bool aEquals, nsCString& aResult) {
aResult += " AND "_ns + aColumnName + " "_ns;
if (aLessThan) {
aResult.Append('<');
} else {
aResult.Append('>');
}
if (aEquals) {
aResult.Append('=');
}
aResult += " :"_ns + aStatementParameterName;
}
// static
Result<IndexDataValuesAutoArray, nsresult>
DatabaseOperationBase::IndexDataValuesFromUpdateInfos(
const nsTArray<IndexUpdateInfo>& aUpdateInfos,
const UniqueIndexTable& aUniqueIndexTable) {
MOZ_ASSERT_IF(!aUpdateInfos.IsEmpty(), aUniqueIndexTable.Count());
AUTO_PROFILER_LABEL("DatabaseOperationBase::IndexDataValuesFromUpdateInfos",
DOM);
// XXX We could use TransformIntoNewArray here if it allowed to specify that
// an AutoArray should be created.
IndexDataValuesAutoArray indexValues;
if (NS_WARN_IF(!indexValues.SetCapacity(aUpdateInfos.Length(), fallible))) {
IDB_REPORT_INTERNAL_ERR();
return Err(NS_ERROR_OUT_OF_MEMORY);
}
std::transform(aUpdateInfos.cbegin(), aUpdateInfos.cend(),
MakeBackInserter(indexValues),
[&aUniqueIndexTable](const IndexUpdateInfo& updateInfo) {
const IndexOrObjectStoreId& indexId = updateInfo.indexId();
bool unique = false;
MOZ_ALWAYS_TRUE(aUniqueIndexTable.Get(indexId, &unique));
return IndexDataValue{indexId, unique, updateInfo.value(),
updateInfo.localizedValue()};
});
indexValues.Sort();
return indexValues;
}
// static
nsresult DatabaseOperationBase::InsertIndexTableRows(
DatabaseConnection* aConnection, const IndexOrObjectStoreId aObjectStoreId,
const Key& aObjectStoreKey, const nsTArray<IndexDataValue>& aIndexValues) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(!aObjectStoreKey.IsUnset());
AUTO_PROFILER_LABEL("DatabaseOperationBase::InsertIndexTableRows", DOM);
const uint32_t count = aIndexValues.Length();
if (!count) {
return NS_OK;
}
auto insertUniqueStmt = DatabaseConnection::LazyStatement{
*aConnection,
"INSERT INTO unique_index_data "
"(index_id, value, object_store_id, "
"object_data_key, value_locale) "
"VALUES (:"_ns +
kStmtParamNameIndexId + ", :"_ns + kStmtParamNameValue + ", :"_ns +
kStmtParamNameObjectStoreId + ", :"_ns + kStmtParamNameObjectDataKey +
", :"_ns + kStmtParamNameValueLocale + ");"_ns};
auto insertStmt = DatabaseConnection::LazyStatement{
*aConnection,
"INSERT OR IGNORE INTO index_data "
"(index_id, value, object_data_key, "
"object_store_id, value_locale) "
"VALUES (:"_ns +
kStmtParamNameIndexId + ", :"_ns + kStmtParamNameValue + ", :"_ns +
kStmtParamNameObjectDataKey + ", :"_ns + kStmtParamNameObjectStoreId +
", :"_ns + kStmtParamNameValueLocale + ");"_ns};
for (uint32_t index = 0; index < count; index++) {
const IndexDataValue& info = aIndexValues[index];
auto& stmt = info.mUnique ? insertUniqueStmt : insertStmt;
QM_TRY_INSPECT(const auto& borrowedStmt, stmt.Borrow());
QM_TRY(MOZ_TO_RESULT(
borrowedStmt->BindInt64ByName(kStmtParamNameIndexId, info.mIndexId)));
QM_TRY(MOZ_TO_RESULT(
info.mPosition.BindToStatement(&*borrowedStmt, kStmtParamNameValue)));
QM_TRY(MOZ_TO_RESULT(info.mLocaleAwarePosition.BindToStatement(
&*borrowedStmt, kStmtParamNameValueLocale)));
QM_TRY(MOZ_TO_RESULT(borrowedStmt->BindInt64ByName(
kStmtParamNameObjectStoreId, aObjectStoreId)));
QM_TRY(MOZ_TO_RESULT(aObjectStoreKey.BindToStatement(
&*borrowedStmt, kStmtParamNameObjectDataKey)));
// QM_OR_ELSE_WARN_IF is not used here since we just want to log the
// collision and not spam the reports.
QM_TRY(QM_OR_ELSE_LOG_VERBOSE_IF(
// Expression.
MOZ_TO_RESULT(borrowedStmt->Execute()),
// Predicate.
([&info, index, &aIndexValues](nsresult rv) {
if (rv == NS_ERROR_STORAGE_CONSTRAINT && info.mUnique) {
// If we're inserting multiple entries for the same unique
// index, then we might have failed to insert due to
// colliding with another entry for the same index in which
// case we should ignore it.
for (int32_t index2 = int32_t(index) - 1;
index2 >= 0 && aIndexValues[index2].mIndexId == info.mIndexId;
--index2) {
if (info.mPosition == aIndexValues[index2].mPosition) {
// We found a key with the same value for the same
// index. So we must have had a collision with a value
// we just inserted.
return true;
}
}
}
return false;
}),
// Fallback.
ErrToDefaultOk<>));
}
return NS_OK;
}
// static
nsresult DatabaseOperationBase::DeleteIndexDataTableRows(
DatabaseConnection* aConnection, const Key& aObjectStoreKey,
const nsTArray<IndexDataValue>& aIndexValues) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(!aObjectStoreKey.IsUnset());
AUTO_PROFILER_LABEL("DatabaseOperationBase::DeleteIndexDataTableRows", DOM);
const uint32_t count = aIndexValues.Length();
if (!count) {
return NS_OK;
}
auto deleteUniqueStmt = DatabaseConnection::LazyStatement{
*aConnection, "DELETE FROM unique_index_data WHERE index_id = :"_ns +
kStmtParamNameIndexId + " AND value = :"_ns +
kStmtParamNameValue + ";"_ns};
auto deleteStmt = DatabaseConnection::LazyStatement{
*aConnection, "DELETE FROM index_data WHERE index_id = :"_ns +
kStmtParamNameIndexId + " AND value = :"_ns +
kStmtParamNameValue + " AND object_data_key = :"_ns +
kStmtParamNameObjectDataKey + ";"_ns};
for (uint32_t index = 0; index < count; index++) {
const IndexDataValue& indexValue = aIndexValues[index];
auto& stmt = indexValue.mUnique ? deleteUniqueStmt : deleteStmt;
QM_TRY_INSPECT(const auto& borrowedStmt, stmt.Borrow());
QM_TRY(MOZ_TO_RESULT(borrowedStmt->BindInt64ByName(kStmtParamNameIndexId,
indexValue.mIndexId)));
QM_TRY(MOZ_TO_RESULT(indexValue.mPosition.BindToStatement(
&*borrowedStmt, kStmtParamNameValue)));
if (!indexValue.mUnique) {
QM_TRY(MOZ_TO_RESULT(aObjectStoreKey.BindToStatement(
&*borrowedStmt, kStmtParamNameObjectDataKey)));
}
QM_TRY(MOZ_TO_RESULT(borrowedStmt->Execute()));
}
return NS_OK;
}
// static
nsresult DatabaseOperationBase::DeleteObjectStoreDataTableRowsWithIndexes(
DatabaseConnection* aConnection, const IndexOrObjectStoreId aObjectStoreId,
const Maybe<SerializedKeyRange>& aKeyRange) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(aObjectStoreId);
#ifdef DEBUG
{
QM_TRY_INSPECT(const bool& hasIndexes,
ObjectStoreHasIndexes(*aConnection, aObjectStoreId),
QM_PROPAGATE, [](const auto&) { MOZ_ASSERT(false); });
MOZ_ASSERT(hasIndexes,
"Don't use this slow method if there are no indexes!");
}
#endif
AUTO_PROFILER_LABEL(
"DatabaseOperationBase::DeleteObjectStoreDataTableRowsWithIndexes", DOM);
const bool singleRowOnly = aKeyRange.isSome() && aKeyRange.ref().isOnly();
const auto keyRangeClause =
MaybeGetBindingClauseForKeyRange(aKeyRange, kColumnNameKey);
Key objectStoreKey;
QM_TRY_INSPECT(
const auto& selectStmt,
([singleRowOnly, &aConnection, &objectStoreKey, &aKeyRange,
&keyRangeClause]()
-> Result<CachingDatabaseConnection::BorrowedStatement, nsresult> {
if (singleRowOnly) {
QM_TRY_UNWRAP(auto selectStmt,
aConnection->BorrowCachedStatement(
"SELECT index_data_values "
"FROM object_data "
"WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + " AND key = :"_ns +
kStmtParamNameKey + ";"_ns));
objectStoreKey = aKeyRange.ref().lower();
QM_TRY(MOZ_TO_RESULT(
objectStoreKey.BindToStatement(&*selectStmt, kStmtParamNameKey)));
return selectStmt;
}
QM_TRY_UNWRAP(
auto selectStmt,
aConnection->BorrowCachedStatement(
"SELECT index_data_values, "_ns + kColumnNameKey +
" FROM object_data WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + keyRangeClause + ";"_ns));
if (aKeyRange.isSome()) {
QM_TRY(MOZ_TO_RESULT(
BindKeyRangeToStatement(aKeyRange.ref(), &*selectStmt)));
}
return selectStmt;
}()));
QM_TRY(MOZ_TO_RESULT(selectStmt->BindInt64ByName(kStmtParamNameObjectStoreId,
aObjectStoreId)));
DebugOnly<uint32_t> resultCountDEBUG = 0;
QM_TRY(CollectWhileHasResult(
*selectStmt,
[singleRowOnly, &objectStoreKey, &aConnection, &resultCountDEBUG,
indexValues = IndexDataValuesAutoArray{}](
auto& selectStmt) mutable -> Result<Ok, nsresult> {
if (!singleRowOnly) {
QM_TRY(
MOZ_TO_RESULT(objectStoreKey.SetFromStatement(&selectStmt, 1)));
indexValues.ClearAndRetainStorage();
}
QM_TRY(MOZ_TO_RESULT(
ReadCompressedIndexDataValues(selectStmt, 0, indexValues)));
QM_TRY(MOZ_TO_RESULT(DeleteIndexDataTableRows(
aConnection, objectStoreKey, indexValues)));
resultCountDEBUG++;
return Ok{};
}));
MOZ_ASSERT_IF(singleRowOnly, resultCountDEBUG <= 1);
QM_TRY_UNWRAP(
auto deleteManyStmt,
aConnection->BorrowCachedStatement(
"DELETE FROM object_data "_ns + "WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + keyRangeClause + ";"_ns));
QM_TRY(MOZ_TO_RESULT(deleteManyStmt->BindInt64ByName(
kStmtParamNameObjectStoreId, aObjectStoreId)));
if (aKeyRange.isSome()) {
QM_TRY(MOZ_TO_RESULT(
BindKeyRangeToStatement(aKeyRange.ref(), &*deleteManyStmt)));
}
QM_TRY(MOZ_TO_RESULT(deleteManyStmt->Execute()));
return NS_OK;
}
// static
nsresult DatabaseOperationBase::UpdateIndexValues(
DatabaseConnection* aConnection, const IndexOrObjectStoreId aObjectStoreId,
const Key& aObjectStoreKey, const nsTArray<IndexDataValue>& aIndexValues) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(!aObjectStoreKey.IsUnset());
AUTO_PROFILER_LABEL("DatabaseOperationBase::UpdateIndexValues", DOM);
QM_TRY_UNWRAP((auto [indexDataValues, indexDataValuesLength]),
MakeCompressedIndexDataValues(aIndexValues));
MOZ_ASSERT(!indexDataValuesLength == !(indexDataValues.get()));
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"UPDATE object_data SET index_data_values = :"_ns +
kStmtParamNameIndexDataValues + " WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + " AND key = :"_ns + kStmtParamNameKey +
";"_ns,
[&indexDataValues = indexDataValues,
indexDataValuesLength = indexDataValuesLength, aObjectStoreId,
&aObjectStoreKey](
mozIStorageStatement& updateStmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(
indexDataValues
? updateStmt.BindAdoptedBlobByName(
kStmtParamNameIndexDataValues, indexDataValues.release(),
indexDataValuesLength)
: updateStmt.BindNullByName(kStmtParamNameIndexDataValues)));
QM_TRY(MOZ_TO_RESULT(updateStmt.BindInt64ByName(
kStmtParamNameObjectStoreId, aObjectStoreId)));
QM_TRY(MOZ_TO_RESULT(
aObjectStoreKey.BindToStatement(&updateStmt, kStmtParamNameKey)));
return Ok{};
})));
return NS_OK;
}
// static
Result<bool, nsresult> DatabaseOperationBase::ObjectStoreHasIndexes(
DatabaseConnection& aConnection,
const IndexOrObjectStoreId aObjectStoreId) {
aConnection.AssertIsOnConnectionThread();
MOZ_ASSERT(aObjectStoreId);
QM_TRY_RETURN(aConnection
.BorrowAndExecuteSingleStepStatement(
"SELECT id "
"FROM object_store_index "
"WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + kOpenLimit + "1;"_ns,
[aObjectStoreId](auto& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByName(
kStmtParamNameObjectStoreId, aObjectStoreId)));
return Ok{};
})
.map(IsSome));
}
NS_IMPL_ISUPPORTS_INHERITED(DatabaseOperationBase, Runnable,
mozIStorageProgressHandler)
NS_IMETHODIMP
DatabaseOperationBase::OnProgress(mozIStorageConnection* aConnection,
bool* _retval) {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(_retval);
// This is intentionally racy.
*_retval = QuotaClient::IsShuttingDownOnNonBackgroundThread() ||
!OperationMayProceed();
return NS_OK;
}
DatabaseOperationBase::AutoSetProgressHandler::AutoSetProgressHandler()
: mConnection(Nothing())
#ifdef DEBUG
,
mDEBUGDatabaseOp(nullptr)
#endif
{
MOZ_ASSERT(!IsOnBackgroundThread());
}
DatabaseOperationBase::AutoSetProgressHandler::~AutoSetProgressHandler() {
MOZ_ASSERT(!IsOnBackgroundThread());
if (mConnection) {
Unregister();
}
}
nsresult DatabaseOperationBase::AutoSetProgressHandler::Register(
mozIStorageConnection& aConnection, DatabaseOperationBase* aDatabaseOp) {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aDatabaseOp);
MOZ_ASSERT(!mConnection);
QM_TRY_UNWRAP(
const DebugOnly oldProgressHandler,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageProgressHandler>, aConnection, SetProgressHandler,
kStorageProgressGranularity, aDatabaseOp));
MOZ_ASSERT(!oldProgressHandler.inspect());
mConnection = SomeRef(aConnection);
#ifdef DEBUG
mDEBUGDatabaseOp = aDatabaseOp;
#endif
return NS_OK;
}
void DatabaseOperationBase::AutoSetProgressHandler::Unregister() {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(mConnection);
nsCOMPtr<mozIStorageProgressHandler> oldHandler;
MOZ_ALWAYS_SUCCEEDS(
mConnection->RemoveProgressHandler(getter_AddRefs(oldHandler)));
MOZ_ASSERT(oldHandler == mDEBUGDatabaseOp);
mConnection = Nothing();
}
FactoryOp::FactoryOp(SafeRefPtr<Factory> aFactory,
const Maybe<ContentParentId>& aContentParentId,
const PersistenceType aPersistenceType,
const PrincipalInfo& aPrincipalInfo,
const Maybe<nsString>& aDatabaseName, bool aDeleting)
: DatabaseOperationBase(aFactory->GetLoggingInfo()->Id(),
aFactory->GetLoggingInfo()->NextRequestSN()),
mFactory(std::move(aFactory)),
mContentParentId(aContentParentId),
mPrincipalInfo(aPrincipalInfo),
mDatabaseName(aDatabaseName),
mDirectoryLockId(-1),
mPersistenceType(aPersistenceType),
mState(State::Initial),
mWaitingForPermissionRetry(false),
mEnforcingQuota(true),
mDeleting(aDeleting) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mFactory);
MOZ_ASSERT(!QuotaClient::IsShuttingDownOnBackgroundThread());
}
nsresult FactoryOp::DispatchThisAfterProcessingCurrentEvent(
nsCOMPtr<nsIEventTarget> aEventTarget) {
QM_TRY(MOZ_TO_RESULT(RunAfterProcessingCurrentEvent(
[eventTarget = std::move(aEventTarget), self = RefPtr(this)]() mutable {
QM_WARNONLY_TRY(MOZ_TO_RESULT(
eventTarget->Dispatch(self.forget(), NS_DISPATCH_NORMAL)));
})));
return NS_OK;
}
void FactoryOp::NoteDatabaseBlocked(Database* aDatabase) {
AssertIsOnOwningThread();
MOZ_ASSERT(aDatabase);
MOZ_ASSERT(mState == State::WaitingForOtherDatabasesToClose);
MOZ_ASSERT(!mMaybeBlockedDatabases.IsEmpty());
MOZ_ASSERT(mMaybeBlockedDatabases.Contains(aDatabase));
// Only send the blocked event if all databases have reported back. If the
// database was closed then it will have been removed from the array.
// Otherwise if it was blocked its |mBlocked| flag will be true.
bool sendBlockedEvent = true;
for (auto& info : mMaybeBlockedDatabases) {
if (info == aDatabase) {
// This database was blocked, mark accordingly.
info.mBlocked = true;
} else if (!info.mBlocked) {
// A database has not yet reported back yet, don't send the event yet.
sendBlockedEvent = false;
}
}
if (sendBlockedEvent) {
SendBlockedNotification();
}
}
void FactoryOp::NoteDatabaseClosed(Database* const aDatabase) {
AssertIsOnOwningThread();
MOZ_ASSERT(aDatabase);
MOZ_ASSERT(mState == State::WaitingForOtherDatabasesToClose);
MOZ_ASSERT(!mMaybeBlockedDatabases.IsEmpty());
MOZ_ASSERT(mMaybeBlockedDatabases.Contains(aDatabase));
mMaybeBlockedDatabases.RemoveElement(aDatabase);
if (!mMaybeBlockedDatabases.IsEmpty()) {
return;
}
DatabaseActorInfo* info;
MOZ_ALWAYS_TRUE(gLiveDatabaseHashtable->Get(mDatabaseId.ref(), &info));
MOZ_ASSERT(info->mWaitingFactoryOp == this);
if (AreActorsAlive()) {
// The IPDL strong reference has not yet been released, so we can clear
// mWaitingFactoryOp immediately.
info->mWaitingFactoryOp = nullptr;
WaitForTransactions();
return;
}
// The IPDL strong reference has been released, mWaitingFactoryOp holds the
// last strong reference to us, so we need to move it to a stack variable
// instead of clearing it immediately (We could clear it immediately if only
// the other actor is destroyed, but we don't need to optimize for that, and
// move it anyway).
const RefPtr<FactoryOp> waitingFactoryOp = std::move(info->mWaitingFactoryOp);
IDB_REPORT_INTERNAL_ERR();
SetFailureCodeIfUnset(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
// We hold a strong ref in waitingFactoryOp, so it's safe to call Run()
// directly.
mState = State::SendingResults;
MOZ_ALWAYS_SUCCEEDS(Run());
}
void FactoryOp::StringifyState(nsACString& aResult) const {
AssertIsOnOwningThread();
switch (mState) {
case State::Initial:
aResult.AppendLiteral("Initial");
return;
case State::DirectoryOpenPending:
aResult.AppendLiteral("DirectoryOpenPending");
return;
case State::DirectoryWorkOpen:
aResult.AppendLiteral("DirectoryWorkOpen");
return;
case State::DirectoryWorkDone:
aResult.AppendLiteral("DirectoryWorkDone");
return;
case State::DatabaseOpenPending:
aResult.AppendLiteral("DatabaseOpenPending");
return;
case State::DatabaseWorkOpen:
aResult.AppendLiteral("DatabaseWorkOpen");
return;
case State::BeginVersionChange:
aResult.AppendLiteral("BeginVersionChange");
return;
case State::WaitingForOtherDatabasesToClose:
aResult.AppendLiteral("WaitingForOtherDatabasesToClose");
return;
case State::WaitingForTransactionsToComplete:
aResult.AppendLiteral("WaitingForTransactionsToComplete");
return;
case State::DatabaseWorkVersionChange:
aResult.AppendLiteral("DatabaseWorkVersionChange");
return;
case State::SendingResults:
aResult.AppendLiteral("SendingResults");
return;
case State::Completed:
aResult.AppendLiteral("Completed");
return;
default:
MOZ_CRASH("Bad state!");
}
}
void FactoryOp::Stringify(nsACString& aResult) const {
AssertIsOnOwningThread();
aResult.AppendLiteral("PersistenceType:");
aResult.Append(PersistenceTypeToString(mPersistenceType));
aResult.Append(kQuotaGenericDelimiter);
aResult.AppendLiteral("Origin:");
aResult.Append(AnonymizedOriginString(mOriginMetadata.mOrigin));
aResult.Append(kQuotaGenericDelimiter);
aResult.AppendLiteral("State:");
StringifyState(aResult);
}
nsresult FactoryOp::Open() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::Initial);
MOZ_ASSERT(mOriginMetadata.mOrigin.IsEmpty());
MOZ_ASSERT(!mDirectoryLockHandle);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsActorDestroyed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
QM_TRY(QuotaManager::EnsureCreated());
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
QM_TRY_UNWRAP(
auto principalMetadata,
quota::GetInfoFromValidatedPrincipalInfo(*quotaManager, mPrincipalInfo));
mOriginMetadata = {std::move(principalMetadata), mPersistenceType};
if (mPrincipalInfo.type() == PrincipalInfo::TSystemPrincipalInfo) {
MOZ_ASSERT(mPersistenceType == PERSISTENCE_TYPE_PERSISTENT);
mEnforcingQuota = false;
} else if (mPrincipalInfo.type() == PrincipalInfo::TContentPrincipalInfo) {
const ContentPrincipalInfo& contentPrincipalInfo =
mPrincipalInfo.get_ContentPrincipalInfo();
MOZ_ASSERT_IF(
QuotaManager::IsOriginInternal(contentPrincipalInfo.originNoSuffix()),
mPersistenceType == PERSISTENCE_TYPE_PERSISTENT);
mEnforcingQuota = mPersistenceType != PERSISTENCE_TYPE_PERSISTENT;
if (mOriginMetadata.mIsPrivate) {
if (StaticPrefs::dom_indexedDB_privateBrowsing_enabled()) {
// Explicitly disallow moz-extension urls from using the encrypted
// indexedDB storage mode when the caller is an extension (see Bug
// 1841806).
if (StringBeginsWith(contentPrincipalInfo.originNoSuffix(),
"moz-extension:"_ns)) {
return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
}
mInPrivateBrowsing.Flip();
} else {
return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
}
}
} else {
MOZ_ASSERT(false);
}
if (mDatabaseName.isSome()) {
nsCString databaseId;
QuotaManager::GetStorageId(mPersistenceType, mOriginMetadata.mOrigin,
Client::IDB, databaseId);
databaseId.Append('*');
databaseId.Append(NS_ConvertUTF16toUTF8(mDatabaseName.ref()));
mDatabaseId = Some(std::move(databaseId));
// Need to get database file path before opening the directory.
// XXX: For what reason?
QM_TRY_UNWRAP(
auto databaseFilePath,
([this, quotaManager]() -> mozilla::Result<nsString, nsresult> {
QM_TRY_INSPECT(const auto& dbFile,
quotaManager->GetOriginDirectory(mOriginMetadata));
QM_TRY(MOZ_TO_RESULT(dbFile->Append(
NS_LITERAL_STRING_FROM_CSTRING(IDB_DIRECTORY_NAME))));
QM_TRY(MOZ_TO_RESULT(dbFile->Append(
GetDatabaseFilenameBase(mDatabaseName.ref(),
mOriginMetadata.mIsPrivate) +
kSQLiteSuffix)));
QM_TRY_RETURN(
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsString, dbFile, GetPath));
}()));
mDatabaseFilePath = Some(std::move(databaseFilePath));
}
// Open directory
mState = State::DirectoryOpenPending;
quotaManager->OpenClientDirectory({mOriginMetadata, Client::IDB})
->Then(
GetCurrentSerialEventTarget(), __func__,
[self = RefPtr(this)](QuotaManager::ClientDirectoryLockHandlePromise::
ResolveOrRejectValue&& aValue) {
if (aValue.IsResolve()) {
self->DirectoryLockAcquired(std::move(aValue.ResolveValue()));
} else {
self->DirectoryLockFailed();
}
});
return NS_OK;
}
nsresult FactoryOp::DirectoryOpen() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DirectoryOpenPending);
MOZ_ASSERT(mDirectoryLockHandle);
if (mDatabaseName.isNothing()) {
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
// Must set this before dispatching otherwise we will race with the IO
// thread.
mState = State::DirectoryWorkOpen;
QM_TRY(MOZ_TO_RESULT(
quotaManager->IOThread()->Dispatch(this, NS_DISPATCH_NORMAL)),
NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR, IDB_REPORT_INTERNAL_ERR_LAMBDA);
return NS_OK;
}
mState = State::DirectoryWorkDone;
MOZ_ALWAYS_SUCCEEDS(Run());
return NS_OK;
}
nsresult FactoryOp::DirectoryWorkDone() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DirectoryWorkDone);
MOZ_ASSERT(mDirectoryLockHandle);
MOZ_ASSERT(gFactoryOps);
// See if this FactoryOp needs to wait.
const bool blocked = [&self = *this] {
bool foundThis = false;
bool blocked = false;
// XXX LinkedList should support reverse iteration via rbegin() and rend(),
// see bug 1964967.
for (FactoryOp* existingOp = gFactoryOps->getLast(); existingOp;
existingOp = existingOp->getPrevious()) {
if (existingOp == &self) {
foundThis = true;
continue;
}
if (foundThis && self.MustWaitFor(*existingOp)) {
existingOp->AddBlockingOp(self);
self.AddBlockedOnOp(*existingOp);
blocked = true;
}
}
return blocked;
}() || [&self = *this] {
QuotaClient* quotaClient = QuotaClient::GetInstance();
MOZ_ASSERT(quotaClient);
if (RefPtr<Maintenance> currentMaintenance =
quotaClient->GetCurrentMaintenance()) {
if (self.mDatabaseName.isSome()) {
if (RefPtr<DatabaseMaintenance> databaseMaintenance =
currentMaintenance->GetDatabaseMaintenance(
self.mDatabaseFilePath.ref())) {
databaseMaintenance->WaitForCompletion(&self);
return true;
}
} else if (currentMaintenance->HasDatabaseMaintenances()) {
currentMaintenance->WaitForCompletion(&self);
return true;
}
}
return false;
}();
mState = State::DatabaseOpenPending;
if (!blocked) {
QM_TRY(MOZ_TO_RESULT(DatabaseOpen()));
}
return NS_OK;
}
nsresult FactoryOp::SendToIOThread() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DatabaseOpenPending);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
!OperationMayProceed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
// Must set this before dispatching otherwise we will race with the IO thread.
mState = State::DatabaseWorkOpen;
QM_TRY(MOZ_TO_RESULT(
quotaManager->IOThread()->Dispatch(this, NS_DISPATCH_NORMAL)),
NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR, IDB_REPORT_INTERNAL_ERR_LAMBDA);
NotifyDatabaseWorkStarted();
return NS_OK;
}
void FactoryOp::WaitForTransactions() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::BeginVersionChange ||
mState == State::WaitingForOtherDatabasesToClose);
MOZ_ASSERT(!mDatabaseId.ref().IsEmpty());
MOZ_ASSERT(!IsActorDestroyed());
mState = State::WaitingForTransactionsToComplete;
RefPtr<WaitForTransactionsHelper> helper =
new WaitForTransactionsHelper(mDatabaseId.ref(), this);
helper->WaitForTransactions();
}
void FactoryOp::CleanupMetadata() {
AssertIsOnOwningThread();
for (const NotNull<RefPtr<FactoryOp>>& blockingOp : mBlocking) {
blockingOp->MaybeUnblock(*this);
}
mBlocking.Clear();
MOZ_ASSERT(gFactoryOps);
removeFrom(*gFactoryOps);
// We might get here even after QuotaManagerOpen failed, so we need to check
// if we have a quota manager.
quota::QuotaManager::SafeMaybeRecordQuotaClientShutdownStep(
quota::Client::IDB, "An element was removed from gFactoryOps"_ns);
// Match the IncreaseBusyCount in AllocPBackgroundIDBFactoryRequestParent().
DecreaseBusyCount();
}
void FactoryOp::FinishSendResults() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::SendingResults);
MOZ_ASSERT(mFactory);
mState = State::Completed;
// Make sure to release the factory on this thread.
mFactory = nullptr;
}
nsresult FactoryOp::SendVersionChangeMessages(
DatabaseActorInfo* aDatabaseActorInfo, Maybe<Database&> aOpeningDatabase,
uint64_t aOldVersion, const Maybe<uint64_t>& aNewVersion) {
AssertIsOnOwningThread();
MOZ_ASSERT(aDatabaseActorInfo);
MOZ_ASSERT(mState == State::BeginVersionChange);
MOZ_ASSERT(mMaybeBlockedDatabases.IsEmpty());
MOZ_ASSERT(!IsActorDestroyed());
const uint32_t expectedCount = mDeleting ? 0 : 1;
const uint32_t liveCount = aDatabaseActorInfo->mLiveDatabases.length();
if (liveCount > expectedCount) {
nsTArray<MaybeBlockedDatabaseInfo> maybeBlockedDatabases;
for (Database* const database : aDatabaseActorInfo->mLiveDatabases) {
if ((!aOpeningDatabase || database != &aOpeningDatabase.ref()) &&
!database->IsClosed() &&
NS_WARN_IF(!maybeBlockedDatabases.AppendElement(
SafeRefPtr{database, AcquireStrongRefFromRawPtr{}}, fallible))) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
mMaybeBlockedDatabases = std::move(maybeBlockedDatabases);
}
// We don't want to wait forever if we were not able to send the
// message.
mMaybeBlockedDatabases.RemoveLastElements(
mMaybeBlockedDatabases.end() -
std::remove_if(mMaybeBlockedDatabases.begin(),
mMaybeBlockedDatabases.end(),
[aOldVersion, &aNewVersion](auto& maybeBlockedDatabase) {
return !maybeBlockedDatabase->SendVersionChange(
aOldVersion, aNewVersion);
}));
return NS_OK;
} // namespace indexedDB
bool FactoryOp::MustWaitFor(const FactoryOp& aExistingOp) {
AssertIsOnOwningThread();
// If the persistence types don't overlap, the op can proceed.
if (aExistingOp.mPersistenceType != mPersistenceType) {
return false;
}
// If the origins don't overlap, the op can proceed.
if (aExistingOp.mOriginMetadata.mOrigin != mOriginMetadata.mOrigin) {
return false;
}
// If the database ids don't overlap, the op can proceed.
if (!aExistingOp.mDatabaseId.isNothing() && !mDatabaseId.isNothing() &&
aExistingOp.mDatabaseId.ref() != mDatabaseId.ref()) {
return false;
}
return true;
}
// Run() assumes that the caller holds a strong reference to the object that
// can't be cleared while Run() is being executed.
// So if you call Run() directly (as opposed to dispatching to an event queue)
// you need to make sure there's such a reference.
// See bug 1356824 for more details.
NS_IMETHODIMP
FactoryOp::Run() {
const auto handleError = [this](const nsresult rv) {
if (mState != State::SendingResults) {
SetFailureCodeIfUnset(rv);
// Must set mState before dispatching otherwise we will race with the
// owning thread.
mState = State::SendingResults;
if (IsOnOwningThread()) {
SendResults();
} else {
MOZ_ALWAYS_SUCCEEDS(
DispatchThisAfterProcessingCurrentEvent(mOwningEventTarget));
}
}
};
switch (mState) {
case State::Initial:
QM_WARNONLY_TRY(MOZ_TO_RESULT(Open()), handleError);
break;
case State::DirectoryWorkOpen:
QM_WARNONLY_TRY(MOZ_TO_RESULT(DoDirectoryWork()), handleError);
break;
case State::DirectoryWorkDone:
QM_WARNONLY_TRY(MOZ_TO_RESULT(DirectoryWorkDone()), handleError);
break;
case State::DatabaseOpenPending:
QM_WARNONLY_TRY(MOZ_TO_RESULT(DatabaseOpen()), handleError);
break;
case State::DatabaseWorkOpen:
QM_WARNONLY_TRY(MOZ_TO_RESULT(DoDatabaseWork()), handleError);
break;
case State::BeginVersionChange:
QM_WARNONLY_TRY(MOZ_TO_RESULT(BeginVersionChange()), handleError);
break;
case State::WaitingForTransactionsToComplete:
QM_WARNONLY_TRY(MOZ_TO_RESULT(DispatchToWorkThread()), handleError);
break;
case State::DatabaseWorkVersionUpdate:
QM_WARNONLY_TRY(MOZ_TO_RESULT(DoVersionUpdate()), handleError);
break;
case State::SendingResults:
SendResults();
break;
default:
MOZ_CRASH("Bad state!");
}
return NS_OK;
}
void FactoryOp::DirectoryLockAcquired(ClientDirectoryLockHandle aLockHandle) {
AssertIsOnOwningThread();
MOZ_ASSERT(aLockHandle);
MOZ_ASSERT(mState == State::DirectoryOpenPending);
MOZ_ASSERT(!mDirectoryLockHandle);
mDirectoryLockHandle = std::move(aLockHandle);
MOZ_ASSERT(mDirectoryLockHandle->Id() >= 0);
mDirectoryLockId = mDirectoryLockHandle->Id();
auto cleanupAndReturn = [self = RefPtr(this)](const nsresult rv) {
self->SetFailureCodeIfUnset(rv);
// The caller holds a strong reference to us, no need for a self reference
// before calling Run().
self->mState = State::SendingResults;
MOZ_ALWAYS_SUCCEEDS(self->Run());
};
if (mDirectoryLockHandle->Invalidated()) {
return cleanupAndReturn(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
}
QM_WARNONLY_TRY(MOZ_TO_RESULT(DirectoryOpen()), cleanupAndReturn);
}
void FactoryOp::DirectoryLockFailed() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DirectoryOpenPending);
MOZ_ASSERT(!mDirectoryLockHandle);
if (!HasFailed()) {
IDB_REPORT_INTERNAL_ERR();
SetFailureCode(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
}
// The caller holds a strong reference to us, no need for a self reference
// before calling Run().
mState = State::SendingResults;
MOZ_ALWAYS_SUCCEEDS(Run());
}
nsresult FactoryRequestOp::DoDirectoryWork() {
MOZ_CRASH("Not implemented because this should be unreachable.");
}
void FactoryRequestOp::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnBackgroundThread();
NoteActorDestroyed();
}
OpenDatabaseOp::OpenDatabaseOp(SafeRefPtr<Factory> aFactory,
const Maybe<ContentParentId>& aContentParentId,
const CommonFactoryRequestParams& aParams)
: FactoryRequestOp(std::move(aFactory), aContentParentId, aParams,
/* aDeleting */ false),
mMetadata(MakeSafeRefPtr<FullDatabaseMetadata>(aParams.metadata())),
mRequestedVersion(aParams.metadata().version()),
mVersionChangeOp(nullptr),
mTelemetryId(0) {}
void OpenDatabaseOp::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnOwningThread();
FactoryRequestOp::ActorDestroy(aWhy);
if (mVersionChangeOp) {
mVersionChangeOp->NoteActorDestroyed();
}
}
nsresult OpenDatabaseOp::DatabaseOpen() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DatabaseOpenPending);
nsresult rv = SendToIOThread();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
nsresult OpenDatabaseOp::DoDatabaseWork() {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State::DatabaseWorkOpen);
AUTO_PROFILER_LABEL("OpenDatabaseOp::DoDatabaseWork", DOM);
QM_TRY(OkIf(!QuotaClient::IsShuttingDownOnNonBackgroundThread()),
NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR, IDB_REPORT_INTERNAL_ERR_LAMBDA);
if (!OperationMayProceed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
const nsAString& databaseName = mCommonParams.metadata().name();
const PersistenceType persistenceType =
mCommonParams.metadata().persistenceType();
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
QM_TRY_INSPECT(
const auto& dbDirectory,
([persistenceType, "aManager,
this]() -> mozilla::Result<nsCOMPtr<nsIFile>, nsresult> {
if (persistenceType == PERSISTENCE_TYPE_PERSISTENT) {
QM_TRY_RETURN(quotaManager->GetOriginDirectory(mOriginMetadata));
}
QM_TRY_RETURN(
quotaManager->GetOrCreateTemporaryOriginDirectory(mOriginMetadata));
}()));
QM_TRY(MOZ_TO_RESULT(
dbDirectory->Append(NS_LITERAL_STRING_FROM_CSTRING(IDB_DIRECTORY_NAME))));
{
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(dbDirectory, Exists));
if (!exists) {
QM_TRY(MOZ_TO_RESULT(dbDirectory->Create(nsIFile::DIRECTORY_TYPE, 0755)));
}
#ifdef DEBUG
else {
bool isDirectory;
MOZ_ASSERT(NS_SUCCEEDED(dbDirectory->IsDirectory(&isDirectory)));
MOZ_ASSERT(isDirectory);
}
#endif
}
const auto databaseFilenameBase =
GetDatabaseFilenameBase(databaseName, mOriginMetadata.mIsPrivate);
QM_TRY_INSPECT(const auto& markerFile,
CloneFileAndAppend(*dbDirectory, kIdbDeletionMarkerFilePrefix +
databaseFilenameBase));
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(markerFile, Exists));
if (exists) {
// Delete the database and directroy since they should be deleted in
// previous operation.
// Note: only update usage to the QuotaManager when mEnforcingQuota == true
QM_TRY(MOZ_TO_RESULT(RemoveDatabaseFilesAndDirectory(
*dbDirectory, databaseFilenameBase,
mEnforcingQuota ? quotaManager : nullptr, persistenceType,
mOriginMetadata, databaseName)));
}
QM_TRY_INSPECT(
const auto& dbFile,
CloneFileAndAppend(*dbDirectory, databaseFilenameBase + kSQLiteSuffix));
mTelemetryId = TelemetryIdForFile(dbFile);
#ifdef DEBUG
{
QM_TRY_INSPECT(
const auto& databaseFilePath,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsString, dbFile, GetPath));
MOZ_ASSERT(databaseFilePath == mDatabaseFilePath.ref());
}
#endif
QM_TRY_INSPECT(
const auto& fmDirectory,
CloneFileAndAppend(*dbDirectory, databaseFilenameBase +
kFileManagerDirectoryNameSuffix));
IndexedDatabaseManager* const idm = IndexedDatabaseManager::Get();
MOZ_ASSERT(idm);
SafeRefPtr<DatabaseFileManager> fileManager = idm->GetFileManager(
persistenceType, mOriginMetadata.mOrigin, databaseName);
if (!fileManager) {
fileManager = MakeSafeRefPtr<DatabaseFileManager>(
persistenceType, mOriginMetadata, databaseName, mDatabaseId.ref(),
mDatabaseFilePath.ref(), mEnforcingQuota, mInPrivateBrowsing);
}
Maybe<const CipherKey> maybeKey =
mInPrivateBrowsing
? Some(fileManager->MutableCipherKeyManagerRef().Ensure())
: Nothing();
MOZ_RELEASE_ASSERT(mInPrivateBrowsing == maybeKey.isSome());
QM_TRY_UNWRAP(
NotNull<nsCOMPtr<mozIStorageConnection>> connection,
CreateStorageConnection(*dbFile, *fmDirectory, databaseName,
mOriginMetadata.mOrigin, mDirectoryLockId,
mTelemetryId, maybeKey));
AutoSetProgressHandler asph;
QM_TRY(MOZ_TO_RESULT(asph.Register(*connection, this)));
QM_TRY(MOZ_TO_RESULT(LoadDatabaseInformation(*connection)));
MOZ_ASSERT(mMetadata->mNextObjectStoreId > mMetadata->mObjectStores.Count());
MOZ_ASSERT(mMetadata->mNextIndexId > 0);
// See if we need to do a versionchange transaction
// Optional version semantics.
if (!mRequestedVersion) {
// If the requested version was not specified and the database was created,
// treat it as if version 1 were requested.
// Otherwise, treat it as if the current version were requested.
mRequestedVersion = mMetadata->mCommonMetadata.version() == 0
? 1
: mMetadata->mCommonMetadata.version();
}
QM_TRY(OkIf(mMetadata->mCommonMetadata.version() <= mRequestedVersion),
NS_ERROR_DOM_INDEXEDDB_VERSION_ERR);
if (!fileManager->Initialized()) {
QM_TRY(MOZ_TO_RESULT(fileManager->Init(
fmDirectory, mMetadata->mCommonMetadata.version(), *connection)));
idm->AddFileManager(fileManager.clonePtr());
}
mFileManager = std::move(fileManager);
// Must close connection before dispatching otherwise we might race with the
// connection thread which needs to open the same database.
asph.Unregister();
MOZ_ALWAYS_SUCCEEDS(connection->Close());
SleepIfEnabled(
StaticPrefs::dom_indexedDB_databaseInitialization_pauseOnIOThreadMs());
// Must set mState before dispatching otherwise we will race with the owning
// thread.
mState = (mMetadata->mCommonMetadata.version() == mRequestedVersion)
? State::SendingResults
: State::BeginVersionChange;
QM_TRY(MOZ_TO_RESULT(
DispatchThisAfterProcessingCurrentEvent(mOwningEventTarget)));
return NS_OK;
}
nsresult OpenDatabaseOp::LoadDatabaseInformation(
mozIStorageConnection& aConnection) {
AssertIsOnIOThread();
MOZ_ASSERT(mMetadata);
{
// Load version information.
QM_TRY_INSPECT(
const auto& stmt,
CreateAndExecuteSingleStepStatement<
SingleStepResult::ReturnNullIfNoResult>(
aConnection, "SELECT name, origin, version FROM database"_ns));
QM_TRY(OkIf(stmt), NS_ERROR_FILE_CORRUPTED);
QM_TRY_INSPECT(const auto& databaseName, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, stmt, GetString, 0));
QM_TRY(OkIf(mCommonParams.metadata().name() == databaseName),
NS_ERROR_FILE_CORRUPTED);
QM_TRY_INSPECT(const auto& origin, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCString, stmt, GetUTF8String, 1));
// We can't just compare these strings directly. See bug 1339081 comment 69.
QM_TRY(OkIf(QuotaManager::AreOriginsEqualOnDisk(mOriginMetadata.mOrigin,
origin)),
NS_ERROR_FILE_CORRUPTED);
QM_TRY_INSPECT(const int64_t& version,
MOZ_TO_RESULT_INVOKE_MEMBER(stmt, GetInt64, 2));
mMetadata->mCommonMetadata.version() = uint64_t(version);
}
ObjectStoreTable& objectStores = mMetadata->mObjectStores;
QM_TRY_INSPECT(
const auto& lastObjectStoreId,
([&aConnection,
&objectStores]() -> mozilla::Result<IndexOrObjectStoreId, nsresult> {
// Load object store names and ids.
QM_TRY_INSPECT(
const auto& stmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>, aConnection, CreateStatement,
"SELECT id, auto_increment, name, key_path "
"FROM object_store"_ns));
IndexOrObjectStoreId lastObjectStoreId = 0;
QM_TRY(CollectWhileHasResult(
*stmt,
[&lastObjectStoreId, &objectStores,
usedIds = Maybe<nsTHashSet<uint64_t>>{},
usedNames = Maybe<nsTHashSet<nsString>>{}](
auto& stmt) mutable -> mozilla::Result<Ok, nsresult> {
QM_TRY_INSPECT(const IndexOrObjectStoreId& objectStoreId,
MOZ_TO_RESULT_INVOKE_MEMBER(stmt, GetInt64, 0));
if (!usedIds) {
usedIds.emplace();
}
QM_TRY(OkIf(objectStoreId > 0), Err(NS_ERROR_FILE_CORRUPTED));
QM_TRY(OkIf(!usedIds.ref().Contains(objectStoreId)),
Err(NS_ERROR_FILE_CORRUPTED));
QM_TRY(OkIf(usedIds.ref().Insert(objectStoreId, fallible)),
Err(NS_ERROR_OUT_OF_MEMORY));
nsString name;
QM_TRY(MOZ_TO_RESULT(stmt.GetString(2, name)));
if (!usedNames) {
usedNames.emplace();
}
QM_TRY(OkIf(!usedNames.ref().Contains(name)),
Err(NS_ERROR_FILE_CORRUPTED));
QM_TRY(OkIf(usedNames.ref().Insert(name, fallible)),
Err(NS_ERROR_OUT_OF_MEMORY));
ObjectStoreMetadata commonMetadata;
commonMetadata.id() = objectStoreId;
commonMetadata.name() = std::move(name);
QM_TRY_INSPECT(
const int32_t& columnType,
MOZ_TO_RESULT_INVOKE_MEMBER(stmt, GetTypeOfIndex, 3));
if (columnType == mozIStorageStatement::VALUE_TYPE_NULL) {
commonMetadata.keyPath() = KeyPath(0);
} else {
MOZ_ASSERT(columnType == mozIStorageStatement::VALUE_TYPE_TEXT);
nsString keyPathSerialization;
QM_TRY(MOZ_TO_RESULT(stmt.GetString(3, keyPathSerialization)));
commonMetadata.keyPath() =
KeyPath::DeserializeFromString(keyPathSerialization);
QM_TRY(OkIf(commonMetadata.keyPath().IsValid()),
Err(NS_ERROR_FILE_CORRUPTED));
}
QM_TRY_INSPECT(const int64_t& nextAutoIncrementId,
MOZ_TO_RESULT_INVOKE_MEMBER(stmt, GetInt64, 1));
commonMetadata.autoIncrement() = !!nextAutoIncrementId;
QM_TRY(OkIf(objectStores.InsertOrUpdate(
objectStoreId,
MakeSafeRefPtr<FullObjectStoreMetadata>(
std::move(commonMetadata),
FullObjectStoreMetadata::AutoIncrementIds{
nextAutoIncrementId, nextAutoIncrementId}),
fallible)),
Err(NS_ERROR_OUT_OF_MEMORY));
lastObjectStoreId = std::max(lastObjectStoreId, objectStoreId);
return Ok{};
}));
return lastObjectStoreId;
}()));
QM_TRY_INSPECT(
const auto& lastIndexId,
([this, &aConnection,
&objectStores]() -> mozilla::Result<IndexOrObjectStoreId, nsresult> {
// Load index information
QM_TRY_INSPECT(
const auto& stmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>, aConnection, CreateStatement,
"SELECT "
"id, object_store_id, name, key_path, "
"unique_index, multientry, "
"locale, is_auto_locale "
"FROM object_store_index"_ns));
IndexOrObjectStoreId lastIndexId = 0;
QM_TRY(CollectWhileHasResult(
*stmt,
[this, &lastIndexId, &objectStores, &aConnection,
usedIds = Maybe<nsTHashSet<uint64_t>>{},
usedNames = Maybe<nsTHashSet<nsString>>{}](
auto& stmt) mutable -> mozilla::Result<Ok, nsresult> {
QM_TRY_INSPECT(const IndexOrObjectStoreId& objectStoreId,
MOZ_TO_RESULT_INVOKE_MEMBER(stmt, GetInt64, 1));
// XXX Why does this return NS_ERROR_OUT_OF_MEMORY if we don't
// know the object store id?
auto objectStoreMetadata = objectStores.Lookup(objectStoreId);
QM_TRY(OkIf(static_cast<bool>(objectStoreMetadata)),
Err(NS_ERROR_OUT_OF_MEMORY));
MOZ_ASSERT((*objectStoreMetadata)->mCommonMetadata.id() ==
objectStoreId);
IndexOrObjectStoreId indexId;
QM_TRY(MOZ_TO_RESULT(stmt.GetInt64(0, &indexId)));
if (!usedIds) {
usedIds.emplace();
}
QM_TRY(OkIf(indexId > 0), Err(NS_ERROR_FILE_CORRUPTED));
QM_TRY(OkIf(!usedIds.ref().Contains(indexId)),
Err(NS_ERROR_FILE_CORRUPTED));
QM_TRY(OkIf(usedIds.ref().Insert(indexId, fallible)),
Err(NS_ERROR_OUT_OF_MEMORY));
nsString name;
QM_TRY(MOZ_TO_RESULT(stmt.GetString(2, name)));
const nsAutoString hashName =
IntToString(indexId) + u":"_ns + name;
if (!usedNames) {
usedNames.emplace();
}
QM_TRY(OkIf(!usedNames.ref().Contains(hashName)),
Err(NS_ERROR_FILE_CORRUPTED));
QM_TRY(OkIf(usedNames.ref().Insert(hashName, fallible)),
Err(NS_ERROR_OUT_OF_MEMORY));
auto indexMetadata = MakeSafeRefPtr<FullIndexMetadata>();
indexMetadata->mCommonMetadata.id() = indexId;
indexMetadata->mCommonMetadata.name() = name;
#ifdef DEBUG
{
int32_t columnType;
nsresult rv = stmt.GetTypeOfIndex(3, &columnType);
MOZ_ASSERT(NS_SUCCEEDED(rv));
MOZ_ASSERT(columnType != mozIStorageStatement::VALUE_TYPE_NULL);
}
#endif
nsString keyPathSerialization;
QM_TRY(MOZ_TO_RESULT(stmt.GetString(3, keyPathSerialization)));
indexMetadata->mCommonMetadata.keyPath() =
KeyPath::DeserializeFromString(keyPathSerialization);
QM_TRY(OkIf(indexMetadata->mCommonMetadata.keyPath().IsValid()),
Err(NS_ERROR_FILE_CORRUPTED));
int32_t scratch;
QM_TRY(MOZ_TO_RESULT(stmt.GetInt32(4, &scratch)));
indexMetadata->mCommonMetadata.unique() = !!scratch;
QM_TRY(MOZ_TO_RESULT(stmt.GetInt32(5, &scratch)));
indexMetadata->mCommonMetadata.multiEntry() = !!scratch;
const bool localeAware = !stmt.IsNull(6);
if (localeAware) {
QM_TRY(MOZ_TO_RESULT(stmt.GetUTF8String(
6, indexMetadata->mCommonMetadata.locale())));
QM_TRY(MOZ_TO_RESULT(stmt.GetInt32(7, &scratch)));
indexMetadata->mCommonMetadata.autoLocale() = !!scratch;
// Update locale-aware indexes if necessary
const nsCString& indexedLocale =
indexMetadata->mCommonMetadata.locale();
const bool& isAutoLocale =
indexMetadata->mCommonMetadata.autoLocale();
const nsCString& systemLocale = mFactory->GetSystemLocale();
if (!systemLocale.IsEmpty() && isAutoLocale &&
!indexedLocale.Equals(systemLocale)) {
QM_TRY(MOZ_TO_RESULT(UpdateLocaleAwareIndex(
aConnection, indexMetadata->mCommonMetadata,
systemLocale)));
}
}
QM_TRY(OkIf((*objectStoreMetadata)
->mIndexes.InsertOrUpdate(
indexId, std::move(indexMetadata), fallible)),
Err(NS_ERROR_OUT_OF_MEMORY));
lastIndexId = std::max(lastIndexId, indexId);
return Ok{};
}));
return lastIndexId;
}()));
QM_TRY(OkIf(lastObjectStoreId != INT64_MAX),
NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR, IDB_REPORT_INTERNAL_ERR_LAMBDA);
QM_TRY(OkIf(lastIndexId != INT64_MAX), NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR,
IDB_REPORT_INTERNAL_ERR_LAMBDA);
mMetadata->mNextObjectStoreId = lastObjectStoreId + 1;
mMetadata->mNextIndexId = lastIndexId + 1;
return NS_OK;
}
/* static */
nsresult OpenDatabaseOp::UpdateLocaleAwareIndex(
mozIStorageConnection& aConnection, const IndexMetadata& aIndexMetadata,
const nsCString& aLocale) {
const auto indexTable =
aIndexMetadata.unique() ? "unique_index_data"_ns : "index_data"_ns;
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
const nsCString readQuery = "SELECT value, object_data_key FROM "_ns +
indexTable + " WHERE index_id = :index_id"_ns;
QM_TRY_INSPECT(const auto& readStmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>, aConnection,
CreateStatement, readQuery));
QM_TRY(MOZ_TO_RESULT(readStmt->BindInt64ByIndex(0, aIndexMetadata.id())));
QM_TRY(CollectWhileHasResult(
*readStmt,
[&aConnection, &indexTable, &aIndexMetadata, &aLocale,
writeStmt = nsCOMPtr<mozIStorageStatement>{}](
auto& readStmt) mutable -> mozilla::Result<Ok, nsresult> {
if (!writeStmt) {
QM_TRY_UNWRAP(
writeStmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>, aConnection, CreateStatement,
"UPDATE "_ns + indexTable + "SET value_locale = :"_ns +
kStmtParamNameValueLocale + " WHERE index_id = :"_ns +
kStmtParamNameIndexId + " AND value = :"_ns +
kStmtParamNameValue + " AND object_data_key = :"_ns +
kStmtParamNameObjectDataKey));
}
mozStorageStatementScoper scoper(writeStmt);
QM_TRY(MOZ_TO_RESULT(writeStmt->BindInt64ByName(kStmtParamNameIndexId,
aIndexMetadata.id())));
Key oldKey, objectStorePosition;
QM_TRY(MOZ_TO_RESULT(oldKey.SetFromStatement(&readStmt, 0)));
QM_TRY(MOZ_TO_RESULT(
oldKey.BindToStatement(writeStmt, kStmtParamNameValue)));
QM_TRY_INSPECT(const auto& newSortKey,
oldKey.ToLocaleAwareKey(aLocale));
QM_TRY(MOZ_TO_RESULT(
newSortKey.BindToStatement(writeStmt, kStmtParamNameValueLocale)));
QM_TRY(
MOZ_TO_RESULT(objectStorePosition.SetFromStatement(&readStmt, 1)));
QM_TRY(MOZ_TO_RESULT(objectStorePosition.BindToStatement(
writeStmt, kStmtParamNameObjectDataKey)));
QM_TRY(MOZ_TO_RESULT(writeStmt->Execute()));
return Ok{};
}));
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
static constexpr auto metaQuery =
"UPDATE object_store_index SET "
"locale = :locale WHERE id = :id"_ns;
QM_TRY_INSPECT(const auto& metaStmt,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsCOMPtr<mozIStorageStatement>, aConnection,
CreateStatement, metaQuery));
QM_TRY(MOZ_TO_RESULT(
metaStmt->BindStringByIndex(0, NS_ConvertASCIItoUTF16(aLocale))));
QM_TRY(MOZ_TO_RESULT(metaStmt->BindInt64ByIndex(1, aIndexMetadata.id())));
QM_TRY(MOZ_TO_RESULT(metaStmt->Execute()));
return NS_OK;
}
nsresult OpenDatabaseOp::BeginVersionChange() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::BeginVersionChange);
MOZ_ASSERT(mMaybeBlockedDatabases.IsEmpty());
MOZ_ASSERT(mMetadata->mCommonMetadata.version() <= mRequestedVersion);
MOZ_ASSERT(!mDatabase);
MOZ_ASSERT(!mVersionChangeTransaction);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsActorDestroyed()) {
IDB_REPORT_INTERNAL_ERR();
QM_TRY(MOZ_TO_RESULT(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR));
}
EnsureDatabaseActor();
if (mDatabase->IsInvalidated()) {
IDB_REPORT_INTERNAL_ERR();
QM_TRY(MOZ_TO_RESULT(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR));
}
MOZ_ASSERT(!mDatabase->IsClosed());
DatabaseActorInfo* info;
MOZ_ALWAYS_TRUE(gLiveDatabaseHashtable->Get(mDatabaseId.ref(), &info));
MOZ_ASSERT(info->mLiveDatabases.contains(mDatabase.unsafeGetRawPtr()));
MOZ_ASSERT(!info->mWaitingFactoryOp);
MOZ_ASSERT(info->mMetadata == mMetadata);
auto transaction = MakeSafeRefPtr<VersionChangeTransaction>(this);
if (NS_WARN_IF(!transaction->CopyDatabaseMetadata())) {
return NS_ERROR_OUT_OF_MEMORY;
}
MOZ_ASSERT(info->mMetadata != mMetadata);
mMetadata = info->mMetadata.clonePtr();
const Maybe<uint64_t> newVersion = Some(mRequestedVersion);
QM_TRY(MOZ_TO_RESULT(SendVersionChangeMessages(
info, mDatabase.maybeDeref(), mMetadata->mCommonMetadata.version(),
newVersion)));
mVersionChangeTransaction = std::move(transaction);
if (mMaybeBlockedDatabases.IsEmpty()) {
// We don't need to wait on any databases, just jump to the transaction
// pool.
WaitForTransactions();
return NS_OK;
}
// If the actor gets destroyed, mWaitingFactoryOp will hold the last strong
// reference to us.
info->mWaitingFactoryOp = this;
mState = State::WaitingForOtherDatabasesToClose;
return NS_OK;
}
bool OpenDatabaseOp::AreActorsAlive() {
AssertIsOnOwningThread();
MOZ_ASSERT(mDatabase);
return !(IsActorDestroyed() || mDatabase->IsActorDestroyed());
}
void OpenDatabaseOp::SendBlockedNotification() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::WaitingForOtherDatabasesToClose);
if (!IsActorDestroyed()) {
Unused << SendBlocked(mMetadata->mCommonMetadata.version());
}
}
nsresult OpenDatabaseOp::DispatchToWorkThread() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::WaitingForTransactionsToComplete);
MOZ_ASSERT(mVersionChangeTransaction);
MOZ_ASSERT(mVersionChangeTransaction->GetMode() ==
IDBTransaction::Mode::VersionChange);
MOZ_ASSERT(mMaybeBlockedDatabases.IsEmpty());
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsActorDestroyed() || mDatabase->IsInvalidated()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
mState = State::DatabaseWorkVersionChange;
// Intentionally empty.
nsTArray<nsString> objectStoreNames;
const int64_t loggingSerialNumber =
mVersionChangeTransaction->LoggingSerialNumber();
const nsID& backgroundChildLoggingId =
mVersionChangeTransaction->GetLoggingInfo()->Id();
if (NS_WARN_IF(!mDatabase->RegisterTransaction(*mVersionChangeTransaction))) {
return NS_ERROR_OUT_OF_MEMORY;
}
if (!gConnectionPool) {
gConnectionPool = new ConnectionPool();
}
RefPtr<VersionChangeOp> versionChangeOp = new VersionChangeOp(this);
uint64_t transactionId = versionChangeOp->StartOnConnectionPool(
backgroundChildLoggingId, mVersionChangeTransaction->DatabaseId(),
loggingSerialNumber, objectStoreNames,
/* aIsWriteTransaction */ true);
mVersionChangeOp = versionChangeOp;
mVersionChangeTransaction->NoteActiveRequest();
mVersionChangeTransaction->Init(transactionId);
return NS_OK;
}
nsresult OpenDatabaseOp::SendUpgradeNeeded() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DatabaseWorkVersionChange);
MOZ_ASSERT(mVersionChangeTransaction);
MOZ_ASSERT(mMaybeBlockedDatabases.IsEmpty());
MOZ_ASSERT(!HasFailed());
MOZ_ASSERT_IF(!IsActorDestroyed(), mDatabase);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsActorDestroyed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
const SafeRefPtr<VersionChangeTransaction> transaction =
std::move(mVersionChangeTransaction);
nsresult rv = EnsureDatabaseActorIsAlive();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// Transfer ownership to IPDL.
transaction->SetActorAlive();
if (!mDatabase->SendPBackgroundIDBVersionChangeTransactionConstructor(
transaction.unsafeGetRawPtr(), mMetadata->mCommonMetadata.version(),
mRequestedVersion, mMetadata->mNextObjectStoreId,
mMetadata->mNextIndexId)) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
return NS_OK;
}
nsresult OpenDatabaseOp::DoVersionUpdate() {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State::DatabaseWorkVersionUpdate);
MOZ_ASSERT(!HasFailed());
AUTO_PROFILER_LABEL("OpenDatabaseOp::DoVersionUpdate", DOM);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
!OperationMayProceed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
mFileManager->UpdateDatabaseVersion(mRequestedVersion);
mState = State::SendingResults;
QM_TRY(MOZ_TO_RESULT(
DispatchThisAfterProcessingCurrentEvent(mOwningEventTarget)));
return NS_OK;
}
void OpenDatabaseOp::SendResults() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::SendingResults);
MOZ_ASSERT(mMaybeBlockedDatabases.IsEmpty());
MOZ_ASSERT_IF(!HasFailed(), !mVersionChangeTransaction);
if (mCompleteCallback) {
auto completeCallback = std::move(mCompleteCallback);
completeCallback();
}
DebugOnly<DatabaseActorInfo*> info = nullptr;
MOZ_ASSERT_IF(mDatabaseId.isSome() && gLiveDatabaseHashtable &&
gLiveDatabaseHashtable->Get(mDatabaseId.ref(), &info),
!info->mWaitingFactoryOp);
if (mVersionChangeTransaction) {
MOZ_ASSERT(HasFailed());
mVersionChangeTransaction->Abort(ResultCode(), /* aForce */ true);
mVersionChangeTransaction = nullptr;
}
if (IsActorDestroyed()) {
SetFailureCodeIfUnset(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
} else {
FactoryRequestResponse response;
if (!HasFailed()) {
// If we just successfully completed a versionchange operation then we
// need to update the version in our metadata.
mMetadata->mCommonMetadata.version() = mRequestedVersion;
nsresult rv = EnsureDatabaseActorIsAlive();
if (NS_SUCCEEDED(rv)) {
// We successfully opened a database so use its actor as the success
// result for this request.
// XXX OpenDatabaseRequestResponse stores a raw pointer, can this be
// avoided?
response = OpenDatabaseRequestResponse{
WrapNotNull(mDatabase.unsafeGetRawPtr())};
} else {
response = ClampResultCode(rv);
#ifdef DEBUG
SetFailureCode(response.get_nsresult());
#endif
}
} else {
#ifdef DEBUG
// If something failed then our metadata pointer is now bad. No one should
// ever touch it again though so just null it out in DEBUG builds to make
// sure we find such cases.
mMetadata = nullptr;
#endif
response = ClampResultCode(ResultCode());
}
Unused << PBackgroundIDBFactoryRequestParent::Send__delete__(this,
response);
}
if (mDatabase) {
MOZ_ASSERT(!mDirectoryLockHandle);
if (HasFailed()) {
mDatabase->Invalidate();
}
// Make sure to release the database on this thread.
mDatabase = nullptr;
CleanupMetadata();
} else if (mDirectoryLockHandle) {
// ConnectionClosedCallback will call CleanupMetadata().
nsCOMPtr<nsIRunnable> callback = NewRunnableMethod(
"dom::indexedDB::OpenDatabaseOp::ConnectionClosedCallback", this,
&OpenDatabaseOp::ConnectionClosedCallback);
RefPtr<WaitForTransactionsHelper> helper =
new WaitForTransactionsHelper(mDatabaseId.ref(), callback);
helper->WaitForTransactions();
} else {
CleanupMetadata();
}
FinishSendResults();
}
void OpenDatabaseOp::ConnectionClosedCallback() {
AssertIsOnOwningThread();
MOZ_ASSERT(HasFailed());
MOZ_ASSERT(mDirectoryLockHandle);
{
auto destroyingDirectoryLockHandle = std::move(mDirectoryLockHandle);
}
CleanupMetadata();
}
void OpenDatabaseOp::EnsureDatabaseActor() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::BeginVersionChange ||
mState == State::DatabaseWorkVersionChange ||
mState == State::SendingResults);
MOZ_ASSERT(!HasFailed());
MOZ_ASSERT(mDatabaseFilePath.isSome());
MOZ_ASSERT(!IsActorDestroyed());
if (mDatabase) {
return;
}
MOZ_ASSERT(mMetadata->mDatabaseId.IsEmpty());
mMetadata->mDatabaseId = mDatabaseId.ref();
MOZ_ASSERT(mMetadata->mFilePath.IsEmpty());
mMetadata->mFilePath = mDatabaseFilePath.ref();
DatabaseActorInfo* info;
if (gLiveDatabaseHashtable->Get(mDatabaseId.ref(), &info)) {
AssertMetadataConsistency(*info->mMetadata);
mMetadata = info->mMetadata.clonePtr();
}
Maybe<const CipherKey> maybeKey =
mInPrivateBrowsing ? mFileManager->MutableCipherKeyManagerRef().Get()
: Nothing();
MOZ_RELEASE_ASSERT(mInPrivateBrowsing == maybeKey.isSome());
const bool directoryLockInvalidated = mDirectoryLockHandle->Invalidated();
// XXX Shouldn't Manager() return already_AddRefed when
// PBackgroundIDBFactoryParent is declared refcounted?
mDatabase = MakeSafeRefPtr<Database>(
SafeRefPtr{static_cast<Factory*>(Manager()),
AcquireStrongRefFromRawPtr{}},
mCommonParams.principalInfo(), mContentParentId, mOriginMetadata,
mTelemetryId, mMetadata.clonePtr(), mFileManager.clonePtr(),
std::move(mDirectoryLockHandle), mInPrivateBrowsing, maybeKey);
if (info) {
info->mLiveDatabases.insertBack(mDatabase.unsafeGetRawPtr());
} else {
// XXX Maybe use LookupOrInsertWith above, to avoid a second lookup here?
info = gLiveDatabaseHashtable
->InsertOrUpdate(
mDatabaseId.ref(),
MakeUnique<DatabaseActorInfo>(
mMetadata.clonePtr(),
WrapNotNullUnchecked(mDatabase.unsafeGetRawPtr())))
.get();
}
if (directoryLockInvalidated) {
mDatabase->Invalidate();
}
// Balanced in Database::CleanupMetadata().
IncreaseBusyCount();
}
nsresult OpenDatabaseOp::EnsureDatabaseActorIsAlive() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DatabaseWorkVersionChange ||
mState == State::SendingResults);
MOZ_ASSERT(!HasFailed());
MOZ_ASSERT(!IsActorDestroyed());
EnsureDatabaseActor();
if (mDatabase->IsActorAlive()) {
return NS_OK;
}
auto* const factory = static_cast<Factory*>(Manager());
QM_TRY_INSPECT(const auto& spec, MetadataToSpec());
mDatabase->SetActorAlive();
if (!factory->SendPBackgroundIDBDatabaseConstructor(
mDatabase.unsafeGetRawPtr(), spec, WrapNotNull(this))) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
if (mDatabase->IsInvalidated()) {
Unused << mDatabase->SendInvalidate();
}
return NS_OK;
}
Result<DatabaseSpec, nsresult> OpenDatabaseOp::MetadataToSpec() const {
AssertIsOnOwningThread();
MOZ_ASSERT(mMetadata);
DatabaseSpec spec;
spec.metadata() = mMetadata->mCommonMetadata;
QM_TRY_UNWRAP(spec.objectStores(),
TransformIntoNewArrayAbortOnErr(
mMetadata->mObjectStores,
[](const auto& objectStoreEntry)
-> mozilla::Result<ObjectStoreSpec, nsresult> {
FullObjectStoreMetadata* metadata =
objectStoreEntry.GetWeak();
MOZ_ASSERT(objectStoreEntry.GetKey());
MOZ_ASSERT(metadata);
ObjectStoreSpec objectStoreSpec;
objectStoreSpec.metadata() = metadata->mCommonMetadata;
QM_TRY_UNWRAP(auto indexes,
TransformIntoNewArray(
metadata->mIndexes,
[](const auto& indexEntry) {
FullIndexMetadata* indexMetadata =
indexEntry.GetWeak();
MOZ_ASSERT(indexEntry.GetKey());
MOZ_ASSERT(indexMetadata);
return indexMetadata->mCommonMetadata;
},
fallible));
objectStoreSpec.indexes() = std::move(indexes);
return objectStoreSpec;
},
fallible));
return spec;
}
#ifdef DEBUG
void OpenDatabaseOp::AssertMetadataConsistency(
const FullDatabaseMetadata& aMetadata) {
AssertIsOnBackgroundThread();
const FullDatabaseMetadata& thisDB = *mMetadata;
const FullDatabaseMetadata& otherDB = aMetadata;
MOZ_ASSERT(&thisDB != &otherDB);
MOZ_ASSERT(thisDB.mCommonMetadata.name() == otherDB.mCommonMetadata.name());
MOZ_ASSERT(thisDB.mCommonMetadata.version() ==
otherDB.mCommonMetadata.version());
MOZ_ASSERT(thisDB.mCommonMetadata.persistenceType() ==
otherDB.mCommonMetadata.persistenceType());
MOZ_ASSERT(thisDB.mDatabaseId == otherDB.mDatabaseId);
MOZ_ASSERT(thisDB.mFilePath == otherDB.mFilePath);
// |thisDB| reflects the latest objectStore and index ids that have committed
// to disk. The in-memory metadata |otherDB| keeps track of objectStores and
// indexes that were created and then removed as well, so the next ids for
// |otherDB| may be higher than for |thisDB|.
MOZ_ASSERT(thisDB.mNextObjectStoreId <= otherDB.mNextObjectStoreId);
MOZ_ASSERT(thisDB.mNextIndexId <= otherDB.mNextIndexId);
MOZ_ASSERT(thisDB.mObjectStores.Count() == otherDB.mObjectStores.Count());
for (const auto& thisObjectStore : thisDB.mObjectStores.Values()) {
MOZ_ASSERT(thisObjectStore);
MOZ_ASSERT(!thisObjectStore->mDeleted);
auto otherObjectStore = MatchMetadataNameOrId(
otherDB.mObjectStores, thisObjectStore->mCommonMetadata.id());
MOZ_ASSERT(otherObjectStore);
MOZ_ASSERT(thisObjectStore != &otherObjectStore.ref());
MOZ_ASSERT(thisObjectStore->mCommonMetadata.id() ==
otherObjectStore->mCommonMetadata.id());
MOZ_ASSERT(thisObjectStore->mCommonMetadata.name() ==
otherObjectStore->mCommonMetadata.name());
MOZ_ASSERT(thisObjectStore->mCommonMetadata.autoIncrement() ==
otherObjectStore->mCommonMetadata.autoIncrement());
MOZ_ASSERT(thisObjectStore->mCommonMetadata.keyPath() ==
otherObjectStore->mCommonMetadata.keyPath());
// mNextAutoIncrementId and mCommittedAutoIncrementId may be modified
// concurrently with this OpenOp, so it is not possible to assert equality
// here. It's also possible that we've written the new ids to disk but not
// yet updated the in-memory count.
// TODO The first part of the comment should probably be rephrased. I think
// it still applies but it sounds as if this were thread-unsafe like it was
// before, which isn't true anymore.
{
const auto&& thisAutoIncrementIds =
thisObjectStore->mAutoIncrementIds.Lock();
const auto&& otherAutoIncrementIds =
otherObjectStore->mAutoIncrementIds.Lock();
MOZ_ASSERT(thisAutoIncrementIds->next <= otherAutoIncrementIds->next);
MOZ_ASSERT(
thisAutoIncrementIds->committed <= otherAutoIncrementIds->committed ||
thisAutoIncrementIds->committed == otherAutoIncrementIds->next);
}
MOZ_ASSERT(!otherObjectStore->mDeleted);
MOZ_ASSERT(thisObjectStore->mIndexes.Count() ==
otherObjectStore->mIndexes.Count());
for (const auto& thisIndex : thisObjectStore->mIndexes.Values()) {
MOZ_ASSERT(thisIndex);
MOZ_ASSERT(!thisIndex->mDeleted);
auto otherIndex = MatchMetadataNameOrId(otherObjectStore->mIndexes,
thisIndex->mCommonMetadata.id());
MOZ_ASSERT(otherIndex);
MOZ_ASSERT(thisIndex != &otherIndex.ref());
MOZ_ASSERT(thisIndex->mCommonMetadata.id() ==
otherIndex->mCommonMetadata.id());
MOZ_ASSERT(thisIndex->mCommonMetadata.name() ==
otherIndex->mCommonMetadata.name());
MOZ_ASSERT(thisIndex->mCommonMetadata.keyPath() ==
otherIndex->mCommonMetadata.keyPath());
MOZ_ASSERT(thisIndex->mCommonMetadata.unique() ==
otherIndex->mCommonMetadata.unique());
MOZ_ASSERT(thisIndex->mCommonMetadata.multiEntry() ==
otherIndex->mCommonMetadata.multiEntry());
MOZ_ASSERT(!otherIndex->mDeleted);
}
}
}
#endif // DEBUG
nsresult OpenDatabaseOp::VersionChangeOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mOpenDatabaseOp);
MOZ_ASSERT(mOpenDatabaseOp->mState == State::DatabaseWorkVersionChange);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
!OperationMayProceed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
AUTO_PROFILER_LABEL("OpenDatabaseOp::VersionChangeOp::DoDatabaseWork", DOM);
IDB_LOG_MARK_PARENT_TRANSACTION("Beginning database work", "DB Start",
IDB_LOG_ID_STRING(mBackgroundChildLoggingId),
mTransactionLoggingSerialNumber);
Transaction().SetActiveOnConnectionThread();
QM_TRY(MOZ_TO_RESULT(
aConnection->BeginWriteTransaction(Transaction().GetDurability())));
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"UPDATE database SET version = :version;"_ns,
([&self = *this](
mozIStorageStatement& updateStmt) -> mozilla::Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(
updateStmt.BindInt64ByIndex(0, int64_t(self.mRequestedVersion))));
return Ok{};
}))));
return NS_OK;
}
nsresult OpenDatabaseOp::VersionChangeOp::SendSuccessResult() {
AssertIsOnOwningThread();
MOZ_ASSERT(mOpenDatabaseOp);
MOZ_ASSERT(mOpenDatabaseOp->mState == State::DatabaseWorkVersionChange);
MOZ_ASSERT(mOpenDatabaseOp->mVersionChangeOp == this);
nsresult rv = mOpenDatabaseOp->SendUpgradeNeeded();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
bool OpenDatabaseOp::VersionChangeOp::SendFailureResult(nsresult aResultCode) {
AssertIsOnOwningThread();
MOZ_ASSERT(mOpenDatabaseOp);
MOZ_ASSERT(mOpenDatabaseOp->mState == State::DatabaseWorkVersionChange);
MOZ_ASSERT(mOpenDatabaseOp->mVersionChangeOp == this);
mOpenDatabaseOp->SetFailureCode(aResultCode);
mOpenDatabaseOp->mState = State::SendingResults;
MOZ_ALWAYS_SUCCEEDS(mOpenDatabaseOp->Run());
return false;
}
void OpenDatabaseOp::VersionChangeOp::Cleanup() {
AssertIsOnOwningThread();
MOZ_ASSERT(mOpenDatabaseOp);
MOZ_ASSERT(mOpenDatabaseOp->mVersionChangeOp == this);
mOpenDatabaseOp->mVersionChangeOp = nullptr;
mOpenDatabaseOp = nullptr;
#ifdef DEBUG
// A bit hacky but the VersionChangeOp is not generated in response to a
// child request like most other database operations. Do this to make our
// assertions happy.
//
// XXX: Depending on timing, in most cases, NoteActorDestroyed will not have
// been destroyed before, but in some cases it has. This should be reworked in
// a way this hack is not necessary. There are also several similar cases in
// other *Op classes.
if (!IsActorDestroyed()) {
NoteActorDestroyed();
}
#endif
TransactionDatabaseOperationBase::Cleanup();
}
void DeleteDatabaseOp::LoadPreviousVersion(nsIFile& aDatabaseFile) {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State::DatabaseWorkOpen);
MOZ_ASSERT(!mPreviousVersion);
AUTO_PROFILER_LABEL("DeleteDatabaseOp::LoadPreviousVersion", DOM);
nsresult rv;
nsCOMPtr<mozIStorageService> ss =
do_GetService(MOZ_STORAGE_SERVICE_CONTRACTID, &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
IndexedDatabaseManager* const idm = IndexedDatabaseManager::Get();
MOZ_ASSERT(idm);
const PersistenceType persistenceType =
mCommonParams.metadata().persistenceType();
const nsAString& databaseName = mCommonParams.metadata().name();
SafeRefPtr<DatabaseFileManager> fileManager = idm->GetFileManager(
persistenceType, mOriginMetadata.mOrigin, databaseName);
if (!fileManager) {
fileManager = MakeSafeRefPtr<DatabaseFileManager>(
persistenceType, mOriginMetadata, databaseName, mDatabaseId.ref(),
mDatabaseFilePath.ref(), mEnforcingQuota, mInPrivateBrowsing);
}
const auto maybeKey =
mInPrivateBrowsing
? Some(fileManager->MutableCipherKeyManagerRef().Ensure())
: Nothing();
MOZ_RELEASE_ASSERT(mInPrivateBrowsing == maybeKey.isSome());
// Pass -1 as the directoryLockId to disable quota checking, since we might
// temporarily exceed quota before deleting the database.
QM_TRY_INSPECT(const auto& dbFileUrl,
GetDatabaseFileURL(aDatabaseFile, -1, maybeKey), QM_VOID);
QM_TRY_UNWRAP(const NotNull<nsCOMPtr<mozIStorageConnection>> connection,
OpenDatabaseAndHandleBusy(*ss, *dbFileUrl), QM_VOID);
#ifdef DEBUG
{
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement<
SingleStepResult::ReturnNullIfNoResult>(
*connection, "SELECT name FROM database"_ns),
QM_VOID);
QM_TRY(OkIf(stmt), QM_VOID);
nsString databaseName;
rv = stmt->GetString(0, databaseName);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
MOZ_ASSERT(mCommonParams.metadata().name() == databaseName);
}
#endif
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement<
SingleStepResult::ReturnNullIfNoResult>(
*connection, "SELECT version FROM database"_ns),
QM_VOID);
QM_TRY(OkIf(stmt), QM_VOID);
int64_t version;
rv = stmt->GetInt64(0, &version);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
mPreviousVersion = uint64_t(version);
}
nsresult DeleteDatabaseOp::DatabaseOpen() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DatabaseOpenPending);
nsresult rv = SendToIOThread();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
nsresult DeleteDatabaseOp::DoDatabaseWork() {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State::DatabaseWorkOpen);
MOZ_ASSERT(mOriginMetadata.mPersistenceType ==
mCommonParams.metadata().persistenceType());
AUTO_PROFILER_LABEL("DeleteDatabaseOp::DoDatabaseWork", DOM);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
!OperationMayProceed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
const nsAString& databaseName = mCommonParams.metadata().name();
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
QM_TRY_UNWRAP(auto directory,
quotaManager->GetOriginDirectory(mOriginMetadata));
QM_TRY(MOZ_TO_RESULT(
directory->Append(NS_LITERAL_STRING_FROM_CSTRING(IDB_DIRECTORY_NAME))));
QM_TRY_UNWRAP(mDatabaseDirectoryPath, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
nsString, directory, GetPath));
mDatabaseFilenameBase =
GetDatabaseFilenameBase(databaseName, mOriginMetadata.mIsPrivate);
QM_TRY_INSPECT(
const auto& dbFile,
CloneFileAndAppend(*directory, mDatabaseFilenameBase + kSQLiteSuffix));
#ifdef DEBUG
{
QM_TRY_INSPECT(
const auto& databaseFilePath,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsString, dbFile, GetPath));
MOZ_ASSERT(databaseFilePath == mDatabaseFilePath.ref());
}
#endif
QM_TRY_INSPECT(const bool& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(dbFile, Exists));
if (exists) {
// Parts of this function may fail but that shouldn't prevent us from
// deleting the file eventually.
LoadPreviousVersion(*dbFile);
mState = State::BeginVersionChange;
} else {
mState = State::SendingResults;
}
QM_TRY(MOZ_TO_RESULT(
DispatchThisAfterProcessingCurrentEvent(mOwningEventTarget)));
return NS_OK;
}
nsresult DeleteDatabaseOp::BeginVersionChange() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::BeginVersionChange);
MOZ_ASSERT(mMaybeBlockedDatabases.IsEmpty());
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsActorDestroyed()) {
IDB_REPORT_INTERNAL_ERR();
QM_TRY(MOZ_TO_RESULT(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR));
}
DatabaseActorInfo* info;
if (gLiveDatabaseHashtable->Get(mDatabaseId.ref(), &info)) {
MOZ_ASSERT(!info->mWaitingFactoryOp);
nsresult rv =
SendVersionChangeMessages(info, Nothing(), mPreviousVersion, Nothing());
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (!mMaybeBlockedDatabases.IsEmpty()) {
// If the actor gets destroyed, mWaitingFactoryOp will hold the last
// strong reference to us.
info->mWaitingFactoryOp = this;
mState = State::WaitingForOtherDatabasesToClose;
return NS_OK;
}
}
// No other databases need to be notified, just make sure that all
// transactions are complete.
WaitForTransactions();
return NS_OK;
}
bool DeleteDatabaseOp::AreActorsAlive() {
AssertIsOnOwningThread();
return !IsActorDestroyed();
}
nsresult DeleteDatabaseOp::DispatchToWorkThread() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::WaitingForTransactionsToComplete);
MOZ_ASSERT(mMaybeBlockedDatabases.IsEmpty());
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnBackgroundThread()) ||
IsActorDestroyed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
mState = State::DatabaseWorkVersionChange;
RefPtr<VersionChangeOp> versionChangeOp = new VersionChangeOp(this);
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
nsresult rv = quotaManager->IOThread()->Dispatch(versionChangeOp.forget(),
NS_DISPATCH_NORMAL);
if (NS_WARN_IF(NS_FAILED(rv))) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
return NS_OK;
}
void DeleteDatabaseOp::SendBlockedNotification() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::WaitingForOtherDatabasesToClose);
if (!IsActorDestroyed()) {
Unused << SendBlocked(mPreviousVersion);
}
}
nsresult DeleteDatabaseOp::DoVersionUpdate() {
MOZ_CRASH("Not implemented because this should be unreachable.");
}
void DeleteDatabaseOp::SendResults() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::SendingResults);
MOZ_ASSERT(mMaybeBlockedDatabases.IsEmpty());
DebugOnly<DatabaseActorInfo*> info = nullptr;
MOZ_ASSERT_IF(mDatabaseId.isSome() && gLiveDatabaseHashtable &&
gLiveDatabaseHashtable->Get(mDatabaseId.ref(), &info),
!info->mWaitingFactoryOp);
if (!IsActorDestroyed()) {
FactoryRequestResponse response;
if (!HasFailed()) {
response = DeleteDatabaseRequestResponse(mPreviousVersion);
} else {
response = ClampResultCode(ResultCode());
}
Unused << PBackgroundIDBFactoryRequestParent::Send__delete__(this,
response);
}
{
auto destroyingDirectoryLockHandle = std::move(mDirectoryLockHandle);
}
CleanupMetadata();
FinishSendResults();
}
nsresult DeleteDatabaseOp::VersionChangeOp::RunOnIOThread() {
AssertIsOnIOThread();
MOZ_ASSERT(mDeleteDatabaseOp->mState == State::DatabaseWorkVersionChange);
AUTO_PROFILER_LABEL("DeleteDatabaseOp::VersionChangeOp::RunOnIOThread", DOM);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
!OperationMayProceed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
const PersistenceType& persistenceType =
mDeleteDatabaseOp->mCommonParams.metadata().persistenceType();
QuotaManager* quotaManager =
mDeleteDatabaseOp->mEnforcingQuota ? QuotaManager::Get() : nullptr;
MOZ_ASSERT_IF(mDeleteDatabaseOp->mEnforcingQuota, quotaManager);
nsCOMPtr<nsIFile> directory =
GetFileForPath(mDeleteDatabaseOp->mDatabaseDirectoryPath);
if (NS_WARN_IF(!directory)) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
nsresult rv = RemoveDatabaseFilesAndDirectory(
*directory, mDeleteDatabaseOp->mDatabaseFilenameBase, quotaManager,
persistenceType, mDeleteDatabaseOp->mOriginMetadata,
mDeleteDatabaseOp->mCommonParams.metadata().name());
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
rv = mOwningEventTarget->Dispatch(this, NS_DISPATCH_NORMAL);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
void DeleteDatabaseOp::VersionChangeOp::RunOnOwningThread() {
AssertIsOnOwningThread();
MOZ_ASSERT(mDeleteDatabaseOp->mState == State::DatabaseWorkVersionChange);
const RefPtr<DeleteDatabaseOp> deleteOp = std::move(mDeleteDatabaseOp);
if (deleteOp->IsActorDestroyed()) {
IDB_REPORT_INTERNAL_ERR();
deleteOp->SetFailureCode(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
} else if (HasFailed()) {
deleteOp->SetFailureCodeIfUnset(ResultCode());
} else {
DatabaseActorInfo* info;
// Inform all the other databases that they are now invalidated. That
// should remove the previous metadata from our table.
if (gLiveDatabaseHashtable->Get(deleteOp->mDatabaseId.ref(), &info)) {
MOZ_ASSERT(!info->mLiveDatabases.isEmpty());
MOZ_ASSERT(!info->mWaitingFactoryOp);
nsTArray<SafeRefPtr<Database>> liveDatabases;
if (NS_WARN_IF(!liveDatabases.SetCapacity(info->mLiveDatabases.length(),
fallible))) {
deleteOp->SetFailureCode(NS_ERROR_OUT_OF_MEMORY);
} else {
std::transform(info->mLiveDatabases.begin(), info->mLiveDatabases.end(),
MakeBackInserter(liveDatabases),
[](Database* const aDatabase) -> SafeRefPtr<Database> {
return {aDatabase, AcquireStrongRefFromRawPtr{}};
});
#ifdef DEBUG
// The code below should result in the deletion of |info|. Set to null
// here to make sure we find invalid uses later.
info = nullptr;
#endif
for (const auto& database : liveDatabases) {
database->Invalidate();
}
MOZ_ASSERT(!gLiveDatabaseHashtable->Get(deleteOp->mDatabaseId.ref()));
}
}
}
// We hold a strong ref to the deleteOp, so it's safe to call Run() directly.
deleteOp->mState = State::SendingResults;
MOZ_ALWAYS_SUCCEEDS(deleteOp->Run());
#ifdef DEBUG
// A bit hacky but the DeleteDatabaseOp::VersionChangeOp is not really a
// normal database operation that is tied to an actor. Do this to make our
// assertions happy.
NoteActorDestroyed();
#endif
}
nsresult DeleteDatabaseOp::VersionChangeOp::Run() {
nsresult rv;
if (IsOnIOThread()) {
rv = RunOnIOThread();
} else {
RunOnOwningThread();
rv = NS_OK;
}
if (NS_WARN_IF(NS_FAILED(rv))) {
SetFailureCodeIfUnset(rv);
MOZ_ALWAYS_SUCCEEDS(mOwningEventTarget->Dispatch(this, NS_DISPATCH_NORMAL));
}
return NS_OK;
}
nsresult GetDatabasesOp::DatabasesNotAvailable() {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State::DatabaseWorkOpen);
mState = State::SendingResults;
QM_TRY(MOZ_TO_RESULT(
DispatchThisAfterProcessingCurrentEvent(mOwningEventTarget)));
return NS_OK;
}
nsresult GetDatabasesOp::DoDirectoryWork() {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State::DirectoryWorkOpen);
// This state (DirectoryWorkOpen) runs immediately on the I/O thread, before
// waiting for existing factory operations to complete (at which point
// DoDatabaseWork will be invoked). To match the spec, we must snapshot the
// current state of any databases that are being created (version = 0) or
// upgraded (version >= 1) now. If we only sampled these values in
// DoDatabaseWork, we would only see their post-creation/post-upgrade
// versions, which would be incorrect.
IndexedDatabaseManager* const idm = IndexedDatabaseManager::Get();
MOZ_ASSERT(idm);
const auto& fileManagers =
idm->GetFileManagers(mPersistenceType, mOriginMetadata.mOrigin);
for (const auto& fileManager : fileManagers) {
auto& metadata =
mDatabaseMetadataTable.LookupOrInsert(fileManager->DatabaseFilePath());
metadata.name() = fileManager->DatabaseName();
metadata.version() = fileManager->DatabaseVersion();
}
// Must set this before dispatching otherwise we will race with the IO thread.
mState = State::DirectoryWorkDone;
QM_TRY(MOZ_TO_RESULT(mOwningEventTarget->Dispatch(this, NS_DISPATCH_NORMAL)));
return NS_OK;
}
nsresult GetDatabasesOp::DatabaseOpen() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::DatabaseOpenPending);
nsresult rv = SendToIOThread();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
nsresult GetDatabasesOp::DoDatabaseWork() {
AssertIsOnIOThread();
MOZ_ASSERT(mState == State::DatabaseWorkOpen);
AUTO_PROFILER_LABEL("GetDatabasesOp::DoDatabaseWork", DOM);
if (NS_WARN_IF(QuotaClient::IsShuttingDownOnNonBackgroundThread()) ||
!OperationMayProceed()) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
QuotaManager* const quotaManager = QuotaManager::Get();
MOZ_ASSERT(quotaManager);
{
QM_TRY_INSPECT(const bool& exists,
quotaManager->DoesOriginDirectoryExist(mOriginMetadata));
if (!exists) {
return DatabasesNotAvailable();
}
}
// XXX Is this really needed ?
QM_TRY((["aManager,
this]() -> mozilla::Result<nsCOMPtr<nsIFile>, nsresult> {
if (mPersistenceType == PERSISTENCE_TYPE_PERSISTENT) {
QM_TRY_RETURN(quotaManager->GetOriginDirectory(mOriginMetadata));
}
QM_TRY_RETURN(
quotaManager->GetOrCreateTemporaryOriginDirectory(mOriginMetadata));
}()
.map([](const auto& res) { return Ok{}; })));
{
QM_TRY_INSPECT(const bool& exists,
quotaManager->DoesClientDirectoryExist(
ClientMetadata{mOriginMetadata, Client::IDB}));
if (!exists) {
return DatabasesNotAvailable();
}
}
QM_TRY_INSPECT(
const auto& clientDirectory,
(["aManager, this]()
-> mozilla::Result<std::pair<nsCOMPtr<nsIFile>, bool>, nsresult> {
if (mPersistenceType == PERSISTENCE_TYPE_PERSISTENT) {
QM_TRY_RETURN(quotaManager->EnsurePersistentClientIsInitialized(
ClientMetadata{mOriginMetadata, Client::IDB}));
}
QM_TRY_RETURN(quotaManager->EnsureTemporaryClientIsInitialized(
ClientMetadata{mOriginMetadata, Client::IDB},
/* aCreateIfNonExistent */ true));
}()
.map([](const auto& res) { return res.first; })));
QM_TRY_INSPECT(
(const auto& [subdirsToProcess, databaseFilenames]),
QuotaClient::GetDatabaseFilenames(*clientDirectory,
/* aCanceled */ Atomic<bool>{false}));
for (const auto& databaseFilename : databaseFilenames) {
QM_TRY_INSPECT(
const auto& databaseFile,
CloneFileAndAppend(*clientDirectory, databaseFilename + kSQLiteSuffix));
nsString path;
databaseFile->GetPath(path);
// Use the snapshotted values from DoDirectoryWork which correctly
// snapshotted the state of any pending creations/upgrades. This does mean
// that we need to skip reporting databases that had a version of 0 at that
// time because they were still being created. In the event that any other
// creation or upgrade requests are made after our operation is created,
// this operation will block those, so it's not possible for this set of
// data to get out of sync. The snapshotting (using cached database name
// and version in DatabaseFileManager) also guarantees that we are not
// touching the SQLite database here on the QuotaManager I/O thread which
// is already open on the connection thread.
auto metadata = mDatabaseMetadataTable.Lookup(path);
if (metadata) {
if (metadata->version() != 0) {
mDatabaseMetadataArray.AppendElement(DatabaseMetadata(
metadata->name(), metadata->version(), mPersistenceType));
}
continue;
}
// Since the database is not already open (there was no DatabaseFileManager
// for snapshotting in DoDirectoryWork which could provide us with the
// database name and version without needing to open the SQLite database),
// it is safe and necessary for us to open the database on this thread and
// retrieve its name and version. We do not need to worry about racing a
// database open because database opens can only be processed on this
// thread and we are performing the steps below synchronously.
QM_TRY_INSPECT(
const auto& fmDirectory,
CloneFileAndAppend(*clientDirectory,
databaseFilename + kFileManagerDirectoryNameSuffix));
QM_TRY_UNWRAP(
const NotNull<nsCOMPtr<mozIStorageConnection>> connection,
CreateStorageConnection(*databaseFile, *fmDirectory, VoidString(),
mOriginMetadata.mOrigin, mDirectoryLockId,
TelemetryIdForFile(databaseFile), Nothing{}));
{
// Load version information.
QM_TRY_INSPECT(const auto& stmt,
CreateAndExecuteSingleStepStatement<
SingleStepResult::ReturnNullIfNoResult>(
*connection, "SELECT name, version FROM database"_ns));
QM_TRY(OkIf(stmt), NS_ERROR_FILE_CORRUPTED);
QM_TRY_INSPECT(
const auto& databaseName,
MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(nsString, stmt, GetString, 0));
QM_TRY_INSPECT(const int64_t& version,
MOZ_TO_RESULT_INVOKE_MEMBER(stmt, GetInt64, 1));
mDatabaseMetadataArray.AppendElement(
DatabaseMetadata(databaseName, version, mPersistenceType));
}
}
mState = State::SendingResults;
QM_TRY(MOZ_TO_RESULT(
DispatchThisAfterProcessingCurrentEvent(mOwningEventTarget)));
return NS_OK;
}
nsresult GetDatabasesOp::BeginVersionChange() {
MOZ_CRASH("Not implemented because this should be unreachable.");
}
bool GetDatabasesOp::AreActorsAlive() {
MOZ_CRASH("Not implemented because this should be unreachable.");
}
void GetDatabasesOp::SendBlockedNotification() {
MOZ_CRASH("Not implemented because this should be unreachable.");
}
nsresult GetDatabasesOp::DispatchToWorkThread() {
MOZ_CRASH("Not implemented because this should be unreachable.");
}
nsresult GetDatabasesOp::DoVersionUpdate() {
MOZ_CRASH("Not implemented because this should be unreachable.");
}
void GetDatabasesOp::SendResults() {
AssertIsOnOwningThread();
MOZ_ASSERT(mState == State::SendingResults);
#ifdef DEBUG
NoteActorDestroyed();
#endif
if (HasFailed()) {
mResolver(ClampResultCode(ResultCode()));
} else {
mResolver(mDatabaseMetadataArray);
}
{
auto destroyingDirectoryLockHandle = std::move(mDirectoryLockHandle);
}
CleanupMetadata();
FinishSendResults();
}
TransactionDatabaseOperationBase::TransactionDatabaseOperationBase(
SafeRefPtr<TransactionBase> aTransaction, const int64_t aRequestId)
: DatabaseOperationBase(aTransaction->GetLoggingInfo()->Id(),
aTransaction->GetLoggingInfo()->NextRequestSN()),
mTransaction(WrapNotNull(std::move(aTransaction))),
mRequestId(aRequestId),
mTransactionIsAborted((*mTransaction)->IsAborted()),
mTransactionLoggingSerialNumber((*mTransaction)->LoggingSerialNumber()) {
MOZ_ASSERT(LoggingSerialNumber());
}
TransactionDatabaseOperationBase::TransactionDatabaseOperationBase(
SafeRefPtr<TransactionBase> aTransaction, const int64_t aRequestId,
uint64_t aLoggingSerialNumber)
: DatabaseOperationBase(aTransaction->GetLoggingInfo()->Id(),
aLoggingSerialNumber),
mTransaction(WrapNotNull(std::move(aTransaction))),
mRequestId(aRequestId),
mTransactionIsAborted((*mTransaction)->IsAborted()),
mTransactionLoggingSerialNumber((*mTransaction)->LoggingSerialNumber()) {}
TransactionDatabaseOperationBase::~TransactionDatabaseOperationBase() {
MOZ_ASSERT(mInternalState == InternalState::Completed);
MOZ_ASSERT(!mTransaction,
"TransactionDatabaseOperationBase::Cleanup() was not called by a "
"subclass!");
}
#ifdef DEBUG
void TransactionDatabaseOperationBase::AssertIsOnConnectionThread() const {
(*mTransaction)->AssertIsOnConnectionThread();
}
#endif // DEBUG
uint64_t TransactionDatabaseOperationBase::StartOnConnectionPool(
const nsID& aBackgroundChildLoggingId, const nsACString& aDatabaseId,
int64_t aLoggingSerialNumber, const nsTArray<nsString>& aObjectStoreNames,
bool aIsWriteTransaction) {
AssertIsOnOwningThread();
MOZ_ASSERT(mInternalState == InternalState::Initial);
// Must set mInternalState before dispatching otherwise we will race with the
// connection thread.
mInternalState = InternalState::DatabaseWork;
return gConnectionPool->Start(aBackgroundChildLoggingId, aDatabaseId,
aLoggingSerialNumber, aObjectStoreNames,
aIsWriteTransaction, this);
}
void TransactionDatabaseOperationBase::DispatchToConnectionPool() {
AssertIsOnOwningThread();
MOZ_ASSERT(mInternalState == InternalState::Initial);
Unused << this->Run();
}
void TransactionDatabaseOperationBase::RunOnConnectionThread() {
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(mInternalState == InternalState::DatabaseWork);
MOZ_ASSERT(!HasFailed());
AUTO_PROFILER_LABEL("TransactionDatabaseOperationBase::RunOnConnectionThread",
DOM);
// There are several cases where we don't actually have to to any work here.
if (mTransactionIsAborted || (*mTransaction)->IsInvalidatedOnAnyThread()) {
// This transaction is already set to be aborted or invalidated.
SetFailureCode(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
} else if (!OperationMayProceed()) {
// The operation was canceled in some way, likely because the child process
// has crashed.
IDB_REPORT_INTERNAL_ERR();
OverrideFailureCode(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
} else {
Database& database = (*mTransaction)->GetMutableDatabase();
// Here we're actually going to perform the database operation.
nsresult rv = database.EnsureConnection();
if (NS_WARN_IF(NS_FAILED(rv))) {
SetFailureCode(rv);
} else {
DatabaseConnection* connection = database.GetConnection();
MOZ_ASSERT(connection);
auto& storageConnection = connection->MutableStorageConnection();
AutoSetProgressHandler autoProgress;
if (mLoggingSerialNumber) {
rv = autoProgress.Register(storageConnection, this);
if (NS_WARN_IF(NS_FAILED(rv))) {
SetFailureCode(rv);
}
}
if (NS_SUCCEEDED(rv)) {
if (mLoggingSerialNumber) {
IDB_LOG_MARK_PARENT_TRANSACTION_REQUEST(
"Beginning database work", "DB Start",
IDB_LOG_ID_STRING(mBackgroundChildLoggingId),
mTransactionLoggingSerialNumber, mLoggingSerialNumber);
}
rv = DoDatabaseWork(connection);
if (mLoggingSerialNumber) {
IDB_LOG_MARK_PARENT_TRANSACTION_REQUEST(
"Finished database work", "DB End",
IDB_LOG_ID_STRING(mBackgroundChildLoggingId),
mTransactionLoggingSerialNumber, mLoggingSerialNumber);
}
if (NS_FAILED(rv)) {
SetFailureCode(rv);
}
}
}
}
// Must set mInternalState before dispatching otherwise we will race with the
// owning thread.
if (HasPreprocessInfo()) {
mInternalState = InternalState::SendingPreprocess;
} else {
mInternalState = InternalState::SendingResults;
}
MOZ_ALWAYS_SUCCEEDS(mOwningEventTarget->Dispatch(this, NS_DISPATCH_NORMAL));
}
bool TransactionDatabaseOperationBase::HasPreprocessInfo() { return false; }
nsresult TransactionDatabaseOperationBase::SendPreprocessInfo() {
return NS_OK;
}
void TransactionDatabaseOperationBase::NoteContinueReceived() {
AssertIsOnOwningThread();
MOZ_ASSERT(mInternalState == InternalState::WaitingForContinue);
mWaitingForContinue = false;
mInternalState = InternalState::SendingResults;
// This TransactionDatabaseOperationBase can only be held alive by the IPDL.
// Run() can end up with clearing that last reference. So we need to add
// a self reference here.
RefPtr<TransactionDatabaseOperationBase> kungFuDeathGrip = this;
Unused << this->Run();
}
void TransactionDatabaseOperationBase::SendToConnectionPool() {
AssertIsOnOwningThread();
MOZ_ASSERT(mInternalState == InternalState::Initial);
// Must set mInternalState before dispatching otherwise we will race with the
// connection thread.
mInternalState = InternalState::DatabaseWork;
gConnectionPool->StartOp((*mTransaction)->TransactionId(), this);
(*mTransaction)->NoteActiveRequest();
}
void TransactionDatabaseOperationBase::SendPreprocess() {
AssertIsOnOwningThread();
MOZ_ASSERT(mInternalState == InternalState::SendingPreprocess);
SendPreprocessInfoOrResults(/* aSendPreprocessInfo */ true);
}
void TransactionDatabaseOperationBase::SendResults() {
AssertIsOnOwningThread();
MOZ_ASSERT(mInternalState == InternalState::SendingResults);
SendPreprocessInfoOrResults(/* aSendPreprocessInfo */ false);
}
void TransactionDatabaseOperationBase::SendPreprocessInfoOrResults(
bool aSendPreprocessInfo) {
AssertIsOnOwningThread();
MOZ_ASSERT(mInternalState == InternalState::SendingPreprocess ||
mInternalState == InternalState::SendingResults);
// The flag is raised only when there is no mUpdateRefcountFunction for the
// executing operation. It assume that is because the previous
// StartTransactionOp was failed to begin a write transaction and it reported
// when this operation has already jumped to the Connection thread.
MOZ_DIAGNOSTIC_ASSERT_IF(mAssumingPreviousOperationFail,
(*mTransaction)->IsAborted());
if (NS_WARN_IF(IsActorDestroyed())) {
// Normally we wouldn't need to send any notifications if the actor was
// already destroyed, but this can be a VersionChangeOp which needs to
// notify its parent operation (OpenDatabaseOp) about the failure.
// So SendFailureResult needs to be called even when the actor was
// destroyed. Normal operations redundantly check if the actor was
// destroyed in SendSuccessResult and SendFailureResult, therefore it's
// ok to call it in all cases here.
if (!HasFailed()) {
IDB_REPORT_INTERNAL_ERR();
SetFailureCode(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
}
} else if ((*mTransaction)->IsInvalidated() || (*mTransaction)->IsAborted()) {
// Aborted transactions always see their requests fail with ABORT_ERR,
// even if the request succeeded or failed with another error.
OverrideFailureCode(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
}
const nsresult rv = [aSendPreprocessInfo, this] {
if (HasFailed()) {
return ResultCode();
}
if (aSendPreprocessInfo) {
// This should not release the IPDL reference.
return SendPreprocessInfo();
}
// This may release the IPDL reference.
return SendSuccessResult();
}();
if (NS_FAILED(rv)) {
SetFailureCodeIfUnset(rv);
// This should definitely release the IPDL reference.
if (!SendFailureResult(rv)) {
// Abort the transaction.
(*mTransaction)->Abort(rv, /* aForce */ false);
}
}
if (aSendPreprocessInfo && !HasFailed()) {
mInternalState = InternalState::WaitingForContinue;
mWaitingForContinue = true;
} else {
if (mLoggingSerialNumber) {
(*mTransaction)->NoteFinishedRequest(mRequestId, ResultCode());
}
gConnectionPool->FinishOp((*mTransaction)->TransactionId());
Cleanup();
mInternalState = InternalState::Completed;
}
}
bool TransactionDatabaseOperationBase::Init(TransactionBase& aTransaction) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mInternalState == InternalState::Initial);
return true;
}
void TransactionDatabaseOperationBase::Cleanup() {
AssertIsOnOwningThread();
MOZ_ASSERT(mInternalState == InternalState::SendingResults);
mTransaction.destroy();
}
NS_IMETHODIMP
TransactionDatabaseOperationBase::Run() {
switch (mInternalState) {
case InternalState::Initial:
SendToConnectionPool();
return NS_OK;
case InternalState::DatabaseWork:
RunOnConnectionThread();
return NS_OK;
case InternalState::SendingPreprocess:
SendPreprocess();
return NS_OK;
case InternalState::SendingResults:
SendResults();
return NS_OK;
default:
MOZ_CRASH("Bad state!");
}
}
TransactionBase::CommitOp::CommitOp(SafeRefPtr<TransactionBase> aTransaction,
nsresult aResultCode)
: DatabaseOperationBase(aTransaction->GetLoggingInfo()->Id(),
aTransaction->GetLoggingInfo()->NextRequestSN()),
mTransaction(std::move(aTransaction)),
mResultCode(aResultCode) {
MOZ_ASSERT(mTransaction);
MOZ_ASSERT(LoggingSerialNumber());
}
nsresult TransactionBase::CommitOp::WriteAutoIncrementCounts() {
MOZ_ASSERT(mTransaction);
mTransaction->AssertIsOnConnectionThread();
MOZ_ASSERT(mTransaction->GetMode() == IDBTransaction::Mode::ReadWrite ||
mTransaction->GetMode() == IDBTransaction::Mode::ReadWriteFlush ||
mTransaction->GetMode() == IDBTransaction::Mode::Cleanup ||
mTransaction->GetMode() == IDBTransaction::Mode::VersionChange);
const nsTArray<SafeRefPtr<FullObjectStoreMetadata>>& metadataArray =
mTransaction->mModifiedAutoIncrementObjectStoreMetadataArray;
if (!metadataArray.IsEmpty()) {
DatabaseConnection* connection =
mTransaction->GetDatabase().GetConnection();
MOZ_ASSERT(connection);
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
auto stmt = DatabaseConnection::LazyStatement(
*connection,
"UPDATE object_store "
"SET auto_increment = :auto_increment WHERE id "
"= :object_store_id;"_ns);
for (const auto& metadata : metadataArray) {
MOZ_ASSERT(!metadata->mDeleted);
const int64_t nextAutoIncrementId = [&metadata] {
const auto&& lockedAutoIncrementIds =
metadata->mAutoIncrementIds.Lock();
return lockedAutoIncrementIds->next;
}();
MOZ_ASSERT(nextAutoIncrementId > 1);
QM_TRY_INSPECT(const auto& borrowedStmt, stmt.Borrow());
QM_TRY(MOZ_TO_RESULT(
borrowedStmt->BindInt64ByIndex(1, metadata->mCommonMetadata.id())));
QM_TRY(MOZ_TO_RESULT(
borrowedStmt->BindInt64ByIndex(0, nextAutoIncrementId)));
QM_TRY(MOZ_TO_RESULT(borrowedStmt->Execute()));
}
}
return NS_OK;
}
void TransactionBase::CommitOp::CommitOrRollbackAutoIncrementCounts() {
MOZ_ASSERT(mTransaction);
mTransaction->AssertIsOnConnectionThread();
MOZ_ASSERT(mTransaction->GetMode() == IDBTransaction::Mode::ReadWrite ||
mTransaction->GetMode() == IDBTransaction::Mode::ReadWriteFlush ||
mTransaction->GetMode() == IDBTransaction::Mode::Cleanup ||
mTransaction->GetMode() == IDBTransaction::Mode::VersionChange);
const auto& metadataArray =
mTransaction->mModifiedAutoIncrementObjectStoreMetadataArray;
if (!metadataArray.IsEmpty()) {
bool committed = NS_SUCCEEDED(mResultCode);
for (const auto& metadata : metadataArray) {
auto&& lockedAutoIncrementIds = metadata->mAutoIncrementIds.Lock();
if (committed) {
lockedAutoIncrementIds->committed = lockedAutoIncrementIds->next;
} else {
lockedAutoIncrementIds->next = lockedAutoIncrementIds->committed;
}
}
}
}
#ifdef DEBUG
void TransactionBase::CommitOp::AssertForeignKeyConsistency(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
MOZ_ASSERT(mTransaction);
mTransaction->AssertIsOnConnectionThread();
MOZ_ASSERT(mTransaction->GetMode() != IDBTransaction::Mode::ReadOnly);
{
QM_TRY_INSPECT(
const auto& pragmaStmt,
CreateAndExecuteSingleStepStatement(
aConnection->MutableStorageConnection(), "PRAGMA foreign_keys;"_ns),
QM_ASSERT_UNREACHABLE_VOID);
int32_t foreignKeysEnabled;
MOZ_ALWAYS_SUCCEEDS(pragmaStmt->GetInt32(0, &foreignKeysEnabled));
MOZ_ASSERT(foreignKeysEnabled,
"Database doesn't have foreign keys enabled!");
}
{
QM_TRY_INSPECT(const bool& foreignKeyError,
CreateAndExecuteSingleStepStatement<
SingleStepResult::ReturnNullIfNoResult>(
aConnection->MutableStorageConnection(),
"PRAGMA foreign_key_check;"_ns),
QM_ASSERT_UNREACHABLE_VOID);
MOZ_ASSERT(!foreignKeyError, "Database has inconsisistent foreign keys!");
}
}
#endif // DEBUG
NS_IMPL_ISUPPORTS_INHERITED0(TransactionBase::CommitOp, DatabaseOperationBase)
NS_IMETHODIMP
TransactionBase::CommitOp::Run() {
MOZ_ASSERT(mTransaction);
mTransaction->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("TransactionBase::CommitOp::Run", DOM);
IDB_LOG_MARK_PARENT_TRANSACTION_REQUEST(
"Beginning database work", "DB Start",
IDB_LOG_ID_STRING(mBackgroundChildLoggingId),
mTransaction->LoggingSerialNumber(), mLoggingSerialNumber);
if (mTransaction->GetMode() != IDBTransaction::Mode::ReadOnly &&
mTransaction->mHasBeenActiveOnConnectionThread) {
if (DatabaseConnection* connection =
mTransaction->GetDatabase().GetConnection()) {
// May be null if the VersionChangeOp was canceled.
DatabaseConnection::UpdateRefcountFunction* fileRefcountFunction =
connection->GetUpdateRefcountFunction();
if (NS_SUCCEEDED(mResultCode)) {
if (fileRefcountFunction) {
mResultCode = fileRefcountFunction->WillCommit();
NS_WARNING_ASSERTION(NS_SUCCEEDED(mResultCode),
"WillCommit() failed!");
}
if (NS_SUCCEEDED(mResultCode)) {
mResultCode = WriteAutoIncrementCounts();
NS_WARNING_ASSERTION(NS_SUCCEEDED(mResultCode),
"WriteAutoIncrementCounts() failed!");
if (NS_SUCCEEDED(mResultCode)) {
AssertForeignKeyConsistency(connection);
mResultCode = connection->CommitWriteTransaction();
NS_WARNING_ASSERTION(NS_SUCCEEDED(mResultCode), "Commit failed!");
if (NS_SUCCEEDED(mResultCode) &&
mTransaction->GetMode() ==
IDBTransaction::Mode::ReadWriteFlush) {
mResultCode = connection->Checkpoint();
}
if (NS_SUCCEEDED(mResultCode) && fileRefcountFunction) {
fileRefcountFunction->DidCommit();
}
}
}
}
if (NS_FAILED(mResultCode)) {
if (fileRefcountFunction) {
fileRefcountFunction->DidAbort();
}
connection->RollbackWriteTransaction();
}
CommitOrRollbackAutoIncrementCounts();
connection->FinishWriteTransaction();
if (mTransaction->GetMode() == IDBTransaction::Mode::Cleanup) {
connection->DoIdleProcessing(/* aNeedsCheckpoint */ true,
/* aInterrupted */ Atomic<bool>(false));
connection->EnableQuotaChecks();
}
}
}
IDB_LOG_MARK_PARENT_TRANSACTION_REQUEST(
"Finished database work", "DB End",
IDB_LOG_ID_STRING(mBackgroundChildLoggingId),
mTransaction->LoggingSerialNumber(), mLoggingSerialNumber);
IDB_LOG_MARK_PARENT_TRANSACTION("Finished database work", "DB End",
IDB_LOG_ID_STRING(mBackgroundChildLoggingId),
mTransaction->LoggingSerialNumber());
return NS_OK;
}
void TransactionBase::CommitOp::TransactionFinishedBeforeUnblock() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mTransaction);
AUTO_PROFILER_LABEL("CommitOp::TransactionFinishedBeforeUnblock", DOM);
if (!IsActorDestroyed()) {
mTransaction->UpdateMetadata(mResultCode);
}
}
void TransactionBase::CommitOp::TransactionFinishedAfterUnblock() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mTransaction);
IDB_LOG_MARK_PARENT_TRANSACTION(
"Finished with result 0x%" PRIx32, "Transaction finished (0x%" PRIx32 ")",
IDB_LOG_ID_STRING(mTransaction->GetLoggingInfo()->Id()),
mTransaction->LoggingSerialNumber(), static_cast<uint32_t>(mResultCode));
mTransaction->SendCompleteNotification(ClampResultCode(mResultCode));
mTransaction->GetMutableDatabase().UnregisterTransaction(*mTransaction);
mTransaction = nullptr;
#ifdef DEBUG
// A bit hacky but the CommitOp is not really a normal database operation
// that is tied to an actor. Do this to make our assertions happy.
NoteActorDestroyed();
#endif
}
nsresult VersionChangeTransactionOp::SendSuccessResult() {
AssertIsOnOwningThread();
// Nothing to send here, the API assumes that this request always succeeds.
return NS_OK;
}
bool VersionChangeTransactionOp::SendFailureResult(nsresult aResultCode) {
AssertIsOnOwningThread();
// The only option here is to cause the transaction to abort.
return false;
}
void VersionChangeTransactionOp::Cleanup() {
AssertIsOnOwningThread();
#ifdef DEBUG
// A bit hacky but the VersionChangeTransactionOp is not generated in response
// to a child request like most other database operations. Do this to make our
// assertions happy.
NoteActorDestroyed();
#endif
TransactionDatabaseOperationBase::Cleanup();
}
nsresult CreateObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("CreateObjectStoreOp::DoDatabaseWork", DOM);
#ifdef DEBUG
{
// Make sure that we're not creating an object store with the same name as
// another that already exists. This should be impossible because we should
// have thrown an error long before now...
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(const bool& hasResult,
aConnection
->BorrowAndExecuteSingleStepStatement(
"SELECT name "
"FROM object_store "
"WHERE name = :name;"_ns,
[&self = *this](auto& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindStringByIndex(
0, self.mMetadata.name())));
return Ok{};
})
.map(IsSome),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(!hasResult);
}
#endif
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"INSERT INTO object_store (id, auto_increment, name, key_path) "
"VALUES (:id, :auto_increment, :name, :key_path);"_ns,
[&metadata =
mMetadata](mozIStorageStatement& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(0, metadata.id())));
QM_TRY(MOZ_TO_RESULT(
stmt.BindInt32ByIndex(1, metadata.autoIncrement() ? 1 : 0)));
QM_TRY(MOZ_TO_RESULT(stmt.BindStringByIndex(2, metadata.name())));
if (metadata.keyPath().IsValid()) {
QM_TRY(MOZ_TO_RESULT(stmt.BindStringByIndex(
3, metadata.keyPath().SerializeToString())));
} else {
QM_TRY(MOZ_TO_RESULT(stmt.BindNullByIndex(3)));
}
return Ok{};
})));
#ifdef DEBUG
{
int64_t id;
MOZ_ALWAYS_SUCCEEDS(
aConnection->MutableStorageConnection().GetLastInsertRowID(&id));
MOZ_ASSERT(mMetadata.id() == id);
}
#endif
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
return NS_OK;
}
nsresult DeleteObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("DeleteObjectStoreOp::DoDatabaseWork", DOM);
#ifdef DEBUG
{
// Make sure |mIsLastObjectStore| is telling the truth.
QM_TRY_INSPECT(
const auto& stmt,
aConnection->BorrowCachedStatement("SELECT id FROM object_store;"_ns),
QM_ASSERT_UNREACHABLE);
bool foundThisObjectStore = false;
bool foundOtherObjectStore = false;
while (true) {
bool hasResult;
MOZ_ALWAYS_SUCCEEDS(stmt->ExecuteStep(&hasResult));
if (!hasResult) {
break;
}
int64_t id;
MOZ_ALWAYS_SUCCEEDS(stmt->GetInt64(0, &id));
if (id == mMetadata->mCommonMetadata.id()) {
foundThisObjectStore = true;
} else {
foundOtherObjectStore = true;
}
}
MOZ_ASSERT_IF(mIsLastObjectStore,
foundThisObjectStore && !foundOtherObjectStore);
MOZ_ASSERT_IF(!mIsLastObjectStore,
foundThisObjectStore && foundOtherObjectStore);
}
#endif
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
if (mIsLastObjectStore) {
// We can just delete everything if this is the last object store.
QM_TRY(MOZ_TO_RESULT(
aConnection->ExecuteCachedStatement("DELETE FROM index_data;"_ns)));
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"DELETE FROM unique_index_data;"_ns)));
QM_TRY(MOZ_TO_RESULT(
aConnection->ExecuteCachedStatement("DELETE FROM object_data;"_ns)));
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"DELETE FROM object_store_index;"_ns)));
QM_TRY(MOZ_TO_RESULT(
aConnection->ExecuteCachedStatement("DELETE FROM object_store;"_ns)));
} else {
QM_TRY_INSPECT(
const bool& hasIndexes,
ObjectStoreHasIndexes(*aConnection, mMetadata->mCommonMetadata.id()));
const auto bindObjectStoreIdToFirstParameter =
[this](mozIStorageStatement& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(
stmt.BindInt64ByIndex(0, mMetadata->mCommonMetadata.id())));
return Ok{};
};
// The parameter name :object_store_id in the SQL statements below is not
// used for binding, parameters are bound by index only locally by
// bindObjectStoreIdToFirstParameter.
if (hasIndexes) {
QM_TRY(MOZ_TO_RESULT(DeleteObjectStoreDataTableRowsWithIndexes(
aConnection, mMetadata->mCommonMetadata.id(), Nothing())));
// Now clean up the object store index table.
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"DELETE FROM object_store_index "
"WHERE object_store_id = :object_store_id;"_ns,
bindObjectStoreIdToFirstParameter)));
} else {
// We only have to worry about object data if this object store has no
// indexes.
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"DELETE FROM object_data "
"WHERE object_store_id = :object_store_id;"_ns,
bindObjectStoreIdToFirstParameter)));
}
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"DELETE FROM object_store "
"WHERE id = :object_store_id;"_ns,
bindObjectStoreIdToFirstParameter)));
#ifdef DEBUG
{
int32_t deletedRowCount;
MOZ_ALWAYS_SUCCEEDS(
aConnection->MutableStorageConnection().GetAffectedRows(
&deletedRowCount));
MOZ_ASSERT(deletedRowCount == 1);
}
#endif
}
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
if (mMetadata->mCommonMetadata.autoIncrement()) {
Transaction().ForgetModifiedAutoIncrementObjectStore(*mMetadata);
}
return NS_OK;
}
nsresult RenameObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("RenameObjectStoreOp::DoDatabaseWork", DOM);
#ifdef DEBUG
{
// Make sure that we're not renaming an object store with the same name as
// another that already exists. This should be impossible because we should
// have thrown an error long before now...
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(
const bool& hasResult,
aConnection
->BorrowAndExecuteSingleStepStatement(
"SELECT name "
"FROM object_store "
"WHERE name = :name AND id != :id;"_ns,
[&self = *this](auto& stmt) -> Result<Ok, nsresult> {
QM_TRY(
MOZ_TO_RESULT(stmt.BindStringByIndex(0, self.mNewName)));
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(1, self.mId)));
return Ok{};
})
.map(IsSome),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(!hasResult);
}
#endif
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"UPDATE object_store "
"SET name = :name "
"WHERE id = :id;"_ns,
[&self = *this](mozIStorageStatement& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindStringByIndex(0, self.mNewName)));
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(1, self.mId)));
return Ok{};
})));
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
return NS_OK;
}
CreateIndexOp::CreateIndexOp(SafeRefPtr<VersionChangeTransaction> aTransaction,
const IndexOrObjectStoreId aObjectStoreId,
const IndexMetadata& aMetadata)
: VersionChangeTransactionOp(std::move(aTransaction)),
mMetadata(aMetadata),
mFileManager(Transaction().GetDatabase().GetFileManagerPtr()),
mDatabaseId(Transaction().DatabaseId()),
mObjectStoreId(aObjectStoreId) {
MOZ_ASSERT(aObjectStoreId);
MOZ_ASSERT(aMetadata.id());
MOZ_ASSERT(mFileManager);
MOZ_ASSERT(!mDatabaseId.IsEmpty());
}
nsresult CreateIndexOp::InsertDataFromObjectStore(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mMaybeUniqueIndexTable);
AUTO_PROFILER_LABEL("CreateIndexOp::InsertDataFromObjectStore", DOM);
auto& storageConnection = aConnection->MutableStorageConnection();
RefPtr<UpdateIndexDataValuesFunction> updateFunction =
new UpdateIndexDataValuesFunction(this, aConnection,
Transaction().GetDatabasePtr());
constexpr auto updateFunctionName = "update_index_data_values"_ns;
nsresult rv =
storageConnection.CreateFunction(updateFunctionName, 4, updateFunction);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
rv = InsertDataFromObjectStoreInternal(aConnection);
MOZ_ALWAYS_SUCCEEDS(storageConnection.RemoveFunction(updateFunctionName));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
nsresult CreateIndexOp::InsertDataFromObjectStoreInternal(
DatabaseConnection* aConnection) const {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mMaybeUniqueIndexTable);
MOZ_ASSERT(aConnection->HasStorageConnection());
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"UPDATE object_data "
"SET index_data_values = update_index_data_values "
"(key, index_data_values, file_ids, data) "
"WHERE object_store_id = :object_store_id;"_ns,
[objectStoredId =
mObjectStoreId](mozIStorageStatement& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(0, objectStoredId)));
return Ok{};
})));
return NS_OK;
}
bool CreateIndexOp::Init(TransactionBase& aTransaction) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(mObjectStoreId);
MOZ_ASSERT(mMaybeUniqueIndexTable.isNothing());
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
aTransaction.GetMetadataForObjectStoreId(mObjectStoreId);
MOZ_ASSERT(objectStoreMetadata);
const uint32_t indexCount = objectStoreMetadata->mIndexes.Count();
if (!indexCount) {
return true;
}
auto uniqueIndexTable = UniqueIndexTable{indexCount};
for (const auto& value : objectStoreMetadata->mIndexes.Values()) {
MOZ_ASSERT(!uniqueIndexTable.Contains(value->mCommonMetadata.id()));
if (NS_WARN_IF(!uniqueIndexTable.InsertOrUpdate(
value->mCommonMetadata.id(), value->mCommonMetadata.unique(),
fallible))) {
IDB_REPORT_INTERNAL_ERR();
NS_WARNING("out of memory");
return false;
}
}
uniqueIndexTable.MarkImmutable();
mMaybeUniqueIndexTable.emplace(std::move(uniqueIndexTable));
return true;
}
nsresult CreateIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("CreateIndexOp::DoDatabaseWork", DOM);
#ifdef DEBUG
{
// Make sure that we're not creating an index with the same name and object
// store as another that already exists. This should be impossible because
// we should have thrown an error long before now...
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(
const bool& hasResult,
aConnection
->BorrowAndExecuteSingleStepStatement(
"SELECT name "
"FROM object_store_index "
"WHERE object_store_id = :object_store_id AND name = :name;"_ns,
[&self = *this](auto& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(
stmt.BindInt64ByIndex(0, self.mObjectStoreId)));
QM_TRY(MOZ_TO_RESULT(
stmt.BindStringByIndex(1, self.mMetadata.name())));
return Ok{};
})
.map(IsSome),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(!hasResult);
}
#endif
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"INSERT INTO object_store_index (id, name, key_path, unique_index, "
"multientry, object_store_id, locale, "
"is_auto_locale) "
"VALUES (:id, :name, :key_path, :unique, :multientry, "
":object_store_id, :locale, :is_auto_locale)"_ns,
[&metadata = mMetadata, objectStoreId = mObjectStoreId](
mozIStorageStatement& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(0, metadata.id())));
QM_TRY(MOZ_TO_RESULT(stmt.BindStringByIndex(1, metadata.name())));
QM_TRY(MOZ_TO_RESULT(
stmt.BindStringByIndex(2, metadata.keyPath().SerializeToString())));
QM_TRY(
MOZ_TO_RESULT(stmt.BindInt32ByIndex(3, metadata.unique() ? 1 : 0)));
QM_TRY(MOZ_TO_RESULT(
stmt.BindInt32ByIndex(4, metadata.multiEntry() ? 1 : 0)));
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(5, objectStoreId)));
QM_TRY(MOZ_TO_RESULT(
metadata.locale().IsEmpty()
? stmt.BindNullByIndex(6)
: stmt.BindUTF8StringByIndex(6, metadata.locale())));
QM_TRY(MOZ_TO_RESULT(stmt.BindInt32ByIndex(7, metadata.autoLocale())));
return Ok{};
})));
#ifdef DEBUG
{
int64_t id;
MOZ_ALWAYS_SUCCEEDS(
aConnection->MutableStorageConnection().GetLastInsertRowID(&id));
MOZ_ASSERT(mMetadata.id() == id);
}
#endif
QM_TRY(MOZ_TO_RESULT(InsertDataFromObjectStore(aConnection)));
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
return NS_OK;
}
NS_IMPL_ISUPPORTS(CreateIndexOp::UpdateIndexDataValuesFunction,
mozIStorageFunction);
NS_IMETHODIMP
CreateIndexOp::UpdateIndexDataValuesFunction::OnFunctionCall(
mozIStorageValueArray* aValues, nsIVariant** _retval) {
MOZ_ASSERT(aValues);
MOZ_ASSERT(_retval);
MOZ_ASSERT(mConnection);
mConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mOp);
MOZ_ASSERT(mOp->mFileManager);
AUTO_PROFILER_LABEL(
"CreateIndexOp::UpdateIndexDataValuesFunction::OnFunctionCall", DOM);
#ifdef DEBUG
{
uint32_t argCount;
MOZ_ALWAYS_SUCCEEDS(aValues->GetNumEntries(&argCount));
MOZ_ASSERT(argCount == 4); // key, index_data_values, file_ids, data
int32_t valueType;
MOZ_ALWAYS_SUCCEEDS(aValues->GetTypeOfIndex(0, &valueType));
MOZ_ASSERT(valueType == mozIStorageValueArray::VALUE_TYPE_BLOB);
MOZ_ALWAYS_SUCCEEDS(aValues->GetTypeOfIndex(1, &valueType));
MOZ_ASSERT(valueType == mozIStorageValueArray::VALUE_TYPE_NULL ||
valueType == mozIStorageValueArray::VALUE_TYPE_BLOB);
MOZ_ALWAYS_SUCCEEDS(aValues->GetTypeOfIndex(2, &valueType));
MOZ_ASSERT(valueType == mozIStorageValueArray::VALUE_TYPE_NULL ||
valueType == mozIStorageValueArray::VALUE_TYPE_TEXT);
MOZ_ALWAYS_SUCCEEDS(aValues->GetTypeOfIndex(3, &valueType));
MOZ_ASSERT(valueType == mozIStorageValueArray::VALUE_TYPE_BLOB ||
valueType == mozIStorageValueArray::VALUE_TYPE_INTEGER);
}
#endif
QM_TRY_UNWRAP(auto cloneInfo, GetStructuredCloneReadInfoFromValueArray(
aValues,
/* aDataIndex */ 3,
/* aFileIdsIndex */ 2, *mOp->mFileManager));
const IndexMetadata& metadata = mOp->mMetadata;
const IndexOrObjectStoreId& objectStoreId = mOp->mObjectStoreId;
// XXX does this really need a non-const cloneInfo?
QM_TRY_INSPECT(const auto& updateInfos,
DeserializeIndexValueToUpdateInfos(
metadata.id(), metadata.keyPath(), metadata.multiEntry(),
metadata.locale(), cloneInfo));
if (updateInfos.IsEmpty()) {
// XXX See if we can do this without copying...
nsCOMPtr<nsIVariant> unmodifiedValue;
// No changes needed, just return the original value.
QM_TRY_INSPECT(const int32_t& valueType,
MOZ_TO_RESULT_INVOKE_MEMBER(aValues, GetTypeOfIndex, 1));
MOZ_ASSERT(valueType == mozIStorageValueArray::VALUE_TYPE_NULL ||
valueType == mozIStorageValueArray::VALUE_TYPE_BLOB);
if (valueType == mozIStorageValueArray::VALUE_TYPE_NULL) {
unmodifiedValue = new storage::NullVariant();
unmodifiedValue.forget(_retval);
return NS_OK;
}
MOZ_ASSERT(valueType == mozIStorageValueArray::VALUE_TYPE_BLOB);
const uint8_t* blobData;
uint32_t blobDataLength;
QM_TRY(
MOZ_TO_RESULT(aValues->GetSharedBlob(1, &blobDataLength, &blobData)));
const std::pair<uint8_t*, int> copiedBlobDataPair(
static_cast<uint8_t*>(malloc(blobDataLength)), blobDataLength);
if (!copiedBlobDataPair.first) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_OUT_OF_MEMORY;
}
memcpy(copiedBlobDataPair.first, blobData, blobDataLength);
unmodifiedValue = new storage::AdoptedBlobVariant(copiedBlobDataPair);
unmodifiedValue.forget(_retval);
return NS_OK;
}
Key key;
QM_TRY(MOZ_TO_RESULT(key.SetFromValueArray(aValues, 0)));
QM_TRY_UNWRAP(auto indexValues, ReadCompressedIndexDataValues(*aValues, 1));
const bool hadPreviousIndexValues = !indexValues.IsEmpty();
const uint32_t updateInfoCount = updateInfos.Length();
QM_TRY(OkIf(indexValues.SetCapacity(indexValues.Length() + updateInfoCount,
fallible)),
NS_ERROR_OUT_OF_MEMORY, IDB_REPORT_INTERNAL_ERR_LAMBDA);
// First construct the full list to update the index_data_values row.
for (const IndexUpdateInfo& info : updateInfos) {
MOZ_ALWAYS_TRUE(indexValues.InsertElementSorted(
IndexDataValue(metadata.id(), metadata.unique(), info.value(),
info.localizedValue()),
fallible));
}
QM_TRY_UNWRAP((auto [indexValuesBlob, indexValuesBlobLength]),
MakeCompressedIndexDataValues(indexValues));
MOZ_ASSERT(!indexValuesBlobLength == !(indexValuesBlob.get()));
nsCOMPtr<nsIVariant> value;
if (!indexValuesBlob) {
value = new storage::NullVariant();
value.forget(_retval);
return NS_OK;
}
// Now insert the new table rows. We only need to construct a new list if
// the full list is different.
if (hadPreviousIndexValues) {
indexValues.ClearAndRetainStorage();
MOZ_ASSERT(indexValues.Capacity() >= updateInfoCount);
for (const IndexUpdateInfo& info : updateInfos) {
MOZ_ALWAYS_TRUE(indexValues.InsertElementSorted(
IndexDataValue(metadata.id(), metadata.unique(), info.value(),
info.localizedValue()),
fallible));
}
}
QM_TRY(MOZ_TO_RESULT(
InsertIndexTableRows(mConnection, objectStoreId, key, indexValues)));
value = new storage::AdoptedBlobVariant(
std::pair(indexValuesBlob.release(), indexValuesBlobLength));
value.forget(_retval);
return NS_OK;
}
DeleteIndexOp::DeleteIndexOp(SafeRefPtr<VersionChangeTransaction> aTransaction,
const IndexOrObjectStoreId aObjectStoreId,
const IndexOrObjectStoreId aIndexId,
const bool aUnique, const bool aIsLastIndex)
: VersionChangeTransactionOp(std::move(aTransaction)),
mObjectStoreId(aObjectStoreId),
mIndexId(aIndexId),
mUnique(aUnique),
mIsLastIndex(aIsLastIndex) {
MOZ_ASSERT(aObjectStoreId);
MOZ_ASSERT(aIndexId);
}
nsresult DeleteIndexOp::RemoveReferencesToIndex(
DatabaseConnection* aConnection, const Key& aObjectStoreKey,
nsTArray<IndexDataValue>& aIndexValues) const {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aConnection);
MOZ_ASSERT(!aObjectStoreKey.IsUnset());
MOZ_ASSERT_IF(!mIsLastIndex, !aIndexValues.IsEmpty());
AUTO_PROFILER_LABEL("DeleteIndexOp::RemoveReferencesToIndex", DOM);
if (mIsLastIndex) {
// There is no need to parse the previous entry in the index_data_values
// column if this is the last index. Simply set it to NULL.
QM_TRY_INSPECT(const auto& stmt,
aConnection->BorrowCachedStatement(
"UPDATE object_data "
"SET index_data_values = NULL "
"WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + " AND key = :"_ns +
kStmtParamNameKey + ";"_ns));
QM_TRY(MOZ_TO_RESULT(
stmt->BindInt64ByName(kStmtParamNameObjectStoreId, mObjectStoreId)));
QM_TRY(MOZ_TO_RESULT(
aObjectStoreKey.BindToStatement(&*stmt, kStmtParamNameKey)));
QM_TRY(MOZ_TO_RESULT(stmt->Execute()));
return NS_OK;
}
{
IndexDataValue search;
search.mIndexId = mIndexId;
// Use raw pointers for search to avoid redundant index validity checks.
// Maybe this should better be encapsulated in nsTArray.
const auto* const begin = aIndexValues.Elements();
const auto* const end = aIndexValues.Elements() + aIndexValues.Length();
const auto indexIdComparator = [](const IndexDataValue& aA,
const IndexDataValue& aB) {
return aA.mIndexId < aB.mIndexId;
};
MOZ_ASSERT(std::is_sorted(begin, end, indexIdComparator));
const auto [beginRange, endRange] =
std::equal_range(begin, end, search, indexIdComparator);
if (beginRange == end) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_FILE_CORRUPTED;
}
aIndexValues.RemoveElementsAt(beginRange - begin, endRange - beginRange);
}
QM_TRY(MOZ_TO_RESULT(UpdateIndexValues(aConnection, mObjectStoreId,
aObjectStoreKey, aIndexValues)));
return NS_OK;
}
nsresult DeleteIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
#ifdef DEBUG
{
// Make sure |mIsLastIndex| is telling the truth.
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(const auto& stmt,
aConnection->BorrowCachedStatement(
"SELECT id "
"FROM object_store_index "
"WHERE object_store_id = :object_store_id;"_ns),
QM_ASSERT_UNREACHABLE);
MOZ_ALWAYS_SUCCEEDS(stmt->BindInt64ByIndex(0, mObjectStoreId));
bool foundThisIndex = false;
bool foundOtherIndex = false;
while (true) {
bool hasResult;
MOZ_ALWAYS_SUCCEEDS(stmt->ExecuteStep(&hasResult));
if (!hasResult) {
break;
}
int64_t id;
MOZ_ALWAYS_SUCCEEDS(stmt->GetInt64(0, &id));
if (id == mIndexId) {
foundThisIndex = true;
} else {
foundOtherIndex = true;
}
}
MOZ_ASSERT_IF(mIsLastIndex, foundThisIndex && !foundOtherIndex);
MOZ_ASSERT_IF(!mIsLastIndex, foundThisIndex && foundOtherIndex);
}
#endif
AUTO_PROFILER_LABEL("DeleteIndexOp::DoDatabaseWork", DOM);
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
// mozStorage warns that these statements trigger a sort operation but we
// don't care because this is a very rare call and we expect it to be slow.
// The cost of having an index on this field is too high.
QM_TRY_INSPECT(
const auto& selectStmt,
aConnection->BorrowCachedStatement(
mUnique
? (mIsLastIndex
? "/* do not warn (bug someone else) */ "
"SELECT value, object_data_key "
"FROM unique_index_data "
"WHERE index_id = :"_ns +
kStmtParamNameIndexId +
" ORDER BY object_data_key ASC;"_ns
: "/* do not warn (bug out) */ "
"SELECT unique_index_data.value, "
"unique_index_data.object_data_key, "
"object_data.index_data_values "
"FROM unique_index_data "
"JOIN object_data "
"ON unique_index_data.object_data_key = object_data.key "
"WHERE unique_index_data.index_id = :"_ns +
kStmtParamNameIndexId +
" AND object_data.object_store_id = :"_ns +
kStmtParamNameObjectStoreId +
" ORDER BY unique_index_data.object_data_key ASC;"_ns)
: (mIsLastIndex
? "/* do not warn (bug me not) */ "
"SELECT value, object_data_key "
"FROM index_data "
"WHERE index_id = :"_ns +
kStmtParamNameIndexId +
" AND object_store_id = :"_ns +
kStmtParamNameObjectStoreId +
" ORDER BY object_data_key ASC;"_ns
: "/* do not warn (bug off) */ "
"SELECT index_data.value, "
"index_data.object_data_key, "
"object_data.index_data_values "
"FROM index_data "
"JOIN object_data "
"ON index_data.object_data_key = object_data.key "
"WHERE index_data.index_id = :"_ns +
kStmtParamNameIndexId +
" AND object_data.object_store_id = :"_ns +
kStmtParamNameObjectStoreId +
" ORDER BY index_data.object_data_key ASC;"_ns)));
QM_TRY(MOZ_TO_RESULT(
selectStmt->BindInt64ByName(kStmtParamNameIndexId, mIndexId)));
if (!mUnique || !mIsLastIndex) {
QM_TRY(MOZ_TO_RESULT(selectStmt->BindInt64ByName(
kStmtParamNameObjectStoreId, mObjectStoreId)));
}
Key lastObjectStoreKey;
IndexDataValuesAutoArray lastIndexValues;
QM_TRY(CollectWhileHasResult(
*selectStmt,
[this, &aConnection, &lastObjectStoreKey, &lastIndexValues,
deleteIndexRowStmt =
DatabaseConnection::LazyStatement{
*aConnection,
mUnique
? "DELETE FROM unique_index_data "
"WHERE index_id = :"_ns +
kStmtParamNameIndexId + " AND value = :"_ns +
kStmtParamNameValue + ";"_ns
: "DELETE FROM index_data "
"WHERE index_id = :"_ns +
kStmtParamNameIndexId + " AND value = :"_ns +
kStmtParamNameValue + " AND object_data_key = :"_ns +
kStmtParamNameObjectDataKey + ";"_ns}](
auto& selectStmt) mutable -> Result<Ok, nsresult> {
// We always need the index key to delete the index row.
Key indexKey;
QM_TRY(MOZ_TO_RESULT(indexKey.SetFromStatement(&selectStmt, 0)));
QM_TRY(OkIf(!indexKey.IsUnset()), Err(NS_ERROR_FILE_CORRUPTED),
IDB_REPORT_INTERNAL_ERR_LAMBDA);
// Don't call |lastObjectStoreKey.BindToStatement()| directly because we
// don't want to copy the same key multiple times.
const uint8_t* objectStoreKeyData;
uint32_t objectStoreKeyDataLength;
QM_TRY(MOZ_TO_RESULT(selectStmt.GetSharedBlob(
1, &objectStoreKeyDataLength, &objectStoreKeyData)));
QM_TRY(OkIf(objectStoreKeyDataLength), Err(NS_ERROR_FILE_CORRUPTED),
IDB_REPORT_INTERNAL_ERR_LAMBDA);
const nsDependentCString currentObjectStoreKeyBuffer(
reinterpret_cast<const char*>(objectStoreKeyData),
objectStoreKeyDataLength);
if (currentObjectStoreKeyBuffer != lastObjectStoreKey.GetBuffer()) {
// We just walked to the next object store key.
if (!lastObjectStoreKey.IsUnset()) {
// Before we move on to the next key we need to update the previous
// key's index_data_values column.
QM_TRY(MOZ_TO_RESULT(RemoveReferencesToIndex(
aConnection, lastObjectStoreKey, lastIndexValues)));
}
// Save the object store key.
lastObjectStoreKey = Key(currentObjectStoreKeyBuffer);
// And the |index_data_values| row if this isn't the only index.
if (!mIsLastIndex) {
lastIndexValues.ClearAndRetainStorage();
QM_TRY(MOZ_TO_RESULT(
ReadCompressedIndexDataValues(selectStmt, 2, lastIndexValues)));
QM_TRY(OkIf(!lastIndexValues.IsEmpty()),
Err(NS_ERROR_FILE_CORRUPTED),
IDB_REPORT_INTERNAL_ERR_LAMBDA);
}
}
// Now delete the index row.
{
QM_TRY_INSPECT(const auto& borrowedDeleteIndexRowStmt,
deleteIndexRowStmt.Borrow());
QM_TRY(MOZ_TO_RESULT(borrowedDeleteIndexRowStmt->BindInt64ByName(
kStmtParamNameIndexId, mIndexId)));
QM_TRY(MOZ_TO_RESULT(indexKey.BindToStatement(
&*borrowedDeleteIndexRowStmt, kStmtParamNameValue)));
if (!mUnique) {
QM_TRY(MOZ_TO_RESULT(lastObjectStoreKey.BindToStatement(
&*borrowedDeleteIndexRowStmt, kStmtParamNameObjectDataKey)));
}
QM_TRY(MOZ_TO_RESULT(borrowedDeleteIndexRowStmt->Execute()));
}
return Ok{};
}));
// Take care of the last key.
if (!lastObjectStoreKey.IsUnset()) {
MOZ_ASSERT_IF(!mIsLastIndex, !lastIndexValues.IsEmpty());
QM_TRY(MOZ_TO_RESULT(RemoveReferencesToIndex(
aConnection, lastObjectStoreKey, lastIndexValues)));
}
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"DELETE FROM object_store_index "
"WHERE id = :index_id;"_ns,
[indexId =
mIndexId](mozIStorageStatement& deleteStmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(deleteStmt.BindInt64ByIndex(0, indexId)));
return Ok{};
})));
#ifdef DEBUG
{
int32_t deletedRowCount;
MOZ_ALWAYS_SUCCEEDS(aConnection->MutableStorageConnection().GetAffectedRows(
&deletedRowCount));
MOZ_ASSERT(deletedRowCount == 1);
}
#endif
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
return NS_OK;
}
nsresult RenameIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("RenameIndexOp::DoDatabaseWork", DOM);
#ifdef DEBUG
{
// Make sure that we're not renaming an index with the same name as another
// that already exists. This should be impossible because we should have
// thrown an error long before now...
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY_INSPECT(const bool& hasResult,
aConnection
->BorrowAndExecuteSingleStepStatement(
"SELECT name "
"FROM object_store_index "
"WHERE object_store_id = :object_store_id "
"AND name = :name "
"AND id != :id;"_ns,
[&self = *this](auto& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(
0, self.mObjectStoreId)));
QM_TRY(MOZ_TO_RESULT(
stmt.BindStringByIndex(1, self.mNewName)));
QM_TRY(MOZ_TO_RESULT(
stmt.BindInt64ByIndex(2, self.mIndexId)));
return Ok{};
})
.map(IsSome),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(!hasResult);
}
#else
Unused << mObjectStoreId;
#endif
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"UPDATE object_store_index "
"SET name = :name "
"WHERE id = :id;"_ns,
[&self = *this](mozIStorageStatement& stmt) -> Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindStringByIndex(0, self.mNewName)));
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByIndex(1, self.mIndexId)));
return Ok{};
})));
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
return NS_OK;
}
Result<bool, nsresult> NormalTransactionOp::ObjectStoreHasIndexes(
DatabaseConnection& aConnection, const IndexOrObjectStoreId aObjectStoreId,
const bool aMayHaveIndexes) {
aConnection.AssertIsOnConnectionThread();
MOZ_ASSERT(aObjectStoreId);
if (Transaction().GetMode() == IDBTransaction::Mode::VersionChange &&
aMayHaveIndexes) {
// If this is a version change transaction then mObjectStoreMayHaveIndexes
// could be wrong (e.g. if a unique index failed to be created due to a
// constraint error). We have to check on this thread by asking the database
// directly.
QM_TRY_RETURN(DatabaseOperationBase::ObjectStoreHasIndexes(aConnection,
aObjectStoreId));
}
#ifdef DEBUG
QM_TRY_INSPECT(
const bool& hasIndexes,
DatabaseOperationBase::ObjectStoreHasIndexes(aConnection, aObjectStoreId),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(aMayHaveIndexes == hasIndexes);
#endif
return aMayHaveIndexes;
}
Result<PreprocessParams, nsresult> NormalTransactionOp::GetPreprocessParams() {
return PreprocessParams{};
}
nsresult NormalTransactionOp::SendPreprocessInfo() {
AssertIsOnOwningThread();
MOZ_ASSERT(!IsActorDestroyed());
QM_TRY_INSPECT(const auto& params, GetPreprocessParams());
MOZ_ASSERT(params.type() != PreprocessParams::T__None);
if (NS_WARN_IF(!PBackgroundIDBRequestParent::SendPreprocess(params))) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
return NS_OK;
}
nsresult NormalTransactionOp::SendSuccessResult() {
AssertIsOnOwningThread();
if (!IsActorDestroyed()) {
static const size_t kMaxIDBMsgOverhead = 1024 * 1024 * 10; // 10MB
const uint32_t maximalSizeFromPref =
IndexedDatabaseManager::MaxSerializedMsgSize();
MOZ_ASSERT(maximalSizeFromPref > kMaxIDBMsgOverhead);
const size_t kMaxMessageSize = maximalSizeFromPref - kMaxIDBMsgOverhead;
RequestResponse response;
size_t responseSize = kMaxMessageSize;
GetResponse(response, &responseSize);
// TODO: Adjust the calculation of the response size in relevant
// GetResponse methods to account for the fallback to shared memory during
// serialization of the primary key and index keys if their size exceeds
// IPC::kMessageBufferShmemThreshold. This ensures the calculated size
// accurately reflects the actual IPC message size.
// See also bug 1945040.
if (responseSize >= kMaxMessageSize) {
nsPrintfCString warning(
"The serialized value is too large"
" (size=%zu bytes, max=%zu bytes).",
responseSize, kMaxMessageSize);
NS_WARNING(warning.get());
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
MOZ_ASSERT(response.type() != RequestResponse::T__None);
if (response.type() == RequestResponse::Tnsresult) {
MOZ_ASSERT(NS_FAILED(response.get_nsresult()));
return response.get_nsresult();
}
if (NS_WARN_IF(
!PBackgroundIDBRequestParent::Send__delete__(this, response))) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
}
#ifdef DEBUG
mResponseSent = true;
#endif
return NS_OK;
}
bool NormalTransactionOp::SendFailureResult(nsresult aResultCode) {
AssertIsOnOwningThread();
MOZ_ASSERT(NS_FAILED(aResultCode));
bool result = false;
if (!IsActorDestroyed()) {
result = PBackgroundIDBRequestParent::Send__delete__(
this, ClampResultCode(aResultCode));
}
#ifdef DEBUG
mResponseSent = true;
#endif
return result;
}
void NormalTransactionOp::Cleanup() {
AssertIsOnOwningThread();
MOZ_ASSERT_IF(!IsActorDestroyed(), mResponseSent);
TransactionDatabaseOperationBase::Cleanup();
}
void NormalTransactionOp::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnOwningThread();
NoteActorDestroyed();
// Assume ActorDestroy can happen at any time, so we can't probe the current
// state since mInternalState can be modified on any thread (only one thread
// at a time based on the state machine).
// However we can use mWaitingForContinue which is only touched on the owning
// thread. If mWaitingForContinue is true, we can also modify mInternalState
// since we are guaranteed that there are no pending runnables which would
// probe mInternalState to decide what code needs to run (there shouldn't be
// any running runnables on other threads either).
if (IsWaitingForContinue()) {
NoteContinueReceived();
}
// We don't have to handle the case when mWaitingForContinue is not true since
// it means that either nothing has been initialized yet, so nothing to
// cleanup or there are pending runnables that will detect that the actor has
// been destroyed and cleanup accordingly.
}
mozilla::ipc::IPCResult NormalTransactionOp::RecvContinue(
const PreprocessResponse& aResponse) {
AssertIsOnOwningThread();
switch (aResponse.type()) {
case PreprocessResponse::Tnsresult:
SetFailureCode(aResponse.get_nsresult());
break;
case PreprocessResponse::TObjectStoreGetPreprocessResponse:
case PreprocessResponse::TObjectStoreGetAllPreprocessResponse:
break;
default:
MOZ_CRASH("Should never get here!");
}
NoteContinueReceived();
return IPC_OK();
}
ObjectStoreAddOrPutRequestOp::ObjectStoreAddOrPutRequestOp(
SafeRefPtr<TransactionBase> aTransaction, const int64_t aRequestId,
RequestParams&& aParams)
: NormalTransactionOp(std::move(aTransaction), aRequestId),
mParams(
std::move(aParams.type() == RequestParams::TObjectStoreAddParams
? aParams.get_ObjectStoreAddParams().commonParams()
: aParams.get_ObjectStorePutParams().commonParams())),
mOriginMetadata(Transaction().GetDatabase().OriginMetadata()),
mPersistenceType(Transaction().GetDatabase().Type()),
mOverwrite(aParams.type() == RequestParams::TObjectStorePutParams),
mObjectStoreMayHaveIndexes(false) {
MOZ_ASSERT(aParams.type() == RequestParams::TObjectStoreAddParams ||
aParams.type() == RequestParams::TObjectStorePutParams);
mMetadata =
Transaction().GetMetadataForObjectStoreId(mParams.objectStoreId());
MOZ_ASSERT(mMetadata);
mObjectStoreMayHaveIndexes = mMetadata->HasLiveIndexes();
mDataOverThreshold =
snappy::MaxCompressedLength(mParams.cloneInfo().data().data.Size()) >
IndexedDatabaseManager::DataThreshold();
}
nsresult ObjectStoreAddOrPutRequestOp::RemoveOldIndexDataValues(
DatabaseConnection* aConnection) {
AssertIsOnConnectionThread();
MOZ_ASSERT(aConnection);
MOZ_ASSERT(mOverwrite);
MOZ_ASSERT(!mResponse.IsUnset());
#ifdef DEBUG
{
QM_TRY_INSPECT(const bool& hasIndexes,
DatabaseOperationBase::ObjectStoreHasIndexes(
*aConnection, mParams.objectStoreId()),
QM_ASSERT_UNREACHABLE);
MOZ_ASSERT(hasIndexes,
"Don't use this slow method if there are no indexes!");
}
#endif
QM_TRY_INSPECT(
const auto& indexValuesStmt,
aConnection->BorrowAndExecuteSingleStepStatement(
"SELECT index_data_values "
"FROM object_data "
"WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + " AND key = :"_ns +
kStmtParamNameKey + ";"_ns,
[&self = *this](auto& stmt) -> mozilla::Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByName(
kStmtParamNameObjectStoreId, self.mParams.objectStoreId())));
QM_TRY(MOZ_TO_RESULT(
self.mResponse.BindToStatement(&stmt, kStmtParamNameKey)));
return Ok{};
}));
if (indexValuesStmt) {
QM_TRY_INSPECT(const auto& existingIndexValues,
ReadCompressedIndexDataValues(**indexValuesStmt, 0));
QM_TRY(MOZ_TO_RESULT(
DeleteIndexDataTableRows(aConnection, mResponse, existingIndexValues)));
}
return NS_OK;
}
bool ObjectStoreAddOrPutRequestOp::Init(TransactionBase& aTransaction) {
AssertIsOnOwningThread();
const nsTArray<IndexUpdateInfo>& indexUpdateInfos =
mParams.indexUpdateInfos();
if (!indexUpdateInfos.IsEmpty()) {
mUniqueIndexTable.emplace();
for (const auto& updateInfo : indexUpdateInfos) {
auto indexMetadata = mMetadata->mIndexes.Lookup(updateInfo.indexId());
MOZ_ALWAYS_TRUE(indexMetadata);
MOZ_ASSERT(!(*indexMetadata)->mDeleted);
const IndexOrObjectStoreId& indexId =
(*indexMetadata)->mCommonMetadata.id();
const bool& unique = (*indexMetadata)->mCommonMetadata.unique();
MOZ_ASSERT(indexId == updateInfo.indexId());
MOZ_ASSERT_IF(!(*indexMetadata)->mCommonMetadata.multiEntry(),
!mUniqueIndexTable.ref().Contains(indexId));
if (NS_WARN_IF(!mUniqueIndexTable.ref().InsertOrUpdate(indexId, unique,
fallible))) {
return false;
}
}
} else if (mOverwrite) {
mUniqueIndexTable.emplace();
}
if (mUniqueIndexTable.isSome()) {
mUniqueIndexTable.ref().MarkImmutable();
}
QM_TRY_UNWRAP(
mStoredFileInfos,
TransformIntoNewArray(
mParams.fileAddInfos(),
[](const auto& fileAddInfo) {
MOZ_ASSERT(fileAddInfo.type() == StructuredCloneFileBase::eBlob ||
fileAddInfo.type() ==
StructuredCloneFileBase::eMutableFile);
switch (fileAddInfo.type()) {
case StructuredCloneFileBase::eBlob: {
PBackgroundIDBDatabaseFileParent* file =
fileAddInfo.file().AsParent();
MOZ_ASSERT(file);
auto* const fileActor = static_cast<DatabaseFile*>(file);
MOZ_ASSERT(fileActor);
return StoredFileInfo::CreateForBlob(
fileActor->GetFileInfoPtr(), fileActor);
}
default:
MOZ_CRASH("Should never get here!");
}
},
fallible),
false);
if (mDataOverThreshold) {
auto fileInfo =
aTransaction.GetDatabase().GetFileManager().CreateFileInfo();
if (NS_WARN_IF(!fileInfo)) {
return false;
}
mStoredFileInfos.EmplaceBack(StoredFileInfo::CreateForStructuredClone(
std::move(fileInfo),
MakeRefPtr<SCInputStream>(mParams.cloneInfo().data().data)));
}
return true;
}
nsresult ObjectStoreAddOrPutRequestOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(aConnection->HasStorageConnection());
AUTO_PROFILER_LABEL("ObjectStoreAddOrPutRequestOp::DoDatabaseWork", DOM);
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
QM_TRY_INSPECT(const bool& objectStoreHasIndexes,
ObjectStoreHasIndexes(*aConnection, mParams.objectStoreId(),
mObjectStoreMayHaveIndexes));
// This will be the final key we use.
Key& key = mResponse;
key = mParams.key();
const bool keyUnset = key.IsUnset();
const IndexOrObjectStoreId osid = mParams.objectStoreId();
// First delete old index_data_values if we're overwriting something and we
// have indexes.
if (mOverwrite && !keyUnset && objectStoreHasIndexes) {
QM_TRY(MOZ_TO_RESULT(RemoveOldIndexDataValues(aConnection)));
}
int64_t autoIncrementNum = 0;
{
// The "|| keyUnset" here is mostly a debugging tool. If a key isn't
// specified we should never have a collision and so it shouldn't matter
// if we allow overwrite or not. By not allowing overwrite we raise
// detectable errors rather than corrupting data.
const auto optReplaceDirective =
(!mOverwrite || keyUnset) ? ""_ns : "OR REPLACE "_ns;
QM_TRY_INSPECT(const auto& stmt,
aConnection->BorrowCachedStatement(
"INSERT "_ns + optReplaceDirective +
"INTO object_data "
"(object_store_id, key, file_ids, data) "
"VALUES (:"_ns +
kStmtParamNameObjectStoreId + ", :"_ns +
kStmtParamNameKey + ", :"_ns + kStmtParamNameFileIds +
", :"_ns + kStmtParamNameData + ");"_ns));
QM_TRY(MOZ_TO_RESULT(
stmt->BindInt64ByName(kStmtParamNameObjectStoreId, osid)));
const SerializedStructuredCloneWriteInfo& cloneInfo = mParams.cloneInfo();
const JSStructuredCloneData& cloneData = cloneInfo.data().data;
const size_t cloneDataSize = cloneData.Size();
MOZ_ASSERT(!keyUnset || mMetadata->mCommonMetadata.autoIncrement(),
"Should have key unless autoIncrement");
if (mMetadata->mCommonMetadata.autoIncrement()) {
if (keyUnset) {
{
const auto&& lockedAutoIncrementIds =
mMetadata->mAutoIncrementIds.Lock();
autoIncrementNum = lockedAutoIncrementIds->next;
}
MOZ_ASSERT(autoIncrementNum > 0);
if (autoIncrementNum > (1LL << 53)) {
return NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR;
}
QM_TRY(key.SetFromInteger(autoIncrementNum));
// Update index keys if primary key is preserved in child.
for (auto& updateInfo : mParams.indexUpdateInfos()) {
updateInfo.value().MaybeUpdateAutoIncrementKey(autoIncrementNum);
}
} else if (key.IsFloat()) {
double numericKey = key.ToFloat();
numericKey = std::min(numericKey, double(1LL << 53));
numericKey = floor(numericKey);
const auto&& lockedAutoIncrementIds =
mMetadata->mAutoIncrementIds.Lock();
if (numericKey >= lockedAutoIncrementIds->next) {
autoIncrementNum = numericKey;
}
}
if (keyUnset && mMetadata->mCommonMetadata.keyPath().IsValid()) {
const SerializedStructuredCloneWriteInfo& cloneInfo =
mParams.cloneInfo();
MOZ_ASSERT(cloneInfo.offsetToKeyProp());
MOZ_ASSERT(cloneDataSize > sizeof(uint64_t));
MOZ_ASSERT(cloneInfo.offsetToKeyProp() <=
(cloneDataSize - sizeof(uint64_t)));
// Special case where someone put an object into an autoIncrement'ing
// objectStore with no key in its keyPath set. We needed to figure out
// which row id we would get above before we could set that properly.
uint64_t keyPropValue =
ReinterpretDoubleAsUInt64(static_cast<double>(autoIncrementNum));
static const size_t keyPropSize = sizeof(uint64_t);
char keyPropBuffer[keyPropSize];
LittleEndian::writeUint64(keyPropBuffer, keyPropValue);
auto iter = cloneData.Start();
MOZ_ALWAYS_TRUE(cloneData.Advance(iter, cloneInfo.offsetToKeyProp()));
MOZ_ALWAYS_TRUE(
cloneData.UpdateBytes(iter, keyPropBuffer, keyPropSize));
}
}
key.BindToStatement(&*stmt, kStmtParamNameKey);
if (mDataOverThreshold) {
// The data we store in the SQLite database is a (signed) 64-bit integer.
// The flags are left-shifted 32 bits so the max value is 0xFFFFFFFF.
// The file_ids index occupies the lower 32 bits and its max is
// 0xFFFFFFFF.
static const uint32_t kCompressedFlag = (1 << 0);
uint32_t flags = 0;
flags |= kCompressedFlag;
const uint32_t index = mStoredFileInfos.Length() - 1;
const int64_t data = (uint64_t(flags) << 32) | index;
QM_TRY(MOZ_TO_RESULT(stmt->BindInt64ByName(kStmtParamNameData, data)));
} else {
AutoTArray<char, 4096> flatCloneData; // 4096 from JSStructuredCloneData
QM_TRY(OkIf(flatCloneData.SetLength(cloneDataSize, fallible)),
Err(NS_ERROR_OUT_OF_MEMORY));
{
auto iter = cloneData.Start();
MOZ_ALWAYS_TRUE(
cloneData.ReadBytes(iter, flatCloneData.Elements(), cloneDataSize));
}
// Compress the bytes before adding into the database.
const char* const uncompressed = flatCloneData.Elements();
const size_t uncompressedLength = cloneDataSize;
size_t compressedLength = snappy::MaxCompressedLength(uncompressedLength);
UniqueFreePtr<char> compressed(
static_cast<char*>(malloc(compressedLength)));
if (NS_WARN_IF(!compressed)) {
return NS_ERROR_OUT_OF_MEMORY;
}
snappy::RawCompress(uncompressed, uncompressedLength, compressed.get(),
&compressedLength);
uint8_t* const dataBuffer =
reinterpret_cast<uint8_t*>(compressed.release());
const size_t dataBufferLength = compressedLength;
QM_TRY(MOZ_TO_RESULT(stmt->BindAdoptedBlobByName(
kStmtParamNameData, dataBuffer, dataBufferLength)));
}
if (!mStoredFileInfos.IsEmpty()) {
// Moved outside the loop to allow it to be cached when demanded by the
// first write. (We may have mStoredFileInfos without any required
// writes.)
Maybe<FileHelper> fileHelper;
nsAutoString fileIds;
for (auto& storedFileInfo : mStoredFileInfos) {
MOZ_ASSERT(storedFileInfo.IsValid());
QM_TRY_INSPECT(const auto& inputStream,
storedFileInfo.GetInputStream());
if (inputStream) {
if (fileHelper.isNothing()) {
fileHelper.emplace(Transaction().GetDatabase().GetFileManagerPtr());
QM_TRY(MOZ_TO_RESULT(fileHelper->Init()),
NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR,
IDB_REPORT_INTERNAL_ERR_LAMBDA);
}
const DatabaseFileInfo& fileInfo = storedFileInfo.GetFileInfo();
const DatabaseFileManager& fileManager = fileInfo.Manager();
const auto file = fileHelper->GetFile(fileInfo);
QM_TRY(OkIf(file), NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR,
IDB_REPORT_INTERNAL_ERR_LAMBDA);
const auto journalFile = fileHelper->GetJournalFile(fileInfo);
QM_TRY(OkIf(journalFile), NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR,
IDB_REPORT_INTERNAL_ERR_LAMBDA);
nsCString fileKeyId;
fileKeyId.AppendInt(fileInfo.Id());
const auto maybeKey =
fileManager.IsInPrivateBrowsingMode()
? fileManager.MutableCipherKeyManagerRef().Get(fileKeyId)
: Nothing();
QM_TRY(MOZ_TO_RESULT(fileHelper->CreateFileFromStream(
*file, *journalFile, *inputStream,
storedFileInfo.ShouldCompress(), maybeKey))
.mapErr([](const nsresult rv) {
if (NS_ERROR_GET_MODULE(rv) !=
NS_ERROR_MODULE_DOM_INDEXEDDB) {
IDB_REPORT_INTERNAL_ERR();
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
return rv;
}),
QM_PROPAGATE,
([&fileManager, &file = *file,
&journalFile = *journalFile](const auto) {
// Try to remove the file if the copy failed.
QM_TRY(MOZ_TO_RESULT(
fileManager.SyncDeleteFile(file, journalFile)),
QM_VOID);
}));
storedFileInfo.NotifyWriteSucceeded();
}
if (!fileIds.IsEmpty()) {
fileIds.Append(' ');
}
storedFileInfo.Serialize(fileIds);
}
QM_TRY(MOZ_TO_RESULT(
stmt->BindStringByName(kStmtParamNameFileIds, fileIds)));
} else {
QM_TRY(MOZ_TO_RESULT(stmt->BindNullByName(kStmtParamNameFileIds)));
}
QM_TRY(MOZ_TO_RESULT(stmt->Execute()), QM_PROPAGATE,
[keyUnset = DebugOnly{keyUnset}](const nsresult rv) {
if (rv == NS_ERROR_STORAGE_CONSTRAINT) {
MOZ_ASSERT(!keyUnset, "Generated key had a collision!");
}
});
}
// Update our indexes if needed.
if (!mParams.indexUpdateInfos().IsEmpty()) {
MOZ_ASSERT(mUniqueIndexTable.isSome());
// Write the index_data_values column.
QM_TRY_INSPECT(const auto& indexValues,
IndexDataValuesFromUpdateInfos(mParams.indexUpdateInfos(),
mUniqueIndexTable.ref()));
QM_TRY(
MOZ_TO_RESULT(UpdateIndexValues(aConnection, osid, key, indexValues)));
QM_TRY(MOZ_TO_RESULT(
InsertIndexTableRows(aConnection, osid, key, indexValues)));
}
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
if (autoIncrementNum) {
{
auto&& lockedAutoIncrementIds = mMetadata->mAutoIncrementIds.Lock();
lockedAutoIncrementIds->next = autoIncrementNum + 1;
}
Transaction().NoteModifiedAutoIncrementObjectStore(mMetadata);
}
return NS_OK;
}
void ObjectStoreAddOrPutRequestOp::GetResponse(RequestResponse& aResponse,
size_t* aResponseSize) {
AssertIsOnOwningThread();
if (mOverwrite) {
aResponse = ObjectStorePutResponse(mResponse);
*aResponseSize = mResponse.GetBuffer().Length();
} else {
aResponse = ObjectStoreAddResponse(mResponse);
*aResponseSize = mResponse.GetBuffer().Length();
}
}
void ObjectStoreAddOrPutRequestOp::Cleanup() {
AssertIsOnOwningThread();
mStoredFileInfos.Clear();
NormalTransactionOp::Cleanup();
}
NS_IMPL_ISUPPORTS(ObjectStoreAddOrPutRequestOp::SCInputStream, nsIInputStream)
NS_IMETHODIMP
ObjectStoreAddOrPutRequestOp::SCInputStream::Close() { return NS_OK; }
NS_IMETHODIMP
ObjectStoreAddOrPutRequestOp::SCInputStream::Available(uint64_t* _retval) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
ObjectStoreAddOrPutRequestOp::SCInputStream::StreamStatus() { return NS_OK; }
NS_IMETHODIMP
ObjectStoreAddOrPutRequestOp::SCInputStream::Read(char* aBuf, uint32_t aCount,
uint32_t* _retval) {
return ReadSegments(NS_CopySegmentToBuffer, aBuf, aCount, _retval);
}
NS_IMETHODIMP
ObjectStoreAddOrPutRequestOp::SCInputStream::ReadSegments(
nsWriteSegmentFun aWriter, void* aClosure, uint32_t aCount,
uint32_t* _retval) {
*_retval = 0;
while (aCount) {
uint32_t count = std::min(uint32_t(mIter.RemainingInSegment()), aCount);
if (!count) {
// We've run out of data in the last segment.
break;
}
uint32_t written;
nsresult rv =
aWriter(this, aClosure, mIter.Data(), *_retval, count, &written);
if (NS_WARN_IF(NS_FAILED(rv))) {
// InputStreams do not propagate errors to caller.
return NS_OK;
}
// Writer should write what we asked it to write.
MOZ_ASSERT(written == count);
*_retval += count;
aCount -= count;
if (NS_WARN_IF(!mData.Advance(mIter, count))) {
// InputStreams do not propagate errors to caller.
return NS_OK;
}
}
return NS_OK;
}
NS_IMETHODIMP
ObjectStoreAddOrPutRequestOp::SCInputStream::IsNonBlocking(bool* _retval) {
*_retval = false;
return NS_OK;
}
ObjectStoreGetRequestOp::ObjectStoreGetRequestOp(
SafeRefPtr<TransactionBase> aTransaction, const int64_t aRequestId,
const RequestParams& aParams, bool aGetAll)
: NormalTransactionOp(std::move(aTransaction), aRequestId),
mObjectStoreId(aGetAll
? aParams.get_ObjectStoreGetAllParams().objectStoreId()
: aParams.get_ObjectStoreGetParams().objectStoreId()),
mDatabase(Transaction().GetDatabasePtr()),
mOptionalKeyRange(
aGetAll ? aParams.get_ObjectStoreGetAllParams().optionalKeyRange()
: Some(aParams.get_ObjectStoreGetParams().keyRange())),
mBackgroundParent(Transaction().GetBackgroundParent()),
mPreprocessInfoCount(0),
mLimit(aGetAll ? aParams.get_ObjectStoreGetAllParams().limit() : 1),
mGetAll(aGetAll) {
MOZ_ASSERT(aParams.type() == RequestParams::TObjectStoreGetParams ||
aParams.type() == RequestParams::TObjectStoreGetAllParams);
MOZ_ASSERT(mObjectStoreId);
MOZ_ASSERT(mDatabase);
MOZ_ASSERT_IF(!aGetAll, mOptionalKeyRange.isSome());
MOZ_ASSERT(mBackgroundParent);
}
template <typename T>
Result<T, nsresult> ObjectStoreGetRequestOp::ConvertResponse(
StructuredCloneReadInfoParent&& aInfo) {
T result;
static_assert(std::is_same_v<T, SerializedStructuredCloneReadInfo> ||
std::is_same_v<T, PreprocessInfo>);
if constexpr (std::is_same_v<T, SerializedStructuredCloneReadInfo>) {
result.data().data = aInfo.ReleaseData();
result.hasPreprocessInfo() = aInfo.HasPreprocessInfo();
}
QM_TRY_UNWRAP(result.files(), SerializeStructuredCloneFiles(
mDatabase, aInfo.Files(),
std::is_same_v<T, PreprocessInfo>));
return result;
}
nsresult ObjectStoreGetRequestOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT_IF(!mGetAll, mOptionalKeyRange.isSome());
MOZ_ASSERT_IF(!mGetAll, mLimit == 1);
AUTO_PROFILER_LABEL("ObjectStoreGetRequestOp::DoDatabaseWork", DOM);
const nsCString query =
"SELECT file_ids, data "
"FROM object_data "
"WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId +
MaybeGetBindingClauseForKeyRange(mOptionalKeyRange, kColumnNameKey) +
" ORDER BY key ASC"_ns +
(mLimit ? kOpenLimit + IntToCString(mLimit) : EmptyCString());
QM_TRY_INSPECT(const auto& stmt, aConnection->BorrowCachedStatement(query));
QM_TRY(MOZ_TO_RESULT(
stmt->BindInt64ByName(kStmtParamNameObjectStoreId, mObjectStoreId)));
if (mOptionalKeyRange.isSome()) {
QM_TRY(MOZ_TO_RESULT(
BindKeyRangeToStatement(mOptionalKeyRange.ref(), &*stmt)));
}
QM_TRY(CollectWhileHasResult(
*stmt, [this](auto& stmt) mutable -> mozilla::Result<Ok, nsresult> {
QM_TRY_UNWRAP(auto cloneInfo,
GetStructuredCloneReadInfoFromStatement(
&stmt, 1, 0, mDatabase->GetFileManager()));
if (cloneInfo.HasPreprocessInfo()) {
mPreprocessInfoCount++;
}
QM_TRY(OkIf(mResponse.EmplaceBack(fallible, std::move(cloneInfo))),
Err(NS_ERROR_OUT_OF_MEMORY));
return Ok{};
}));
MOZ_ASSERT_IF(!mGetAll, mResponse.Length() <= 1);
return NS_OK;
}
bool ObjectStoreGetRequestOp::HasPreprocessInfo() {
return mPreprocessInfoCount > 0;
}
Result<PreprocessParams, nsresult>
ObjectStoreGetRequestOp::GetPreprocessParams() {
AssertIsOnOwningThread();
MOZ_ASSERT(!mResponse.IsEmpty());
if (mGetAll) {
auto params = ObjectStoreGetAllPreprocessParams();
auto& preprocessInfos = params.preprocessInfos();
if (NS_WARN_IF(
!preprocessInfos.SetCapacity(mPreprocessInfoCount, fallible))) {
return Err(NS_ERROR_OUT_OF_MEMORY);
}
QM_TRY(TransformIfAbortOnErr(
std::make_move_iterator(mResponse.begin()),
std::make_move_iterator(mResponse.end()),
MakeBackInserter(preprocessInfos),
[](const auto& info) { return info.HasPreprocessInfo(); },
[&self = *this](StructuredCloneReadInfoParent&& info) {
return self.ConvertResponse<PreprocessInfo>(std::move(info));
}));
return PreprocessParams{std::move(params)};
}
auto params = ObjectStoreGetPreprocessParams();
QM_TRY_UNWRAP(params.preprocessInfo(),
ConvertResponse<PreprocessInfo>(std::move(mResponse[0])));
return PreprocessParams{std::move(params)};
}
void ObjectStoreGetRequestOp::GetResponse(RequestResponse& aResponse,
size_t* aResponseSize) {
MOZ_ASSERT_IF(mLimit, mResponse.Length() <= mLimit);
if (mGetAll) {
aResponse = ObjectStoreGetAllResponse();
*aResponseSize = 0;
if (!mResponse.IsEmpty()) {
QM_TRY_UNWRAP(
aResponse.get_ObjectStoreGetAllResponse().cloneInfos(),
TransformIntoNewArrayAbortOnErr(
std::make_move_iterator(mResponse.begin()),
std::make_move_iterator(mResponse.end()),
[this, &aResponseSize](StructuredCloneReadInfoParent&& info) {
*aResponseSize += info.Size();
return ConvertResponse<SerializedStructuredCloneReadInfo>(
std::move(info));
},
fallible),
QM_VOID, [&aResponse](const nsresult result) { aResponse = result; });
}
return;
}
aResponse = ObjectStoreGetResponse();
*aResponseSize = 0;
if (!mResponse.IsEmpty()) {
SerializedStructuredCloneReadInfo& serializedInfo =
aResponse.get_ObjectStoreGetResponse().cloneInfo();
*aResponseSize += mResponse[0].Size();
QM_TRY_UNWRAP(serializedInfo,
ConvertResponse<SerializedStructuredCloneReadInfo>(
std::move(mResponse[0])),
QM_VOID,
[&aResponse](const nsresult result) { aResponse = result; });
}
}
ObjectStoreGetKeyRequestOp::ObjectStoreGetKeyRequestOp(
SafeRefPtr<TransactionBase> aTransaction, const int64_t aRequestId,
const RequestParams& aParams, bool aGetAll)
: NormalTransactionOp(std::move(aTransaction), aRequestId),
mObjectStoreId(
aGetAll ? aParams.get_ObjectStoreGetAllKeysParams().objectStoreId()
: aParams.get_ObjectStoreGetKeyParams().objectStoreId()),
mOptionalKeyRange(
aGetAll ? aParams.get_ObjectStoreGetAllKeysParams().optionalKeyRange()
: Some(aParams.get_ObjectStoreGetKeyParams().keyRange())),
mLimit(aGetAll ? aParams.get_ObjectStoreGetAllKeysParams().limit() : 1),
mGetAll(aGetAll) {
MOZ_ASSERT(aParams.type() == RequestParams::TObjectStoreGetKeyParams ||
aParams.type() == RequestParams::TObjectStoreGetAllKeysParams);
MOZ_ASSERT(mObjectStoreId);
MOZ_ASSERT_IF(!aGetAll, mOptionalKeyRange.isSome());
}
nsresult ObjectStoreGetKeyRequestOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("ObjectStoreGetKeyRequestOp::DoDatabaseWork", DOM);
const nsCString query =
"SELECT key "
"FROM object_data "
"WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId +
MaybeGetBindingClauseForKeyRange(mOptionalKeyRange, kColumnNameKey) +
" ORDER BY key ASC"_ns +
(mLimit ? " LIMIT "_ns + IntToCString(mLimit) : EmptyCString());
QM_TRY_INSPECT(const auto& stmt, aConnection->BorrowCachedStatement(query));
nsresult rv =
stmt->BindInt64ByName(kStmtParamNameObjectStoreId, mObjectStoreId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (mOptionalKeyRange.isSome()) {
rv = BindKeyRangeToStatement(mOptionalKeyRange.ref(), &*stmt);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
QM_TRY(CollectWhileHasResult(
*stmt, [this](auto& stmt) mutable -> mozilla::Result<Ok, nsresult> {
Key* const key = mResponse.AppendElement(fallible);
QM_TRY(OkIf(key), Err(NS_ERROR_OUT_OF_MEMORY));
QM_TRY(MOZ_TO_RESULT(key->SetFromStatement(&stmt, 0)));
return Ok{};
}));
MOZ_ASSERT_IF(!mGetAll, mResponse.Length() <= 1);
return NS_OK;
}
void ObjectStoreGetKeyRequestOp::GetResponse(RequestResponse& aResponse,
size_t* aResponseSize) {
MOZ_ASSERT_IF(mLimit, mResponse.Length() <= mLimit);
if (mGetAll) {
aResponse = ObjectStoreGetAllKeysResponse();
*aResponseSize = std::accumulate(mResponse.begin(), mResponse.end(), 0u,
[](size_t old, const auto& entry) {
return old + entry.GetBuffer().Length();
});
aResponse.get_ObjectStoreGetAllKeysResponse().keys() = std::move(mResponse);
return;
}
aResponse = ObjectStoreGetKeyResponse();
*aResponseSize = 0;
if (!mResponse.IsEmpty()) {
*aResponseSize = mResponse[0].GetBuffer().Length();
aResponse.get_ObjectStoreGetKeyResponse().key() = std::move(mResponse[0]);
}
}
ObjectStoreDeleteRequestOp::ObjectStoreDeleteRequestOp(
SafeRefPtr<TransactionBase> aTransaction, const int64_t aRequestId,
const ObjectStoreDeleteParams& aParams)
: NormalTransactionOp(std::move(aTransaction), aRequestId),
mParams(aParams),
mObjectStoreMayHaveIndexes(false) {
AssertIsOnBackgroundThread();
SafeRefPtr<FullObjectStoreMetadata> metadata =
Transaction().GetMetadataForObjectStoreId(mParams.objectStoreId());
MOZ_ASSERT(metadata);
mObjectStoreMayHaveIndexes = metadata->HasLiveIndexes();
}
nsresult ObjectStoreDeleteRequestOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("ObjectStoreDeleteRequestOp::DoDatabaseWork", DOM);
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
QM_TRY_INSPECT(const bool& objectStoreHasIndexes,
ObjectStoreHasIndexes(*aConnection, mParams.objectStoreId(),
mObjectStoreMayHaveIndexes));
if (objectStoreHasIndexes) {
QM_TRY(MOZ_TO_RESULT(DeleteObjectStoreDataTableRowsWithIndexes(
aConnection, mParams.objectStoreId(), Some(mParams.keyRange()))));
} else {
const auto keyRangeClause =
GetBindingClauseForKeyRange(mParams.keyRange(), kColumnNameKey);
QM_TRY(MOZ_TO_RESULT(aConnection->ExecuteCachedStatement(
"DELETE FROM object_data "
"WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + keyRangeClause + ";"_ns,
[¶ms = mParams](
mozIStorageStatement& stmt) -> mozilla::Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByName(kStmtParamNameObjectStoreId,
params.objectStoreId())));
QM_TRY(
MOZ_TO_RESULT(BindKeyRangeToStatement(params.keyRange(), &stmt)));
return Ok{};
})));
}
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
return NS_OK;
}
ObjectStoreClearRequestOp::ObjectStoreClearRequestOp(
SafeRefPtr<TransactionBase> aTransaction, const int64_t aRequestId,
const ObjectStoreClearParams& aParams)
: NormalTransactionOp(std::move(aTransaction), aRequestId),
mParams(aParams),
mObjectStoreMayHaveIndexes(false) {
AssertIsOnBackgroundThread();
SafeRefPtr<FullObjectStoreMetadata> metadata =
Transaction().GetMetadataForObjectStoreId(mParams.objectStoreId());
MOZ_ASSERT(metadata);
mObjectStoreMayHaveIndexes = metadata->HasLiveIndexes();
}
nsresult ObjectStoreClearRequestOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("ObjectStoreClearRequestOp::DoDatabaseWork", DOM);
DatabaseConnection::AutoSavepoint autoSave;
QM_TRY(MOZ_TO_RESULT(autoSave.Start(Transaction()))
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
,
QM_PROPAGATE, MakeAutoSavepointCleanupHandler(*aConnection)
#endif
);
QM_TRY_INSPECT(const bool& objectStoreHasIndexes,
ObjectStoreHasIndexes(*aConnection, mParams.objectStoreId(),
mObjectStoreMayHaveIndexes));
// The parameter names are not used, parameters are bound by index only
// locally in the same function.
QM_TRY(MOZ_TO_RESULT(
objectStoreHasIndexes
? DeleteObjectStoreDataTableRowsWithIndexes(
aConnection, mParams.objectStoreId(), Nothing())
: aConnection->ExecuteCachedStatement(
"DELETE FROM object_data "
"WHERE object_store_id = :object_store_id;"_ns,
[objectStoreId =
mParams.objectStoreId()](mozIStorageStatement& stmt)
-> mozilla::Result<Ok, nsresult> {
QM_TRY(
MOZ_TO_RESULT(stmt.BindInt64ByIndex(0, objectStoreId)));
return Ok{};
})));
QM_TRY(MOZ_TO_RESULT(autoSave.Commit()));
return NS_OK;
}
nsresult ObjectStoreCountRequestOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("ObjectStoreCountRequestOp::DoDatabaseWork", DOM);
const auto keyRangeClause = MaybeGetBindingClauseForKeyRange(
mParams.optionalKeyRange(), kColumnNameKey);
QM_TRY_INSPECT(
const auto& maybeStmt,
aConnection->BorrowAndExecuteSingleStepStatement(
"SELECT count(*) "
"FROM object_data "
"WHERE object_store_id = :"_ns +
kStmtParamNameObjectStoreId + keyRangeClause,
[¶ms = mParams](auto& stmt) -> mozilla::Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByName(
kStmtParamNameObjectStoreId, params.objectStoreId())));
if (params.optionalKeyRange().isSome()) {
QM_TRY(MOZ_TO_RESULT(BindKeyRangeToStatement(
params.optionalKeyRange().ref(), &stmt)));
}
return Ok{};
}));
QM_TRY(OkIf(maybeStmt.isSome()), NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR,
[](const auto) {
// XXX Why do we have an assertion here, but not at most other
// places using IDB_REPORT_INTERNAL_ERR(_LAMBDA)?
MOZ_ASSERT(false, "This should never be possible!");
IDB_REPORT_INTERNAL_ERR();
});
const auto& stmt = *maybeStmt;
const int64_t count = stmt->AsInt64(0);
QM_TRY(OkIf(count >= 0), NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR, [](const auto) {
// XXX Why do we have an assertion here, but not at most other places using
// IDB_REPORT_INTERNAL_ERR(_LAMBDA)?
MOZ_ASSERT(false, "This should never be possible!");
IDB_REPORT_INTERNAL_ERR();
});
mResponse.count() = count;
return NS_OK;
}
// static
SafeRefPtr<FullIndexMetadata> IndexRequestOpBase::IndexMetadataForParams(
const TransactionBase& aTransaction, const RequestParams& aParams) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aParams.type() == RequestParams::TIndexGetParams ||
aParams.type() == RequestParams::TIndexGetKeyParams ||
aParams.type() == RequestParams::TIndexGetAllParams ||
aParams.type() == RequestParams::TIndexGetAllKeysParams ||
aParams.type() == RequestParams::TIndexCountParams);
IndexOrObjectStoreId objectStoreId;
IndexOrObjectStoreId indexId;
switch (aParams.type()) {
case RequestParams::TIndexGetParams: {
const IndexGetParams& params = aParams.get_IndexGetParams();
objectStoreId = params.objectStoreId();
indexId = params.indexId();
break;
}
case RequestParams::TIndexGetKeyParams: {
const IndexGetKeyParams& params = aParams.get_IndexGetKeyParams();
objectStoreId = params.objectStoreId();
indexId = params.indexId();
break;
}
case RequestParams::TIndexGetAllParams: {
const IndexGetAllParams& params = aParams.get_IndexGetAllParams();
objectStoreId = params.objectStoreId();
indexId = params.indexId();
break;
}
case RequestParams::TIndexGetAllKeysParams: {
const IndexGetAllKeysParams& params = aParams.get_IndexGetAllKeysParams();
objectStoreId = params.objectStoreId();
indexId = params.indexId();
break;
}
case RequestParams::TIndexCountParams: {
const IndexCountParams& params = aParams.get_IndexCountParams();
objectStoreId = params.objectStoreId();
indexId = params.indexId();
break;
}
default:
MOZ_CRASH("Should never get here!");
}
const SafeRefPtr<FullObjectStoreMetadata> objectStoreMetadata =
aTransaction.GetMetadataForObjectStoreId(objectStoreId);
MOZ_ASSERT(objectStoreMetadata);
SafeRefPtr<FullIndexMetadata> indexMetadata =
aTransaction.GetMetadataForIndexId(*objectStoreMetadata, indexId);
MOZ_ASSERT(indexMetadata);
return indexMetadata;
}
IndexGetRequestOp::IndexGetRequestOp(SafeRefPtr<TransactionBase> aTransaction,
const int64_t aRequestId,
const RequestParams& aParams, bool aGetAll)
: IndexRequestOpBase(std::move(aTransaction), aRequestId, aParams),
mDatabase(Transaction().GetDatabasePtr()),
mOptionalKeyRange(aGetAll
? aParams.get_IndexGetAllParams().optionalKeyRange()
: Some(aParams.get_IndexGetParams().keyRange())),
mBackgroundParent(Transaction().GetBackgroundParent()),
mLimit(aGetAll ? aParams.get_IndexGetAllParams().limit() : 1),
mGetAll(aGetAll) {
MOZ_ASSERT(aParams.type() == RequestParams::TIndexGetParams ||
aParams.type() == RequestParams::TIndexGetAllParams);
MOZ_ASSERT(mDatabase);
MOZ_ASSERT_IF(!aGetAll, mOptionalKeyRange.isSome());
MOZ_ASSERT(mBackgroundParent);
}
nsresult IndexGetRequestOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT_IF(!mGetAll, mOptionalKeyRange.isSome());
MOZ_ASSERT_IF(!mGetAll, mLimit == 1);
AUTO_PROFILER_LABEL("IndexGetRequestOp::DoDatabaseWork", DOM);
const auto indexTable = mMetadata->mCommonMetadata.unique()
? "unique_index_data "_ns
: "index_data "_ns;
QM_TRY_INSPECT(
const auto& stmt,
aConnection->BorrowCachedStatement(
"SELECT file_ids, data "
"FROM object_data "
"INNER JOIN "_ns +
indexTable +
"AS index_table "
"ON object_data.object_store_id = "
"index_table.object_store_id "
"AND object_data.key = "
"index_table.object_data_key "
"WHERE index_id = :"_ns +
kStmtParamNameIndexId +
MaybeGetBindingClauseForKeyRange(mOptionalKeyRange,
kColumnNameValue) +
(mLimit ? kOpenLimit + IntToCString(mLimit) : EmptyCString())));
QM_TRY(MOZ_TO_RESULT(stmt->BindInt64ByName(kStmtParamNameIndexId,
mMetadata->mCommonMetadata.id())));
if (mOptionalKeyRange.isSome()) {
QM_TRY(MOZ_TO_RESULT(
BindKeyRangeToStatement(mOptionalKeyRange.ref(), &*stmt)));
}
QM_TRY(CollectWhileHasResult(
*stmt, [this](auto& stmt) mutable -> mozilla::Result<Ok, nsresult> {
QM_TRY_UNWRAP(auto cloneInfo,
GetStructuredCloneReadInfoFromStatement(
&stmt, 1, 0, mDatabase->GetFileManager()));
if (cloneInfo.HasPreprocessInfo()) {
IDB_WARNING("Preprocessing for indexes not yet implemented!");
return Err(NS_ERROR_NOT_IMPLEMENTED);
}
QM_TRY(OkIf(mResponse.EmplaceBack(fallible, std::move(cloneInfo))),
Err(NS_ERROR_OUT_OF_MEMORY));
return Ok{};
}));
MOZ_ASSERT_IF(!mGetAll, mResponse.Length() <= 1);
return NS_OK;
}
// XXX This is more or less a duplicate of ObjectStoreGetRequestOp::GetResponse
void IndexGetRequestOp::GetResponse(RequestResponse& aResponse,
size_t* aResponseSize) {
MOZ_ASSERT_IF(!mGetAll, mResponse.Length() <= 1);
auto convertResponse = [this](StructuredCloneReadInfoParent&& info)
-> mozilla::Result<SerializedStructuredCloneReadInfo, nsresult> {
SerializedStructuredCloneReadInfo result;
result.data().data = info.ReleaseData();
QM_TRY_UNWRAP(result.files(), SerializeStructuredCloneFiles(
mDatabase, info.Files(), false));
return result;
};
if (mGetAll) {
aResponse = IndexGetAllResponse();
*aResponseSize = 0;
if (!mResponse.IsEmpty()) {
QM_TRY_UNWRAP(
aResponse.get_IndexGetAllResponse().cloneInfos(),
TransformIntoNewArrayAbortOnErr(
std::make_move_iterator(mResponse.begin()),
std::make_move_iterator(mResponse.end()),
[convertResponse,
&aResponseSize](StructuredCloneReadInfoParent&& info) {
*aResponseSize += info.Size();
return convertResponse(std::move(info));
},
fallible),
QM_VOID, [&aResponse](const nsresult result) { aResponse = result; });
}
return;
}
aResponse = IndexGetResponse();
*aResponseSize = 0;
if (!mResponse.IsEmpty()) {
SerializedStructuredCloneReadInfo& serializedInfo =
aResponse.get_IndexGetResponse().cloneInfo();
*aResponseSize += mResponse[0].Size();
QM_TRY_UNWRAP(serializedInfo, convertResponse(std::move(mResponse[0])),
QM_VOID,
[&aResponse](const nsresult result) { aResponse = result; });
}
}
IndexGetKeyRequestOp::IndexGetKeyRequestOp(
SafeRefPtr<TransactionBase> aTransaction, const int64_t aRequestId,
const RequestParams& aParams, bool aGetAll)
: IndexRequestOpBase(std::move(aTransaction), aRequestId, aParams),
mOptionalKeyRange(
aGetAll ? aParams.get_IndexGetAllKeysParams().optionalKeyRange()
: Some(aParams.get_IndexGetKeyParams().keyRange())),
mLimit(aGetAll ? aParams.get_IndexGetAllKeysParams().limit() : 1),
mGetAll(aGetAll) {
MOZ_ASSERT(aParams.type() == RequestParams::TIndexGetKeyParams ||
aParams.type() == RequestParams::TIndexGetAllKeysParams);
MOZ_ASSERT_IF(!aGetAll, mOptionalKeyRange.isSome());
}
nsresult IndexGetKeyRequestOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT_IF(!mGetAll, mOptionalKeyRange.isSome());
MOZ_ASSERT_IF(!mGetAll, mLimit == 1);
AUTO_PROFILER_LABEL("IndexGetKeyRequestOp::DoDatabaseWork", DOM);
const bool hasKeyRange = mOptionalKeyRange.isSome();
const auto indexTable = mMetadata->mCommonMetadata.unique()
? "unique_index_data "_ns
: "index_data "_ns;
const nsCString query =
"SELECT object_data_key "
"FROM "_ns +
indexTable + "WHERE index_id = :"_ns + kStmtParamNameIndexId +
MaybeGetBindingClauseForKeyRange(mOptionalKeyRange, kColumnNameValue) +
(mLimit ? kOpenLimit + IntToCString(mLimit) : EmptyCString());
QM_TRY_INSPECT(const auto& stmt, aConnection->BorrowCachedStatement(query));
QM_TRY(MOZ_TO_RESULT(stmt->BindInt64ByName(kStmtParamNameIndexId,
mMetadata->mCommonMetadata.id())));
if (hasKeyRange) {
QM_TRY(MOZ_TO_RESULT(
BindKeyRangeToStatement(mOptionalKeyRange.ref(), &*stmt)));
}
QM_TRY(CollectWhileHasResult(
*stmt, [this](auto& stmt) mutable -> mozilla::Result<Ok, nsresult> {
Key* const key = mResponse.AppendElement(fallible);
QM_TRY(OkIf(key), Err(NS_ERROR_OUT_OF_MEMORY));
QM_TRY(MOZ_TO_RESULT(key->SetFromStatement(&stmt, 0)));
return Ok{};
}));
MOZ_ASSERT_IF(!mGetAll, mResponse.Length() <= 1);
return NS_OK;
}
void IndexGetKeyRequestOp::GetResponse(RequestResponse& aResponse,
size_t* aResponseSize) {
MOZ_ASSERT_IF(!mGetAll, mResponse.Length() <= 1);
if (mGetAll) {
aResponse = IndexGetAllKeysResponse();
*aResponseSize = std::accumulate(mResponse.begin(), mResponse.end(), 0u,
[](size_t old, const auto& entry) {
return old + entry.GetBuffer().Length();
});
aResponse.get_IndexGetAllKeysResponse().keys() = std::move(mResponse);
return;
}
aResponse = IndexGetKeyResponse();
*aResponseSize = 0;
if (!mResponse.IsEmpty()) {
*aResponseSize = mResponse[0].GetBuffer().Length();
aResponse.get_IndexGetKeyResponse().key() = std::move(mResponse[0]);
}
}
nsresult IndexCountRequestOp::DoDatabaseWork(DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
AUTO_PROFILER_LABEL("IndexCountRequestOp::DoDatabaseWork", DOM);
const auto indexTable = mMetadata->mCommonMetadata.unique()
? "unique_index_data "_ns
: "index_data "_ns;
const auto keyRangeClause = MaybeGetBindingClauseForKeyRange(
mParams.optionalKeyRange(), kColumnNameValue);
QM_TRY_INSPECT(
const auto& maybeStmt,
aConnection->BorrowAndExecuteSingleStepStatement(
"SELECT count(*) "
"FROM "_ns +
indexTable + "WHERE index_id = :"_ns + kStmtParamNameIndexId +
keyRangeClause,
[&self = *this](auto& stmt) -> mozilla::Result<Ok, nsresult> {
QM_TRY(MOZ_TO_RESULT(stmt.BindInt64ByName(
kStmtParamNameIndexId, self.mMetadata->mCommonMetadata.id())));
if (self.mParams.optionalKeyRange().isSome()) {
QM_TRY(MOZ_TO_RESULT(BindKeyRangeToStatement(
self.mParams.optionalKeyRange().ref(), &stmt)));
}
return Ok{};
}));
QM_TRY(OkIf(maybeStmt.isSome()), NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR,
[](const auto) {
// XXX Why do we have an assertion here, but not at most other
// places using IDB_REPORT_INTERNAL_ERR(_LAMBDA)?
MOZ_ASSERT(false, "This should never be possible!");
IDB_REPORT_INTERNAL_ERR();
});
const auto& stmt = *maybeStmt;
const int64_t count = stmt->AsInt64(0);
QM_TRY(OkIf(count >= 0), NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR, [](const auto) {
// XXX Why do we have an assertion here, but not at most other places using
// IDB_REPORT_INTERNAL_ERR(_LAMBDA)?
MOZ_ASSERT(false, "This should never be possible!");
IDB_REPORT_INTERNAL_ERR();
});
mResponse.count() = count;
return NS_OK;
}
template <IDBCursorType CursorType>
bool Cursor<CursorType>::CursorOpBase::SendFailureResult(nsresult aResultCode) {
AssertIsOnOwningThread();
MOZ_ASSERT(NS_FAILED(aResultCode));
MOZ_ASSERT(mCursor);
MOZ_ASSERT(mCursor->mCurrentlyRunningOp == this);
MOZ_ASSERT(!mResponseSent);
if (!IsActorDestroyed()) {
mResponse = ClampResultCode(aResultCode);
// This is an expected race when the transaction is invalidated after
// data is retrieved from database.
//
// TODO: There seem to be other cases when mFiles is non-empty here, which
// have been present before adding cursor preloading, but with cursor
// preloading they have become more frequent (also during startup). One
// possible cause with cursor preloading is to be addressed by Bug 1597191.
NS_WARNING_ASSERTION(
!mFiles.IsEmpty() && !Transaction().IsInvalidated(),
"Expected empty mFiles when transaction has not been invalidated");
// SendResponseInternal will assert when mResponse.type() is
// CursorResponse::Tnsresult and mFiles is non-empty, so we clear mFiles
// here.
mFiles.Clear();
mCursor->SendResponseInternal(mResponse, mFiles);
}
#ifdef DEBUG
mResponseSent = true;
#endif
return false;
}
template <IDBCursorType CursorType>
void Cursor<CursorType>::CursorOpBase::Cleanup() {
AssertIsOnOwningThread();
MOZ_ASSERT(mCursor);
MOZ_ASSERT_IF(!IsActorDestroyed(), mResponseSent);
mCursor = nullptr;
#ifdef DEBUG
// A bit hacky but the CursorOp request is not generated in response to a
// child request like most other database operations. Do this to make our
// assertions happy.
NoteActorDestroyed();
#endif
TransactionDatabaseOperationBase::Cleanup();
}
template <IDBCursorType CursorType>
ResponseSizeOrError
CursorOpBaseHelperBase<CursorType>::PopulateResponseFromStatement(
mozIStorageStatement* const aStmt, const bool aInitializeResponse,
Key* const aOptOutSortKey) {
mOp.Transaction().AssertIsOnConnectionThread();
MOZ_ASSERT_IF(aInitializeResponse,
mOp.mResponse.type() == CursorResponse::T__None);
MOZ_ASSERT_IF(!aInitializeResponse,
mOp.mResponse.type() != CursorResponse::T__None);
MOZ_ASSERT_IF(
mOp.mFiles.IsEmpty() &&
(mOp.mResponse.type() ==
CursorResponse::TArrayOfObjectStoreCursorResponse ||
mOp.mResponse.type() == CursorResponse::TArrayOfIndexCursorResponse),
aInitializeResponse);
auto populateResponseHelper = PopulateResponseHelper<CursorType>{mOp};
auto previousKey = aOptOutSortKey ? std::move(*aOptOutSortKey) : Key{};
QM_TRY(MOZ_TO_RESULT(populateResponseHelper.GetKeys(aStmt, aOptOutSortKey)));
// aOptOutSortKey must be set iff the cursor is a unique cursor. For unique
// cursors, we need to skip records with the same key. The SQL queries
// currently do not filter these out.
if (aOptOutSortKey && !previousKey.IsUnset() &&
previousKey == *aOptOutSortKey) {
return 0;
}
QM_TRY(MOZ_TO_RESULT(
populateResponseHelper.MaybeGetCloneInfo(aStmt, GetCursor())));
// CAUTION: It is important that only the part of the function above this
// comment may fail, and modifications to the data structure (in particular
// mResponse and mFiles) may only be made below. This is necessary to allow to
// discard entries that were attempted to be preloaded without causing an
// inconsistent state.
if (aInitializeResponse) {
mOp.mResponse = std::remove_reference_t<
decltype(populateResponseHelper.GetTypedResponse(&mOp.mResponse))>();
}
auto& responses = populateResponseHelper.GetTypedResponse(&mOp.mResponse);
auto& response = *responses.AppendElement();
populateResponseHelper.FillKeys(response);
if constexpr (!CursorTypeTraits<CursorType>::IsKeyOnlyCursor) {
populateResponseHelper.MaybeFillCloneInfo(response, &mOp.mFiles);
}
return populateResponseHelper.GetKeySize(response) +
populateResponseHelper.MaybeGetCloneInfoSize(response);
}
template <IDBCursorType CursorType>
void CursorOpBaseHelperBase<CursorType>::PopulateExtraResponses(
mozIStorageStatement* const aStmt, const uint32_t aMaxExtraCount,
const size_t aInitialResponseSize, const nsACString& aOperation,
Key* const aOptPreviousSortKey) {
mOp.AssertIsOnConnectionThread();
const auto extraCount = [&]() -> uint32_t {
auto accumulatedResponseSize = aInitialResponseSize;
uint32_t extraCount = 0;
do {
bool hasResult;
nsresult rv = aStmt->ExecuteStep(&hasResult);
if (NS_WARN_IF(NS_FAILED(rv))) {
// In case of a failure on one step, do not attempt to execute further
// steps, but use the results already populated.
break;
}
if (!hasResult) {
break;
}
// PopulateResponseFromStatement does not modify the data in case of
// failure, so we can just use the results already populated, and discard
// any remaining entries, and signal overall success. Probably, future
// attempts to access the same entry will fail as well, but it might never
// be accessed by the application.
QM_TRY_INSPECT(
const auto& responseSize,
PopulateResponseFromStatement(aStmt, false, aOptPreviousSortKey),
extraCount, [](const auto&) {
// TODO: Maybe disable preloading for this cursor? The problem will
// probably reoccur on the next attempt, and disabling preloading
// will reduce latency. However, if some problematic entry will be
// skipped over, after that it might be fine again. To judge this,
// the causes for such failures would need to be analyzed more
// thoroughly. Since this seems to be rare, maybe no further action
// is necessary at all.
});
// Check accumulated size of individual responses and maybe break early.
accumulatedResponseSize += responseSize;
if (accumulatedResponseSize > IPC::Channel::kMaximumMessageSize / 2) {
IDB_LOG_MARK_PARENT_TRANSACTION_REQUEST(
"PRELOAD: %s: Dropping entries because maximum message size is "
"exceeded: %" PRIu32 "/%zu bytes",
"%.0s Dropping too large (%" PRIu32 "/%zu)",
IDB_LOG_ID_STRING(mOp.mBackgroundChildLoggingId),
mOp.mTransactionLoggingSerialNumber, mOp.mLoggingSerialNumber,
PromiseFlatCString(aOperation).get(), extraCount,
accumulatedResponseSize);
break;
}
// TODO: Do not count entries skipped for unique cursors.
++extraCount;
} while (true);
return extraCount;
}();
IDB_LOG_MARK_PARENT_TRANSACTION_REQUEST(
"PRELOAD: %s: Number of extra results populated: %" PRIu32 "/%" PRIu32,
"%.0s Populated (%" PRIu32 "/%" PRIu32 ")",
IDB_LOG_ID_STRING(mOp.mBackgroundChildLoggingId),
mOp.mTransactionLoggingSerialNumber, mOp.mLoggingSerialNumber,
PromiseFlatCString(aOperation).get(), extraCount, aMaxExtraCount);
}
template <IDBCursorType CursorType>
void Cursor<CursorType>::SetOptionalKeyRange(
const Maybe<SerializedKeyRange>& aOptionalKeyRange, bool* const aOpen) {
MOZ_ASSERT(aOpen);
Key localeAwareRangeBound;
if (aOptionalKeyRange.isSome()) {
const SerializedKeyRange& range = aOptionalKeyRange.ref();
const bool lowerBound = !IsIncreasingOrder(mDirection);
*aOpen =
!range.isOnly() && (lowerBound ? range.lowerOpen() : range.upperOpen());
const auto& bound =
(range.isOnly() || lowerBound) ? range.lower() : range.upper();
if constexpr (IsIndexCursor) {
if (this->IsLocaleAware()) {
// XXX Don't we need to propagate the error?
QM_TRY_UNWRAP(localeAwareRangeBound,
bound.ToLocaleAwareKey(this->mLocale), QM_VOID);
} else {
localeAwareRangeBound = bound;
}
} else {
localeAwareRangeBound = bound;
}
} else {
*aOpen = false;
}
this->mLocaleAwareRangeBound.init(std::move(localeAwareRangeBound));
}
template <IDBCursorType CursorType>
void ObjectStoreOpenOpHelper<CursorType>::PrepareKeyConditionClauses(
const nsACString& aDirectionClause, const nsACString& aQueryStart) {
const bool isIncreasingOrder = IsIncreasingOrder(GetCursor().mDirection);
nsAutoCString keyRangeClause;
nsAutoCString continueToKeyRangeClause;
AppendConditionClause(kStmtParamNameKey, kStmtParamNameCurrentKey,
!isIncreasingOrder, false, keyRangeClause);
AppendConditionClause(kStmtParamNameKey, kStmtParamNameCurrentKey,
!isIncreasingOrder, true, continueToKeyRangeClause);
{
bool open;
GetCursor().SetOptionalKeyRange(GetOptionalKeyRange(), &open);
if (GetOptionalKeyRange().isSome() &&
!GetCursor().mLocaleAwareRangeBound->IsUnset()) {
AppendConditionClause(kStmtParamNameKey, kStmtParamNameRangeBound,
isIncreasingOrder, !open, keyRangeClause);
AppendConditionClause(kStmtParamNameKey, kStmtParamNameRangeBound,
isIncreasingOrder, !open, continueToKeyRangeClause);
}
}
const nsAutoCString suffix =
aDirectionClause + kOpenLimit + ":"_ns + kStmtParamNameLimit;
GetCursor().mContinueQueries.init(
aQueryStart + keyRangeClause + suffix,
aQueryStart + continueToKeyRangeClause + suffix);
}
template <IDBCursorType CursorType>
void IndexOpenOpHelper<CursorType>::PrepareIndexKeyConditionClause(
const nsACString& aDirectionClause,
const nsLiteralCString& aObjectDataKeyPrefix, nsAutoCString aQueryStart) {
const bool isIncreasingOrder = IsIncreasingOrder(GetCursor().mDirection);
{
bool open;
GetCursor().SetOptionalKeyRange(GetOptionalKeyRange(), &open);
if (GetOptionalKeyRange().isSome() &&
!GetCursor().mLocaleAwareRangeBound->IsUnset()) {
AppendConditionClause(kColumnNameAliasSortKey, kStmtParamNameRangeBound,
isIncreasingOrder, !open, aQueryStart);
}
}
nsCString continueQuery, continueToQuery, continuePrimaryKeyQuery;
continueToQuery =
aQueryStart + " AND "_ns +
GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterOrEquals
: ComparisonOperator::LessOrEquals,
kStmtParamNameCurrentKey);
switch (GetCursor().mDirection) {
case IDBCursorDirection::Next:
case IDBCursorDirection::Prev:
continueQuery =
aQueryStart + " AND "_ns +
GetSortKeyClause(isIncreasingOrder
? ComparisonOperator::GreaterOrEquals
: ComparisonOperator::LessOrEquals,
kStmtParamNameCurrentKey) +
" AND ( "_ns +
GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterThan
: ComparisonOperator::LessThan,
kStmtParamNameCurrentKey) +
" OR "_ns +
GetKeyClause(aObjectDataKeyPrefix + "object_data_key"_ns,
isIncreasingOrder ? ComparisonOperator::GreaterThan
: ComparisonOperator::LessThan,
kStmtParamNameObjectStorePosition) +
" ) "_ns;
continuePrimaryKeyQuery =
aQueryStart +
" AND ("
"("_ns +
GetSortKeyClause(ComparisonOperator::Equals,
kStmtParamNameCurrentKey) +
" AND "_ns +
GetKeyClause(aObjectDataKeyPrefix + "object_data_key"_ns,
isIncreasingOrder ? ComparisonOperator::GreaterOrEquals
: ComparisonOperator::LessOrEquals,
kStmtParamNameObjectStorePosition) +
") OR "_ns +
GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterThan
: ComparisonOperator::LessThan,
kStmtParamNameCurrentKey) +
")"_ns;
break;
case IDBCursorDirection::Nextunique:
case IDBCursorDirection::Prevunique:
continueQuery =
aQueryStart + " AND "_ns +
GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterThan
: ComparisonOperator::LessThan,
kStmtParamNameCurrentKey);
break;
default:
MOZ_CRASH("Should never get here!");
}
const nsAutoCString suffix =
aDirectionClause + kOpenLimit + ":"_ns + kStmtParamNameLimit;
continueQuery += suffix;
continueToQuery += suffix;
if (!continuePrimaryKeyQuery.IsEmpty()) {
continuePrimaryKeyQuery += suffix;
}
GetCursor().mContinueQueries.init(std::move(continueQuery),
std::move(continueToQuery),
std::move(continuePrimaryKeyQuery));
}
template <IDBCursorType CursorType>
nsresult CommonOpenOpHelper<CursorType>::ProcessStatementSteps(
mozIStorageStatement* const aStmt) {
QM_TRY_INSPECT(const bool& hasResult,
MOZ_TO_RESULT_INVOKE_MEMBER(aStmt, ExecuteStep));
if (!hasResult) {
SetResponse(void_t{});
return NS_OK;
}
Key previousKey;
auto* optPreviousKey =
IsUnique(GetCursor().mDirection) ? &previousKey : nullptr;
QM_TRY_INSPECT(const auto& responseSize,
PopulateResponseFromStatement(aStmt, true, optPreviousKey));
// The degree to which extra responses on OpenOp can actually be used depends
// on the parameters of subsequent ContinueOp operations, see also comment in
// ContinueOp::DoDatabaseWork.
//
// TODO: We should somehow evaluate the effects of this. Maybe use a smaller
// extra count than for ContinueOp?
PopulateExtraResponses(aStmt, GetCursor().mMaxExtraCount, responseSize,
"OpenOp"_ns, optPreviousKey);
return NS_OK;
}
nsresult OpenOpHelper<IDBCursorType::ObjectStore>::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(GetCursor().mObjectStoreId);
AUTO_PROFILER_LABEL("Cursor::OpenOp::DoObjectStoreDatabaseWork", DOM);
const bool usingKeyRange = GetOptionalKeyRange().isSome();
const nsCString queryStart = "SELECT "_ns + kColumnNameKey +
", file_ids, data "
"FROM object_data "
"WHERE object_store_id = :"_ns +
kStmtParamNameId;
const auto keyRangeClause =
DatabaseOperationBase::MaybeGetBindingClauseForKeyRange(
GetOptionalKeyRange(), kColumnNameKey);
const auto& directionClause = MakeDirectionClause(GetCursor().mDirection);
// Note: Changing the number or order of SELECT columns in the query will
// require changes to CursorOpBase::PopulateResponseFromStatement.
const nsCString firstQuery = queryStart + keyRangeClause + directionClause +
kOpenLimit +
IntToCString(1 + GetCursor().mMaxExtraCount);
QM_TRY_INSPECT(const auto& stmt,
aConnection->BorrowCachedStatement(firstQuery));
QM_TRY(MOZ_TO_RESULT(
stmt->BindInt64ByName(kStmtParamNameId, GetCursor().mObjectStoreId)));
if (usingKeyRange) {
QM_TRY(MOZ_TO_RESULT(DatabaseOperationBase::BindKeyRangeToStatement(
GetOptionalKeyRange().ref(), &*stmt)));
}
// Now we need to make the query for ContinueOp.
PrepareKeyConditionClauses(directionClause, queryStart);
return ProcessStatementSteps(&*stmt);
}
nsresult OpenOpHelper<IDBCursorType::ObjectStoreKey>::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(GetCursor().mObjectStoreId);
AUTO_PROFILER_LABEL("Cursor::OpenOp::DoObjectStoreKeyDatabaseWork", DOM);
const bool usingKeyRange = GetOptionalKeyRange().isSome();
const nsCString queryStart = "SELECT "_ns + kColumnNameKey +
" FROM object_data "
"WHERE object_store_id = :"_ns +
kStmtParamNameId;
const auto keyRangeClause =
DatabaseOperationBase::MaybeGetBindingClauseForKeyRange(
GetOptionalKeyRange(), kColumnNameKey);
const auto& directionClause = MakeDirectionClause(GetCursor().mDirection);
// Note: Changing the number or order of SELECT columns in the query will
// require changes to CursorOpBase::PopulateResponseFromStatement.
const nsCString firstQuery =
queryStart + keyRangeClause + directionClause + kOpenLimit + "1"_ns;
QM_TRY_INSPECT(const auto& stmt,
aConnection->BorrowCachedStatement(firstQuery));
QM_TRY(MOZ_TO_RESULT(
stmt->BindInt64ByName(kStmtParamNameId, GetCursor().mObjectStoreId)));
if (usingKeyRange) {
QM_TRY(MOZ_TO_RESULT(DatabaseOperationBase::BindKeyRangeToStatement(
GetOptionalKeyRange().ref(), &*stmt)));
}
// Now we need to make the query to get the next match.
PrepareKeyConditionClauses(directionClause, queryStart);
return ProcessStatementSteps(&*stmt);
}
nsresult OpenOpHelper<IDBCursorType::Index>::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(GetCursor().mObjectStoreId);
MOZ_ASSERT(GetCursor().mIndexId);
AUTO_PROFILER_LABEL("Cursor::OpenOp::DoIndexDatabaseWork", DOM);
const bool usingKeyRange = GetOptionalKeyRange().isSome();
const auto indexTable =
GetCursor().mUniqueIndex ? "unique_index_data"_ns : "index_data"_ns;
// The result of MakeColumnPairSelectionList is stored in a local variable,
// since inlining it into the next statement causes a crash on some Mac OS X
// builds (see https://bugzilla.mozilla.org/show_bug.cgi?id=1168606#c110).
const auto columnPairSelectionList = MakeColumnPairSelectionList(
"index_table.value"_ns, "index_table.value_locale"_ns,
kColumnNameAliasSortKey, GetCursor().IsLocaleAware());
const nsCString sortColumnAlias =
"SELECT "_ns + columnPairSelectionList + ", "_ns;
const nsAutoCString queryStart = sortColumnAlias +
"index_table.object_data_key, "
"object_data.file_ids, "
"object_data.data "
"FROM "_ns +
indexTable +
" AS index_table "
"JOIN object_data "
"ON index_table.object_store_id = "
"object_data.object_store_id "
"AND index_table.object_data_key = "
"object_data.key "
"WHERE index_table.index_id = :"_ns +
kStmtParamNameId;
const auto keyRangeClause =
DatabaseOperationBase::MaybeGetBindingClauseForKeyRange(
GetOptionalKeyRange(), kColumnNameAliasSortKey);
nsAutoCString directionClause = " ORDER BY "_ns + kColumnNameAliasSortKey;
switch (GetCursor().mDirection) {
case IDBCursorDirection::Next:
case IDBCursorDirection::Nextunique:
directionClause.AppendLiteral(" ASC, index_table.object_data_key ASC");
break;
case IDBCursorDirection::Prev:
directionClause.AppendLiteral(" DESC, index_table.object_data_key DESC");
break;
case IDBCursorDirection::Prevunique:
directionClause.AppendLiteral(" DESC, index_table.object_data_key ASC");
break;
default:
MOZ_CRASH("Should never get here!");
}
// Note: Changing the number or order of SELECT columns in the query will
// require changes to CursorOpBase::PopulateResponseFromStatement.
const nsCString firstQuery = queryStart + keyRangeClause + directionClause +
kOpenLimit +
IntToCString(1 + GetCursor().mMaxExtraCount);
QM_TRY_INSPECT(const auto& stmt,
aConnection->BorrowCachedStatement(firstQuery));
QM_TRY(MOZ_TO_RESULT(
stmt->BindInt64ByName(kStmtParamNameId, GetCursor().mIndexId)));
if (usingKeyRange) {
if (GetCursor().IsLocaleAware()) {
QM_TRY(MOZ_TO_RESULT(DatabaseOperationBase::BindKeyRangeToStatement(
GetOptionalKeyRange().ref(), &*stmt, GetCursor().mLocale)));
} else {
QM_TRY(MOZ_TO_RESULT(DatabaseOperationBase::BindKeyRangeToStatement(
GetOptionalKeyRange().ref(), &*stmt)));
}
}
// TODO: At least the last two statements are almost the same in all
// DoDatabaseWork variants, consider removing this duplication.
// Now we need to make the query to get the next match.
PrepareKeyConditionClauses(directionClause, std::move(queryStart));
return ProcessStatementSteps(&*stmt);
}
nsresult OpenOpHelper<IDBCursorType::IndexKey>::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(GetCursor().mObjectStoreId);
MOZ_ASSERT(GetCursor().mIndexId);
AUTO_PROFILER_LABEL("Cursor::OpenOp::DoIndexKeyDatabaseWork", DOM);
const bool usingKeyRange = GetOptionalKeyRange().isSome();
const auto table =
GetCursor().mUniqueIndex ? "unique_index_data"_ns : "index_data"_ns;
// The result of MakeColumnPairSelectionList is stored in a local variable,
// since inlining it into the next statement causes a crash on some Mac OS X
// builds (see https://bugzilla.mozilla.org/show_bug.cgi?id=1168606#c110).
const auto columnPairSelectionList = MakeColumnPairSelectionList(
"value"_ns, "value_locale"_ns, kColumnNameAliasSortKey,
GetCursor().IsLocaleAware());
const nsCString sortColumnAlias =
"SELECT "_ns + columnPairSelectionList + ", "_ns;
const nsAutoCString queryStart = sortColumnAlias +
"object_data_key "
" FROM "_ns +
table + " WHERE index_id = :"_ns +
kStmtParamNameId;
const auto keyRangeClause =
DatabaseOperationBase::MaybeGetBindingClauseForKeyRange(
GetOptionalKeyRange(), kColumnNameAliasSortKey);
nsAutoCString directionClause = " ORDER BY "_ns + kColumnNameAliasSortKey;
switch (GetCursor().mDirection) {
case IDBCursorDirection::Next:
case IDBCursorDirection::Nextunique:
directionClause.AppendLiteral(" ASC, object_data_key ASC");
break;
case IDBCursorDirection::Prev:
directionClause.AppendLiteral(" DESC, object_data_key DESC");
break;
case IDBCursorDirection::Prevunique:
directionClause.AppendLiteral(" DESC, object_data_key ASC");
break;
default:
MOZ_CRASH("Should never get here!");
}
// Note: Changing the number or order of SELECT columns in the query will
// require changes to CursorOpBase::PopulateResponseFromStatement.
const nsCString firstQuery =
queryStart + keyRangeClause + directionClause + kOpenLimit + "1"_ns;
QM_TRY_INSPECT(const auto& stmt,
aConnection->BorrowCachedStatement(firstQuery));
QM_TRY(MOZ_TO_RESULT(
stmt->BindInt64ByName(kStmtParamNameId, GetCursor().mIndexId)));
if (usingKeyRange) {
if (GetCursor().IsLocaleAware()) {
QM_TRY(MOZ_TO_RESULT(DatabaseOperationBase::BindKeyRangeToStatement(
GetOptionalKeyRange().ref(), &*stmt, GetCursor().mLocale)));
} else {
QM_TRY(MOZ_TO_RESULT(DatabaseOperationBase::BindKeyRangeToStatement(
GetOptionalKeyRange().ref(), &*stmt)));
}
}
// Now we need to make the query to get the next match.
PrepareKeyConditionClauses(directionClause, std::move(queryStart));
return ProcessStatementSteps(&*stmt);
}
template <IDBCursorType CursorType>
nsresult Cursor<CursorType>::OpenOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mCursor);
MOZ_ASSERT(!mCursor->mContinueQueries);
AUTO_PROFILER_LABEL("Cursor::OpenOp::DoDatabaseWork", DOM);
auto helper = OpenOpHelper<CursorType>{*this};
const auto rv = helper.DoDatabaseWork(aConnection);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
template <IDBCursorType CursorType>
nsresult Cursor<CursorType>::CursorOpBase::SendSuccessResult() {
AssertIsOnOwningThread();
MOZ_ASSERT(mCursor);
MOZ_ASSERT(mCursor->mCurrentlyRunningOp == this);
MOZ_ASSERT(mResponse.type() != CursorResponse::T__None);
if (IsActorDestroyed()) {
return NS_ERROR_DOM_INDEXEDDB_ABORT_ERR;
}
mCursor->SendResponseInternal(mResponse, mFiles);
#ifdef DEBUG
mResponseSent = true;
#endif
return NS_OK;
}
template <IDBCursorType CursorType>
nsresult Cursor<CursorType>::ContinueOp::DoDatabaseWork(
DatabaseConnection* aConnection) {
MOZ_ASSERT(aConnection);
aConnection->AssertIsOnConnectionThread();
MOZ_ASSERT(mCursor);
MOZ_ASSERT(mCursor->mObjectStoreId);
MOZ_ASSERT(!mCursor->mContinueQueries->mContinueQuery.IsEmpty());
MOZ_ASSERT(!mCursor->mContinueQueries->mContinueToQuery.IsEmpty());
MOZ_ASSERT(!mCurrentPosition.mKey.IsUnset());
if constexpr (IsIndexCursor) {
MOZ_ASSERT_IF(
mCursor->mDirection == IDBCursorDirection::Next ||
mCursor->mDirection == IDBCursorDirection::Prev,
!mCursor->mContinueQueries->mContinuePrimaryKeyQuery.IsEmpty());
MOZ_ASSERT(mCursor->mIndexId);
MOZ_ASSERT(!mCurrentPosition.mObjectStoreKey.IsUnset());
}
AUTO_PROFILER_LABEL("Cursor::ContinueOp::DoDatabaseWork", DOM);
// We need to pick a query based on whether or not a key was passed to the
// continue function. If not we'll grab the next item in the database that
// is greater than (or less than, if we're running a PREV cursor) the current
// key. If a key was passed we'll grab the next item in the database that is
// greater than (or less than, if we're running a PREV cursor) or equal to the
// key that was specified.
//
// TODO: The description above is not complete, it does not take account of
// ContinuePrimaryKey nor Advance.
//
// Note: Changing the number or order of SELECT columns in the query will
// require changes to CursorOpBase::PopulateResponseFromStatement.
const uint32_t advanceCount =
mParams.type() == CursorRequestParams::TAdvanceParams
? mParams.get_AdvanceParams().count()
: 1;
MOZ_ASSERT(advanceCount > 0);
bool hasContinueKey = false;
bool hasContinuePrimaryKey = false;
auto explicitContinueKey = Key{};
switch (mParams.type()) {
case CursorRequestParams::TContinueParams:
if (!mParams.get_ContinueParams().key().IsUnset()) {
hasContinueKey = true;
explicitContinueKey = mParams.get_ContinueParams().key();
}
break;
case CursorRequestParams::TContinuePrimaryKeyParams:
MOZ_ASSERT(!mParams.get_ContinuePrimaryKeyParams().key().IsUnset());
MOZ_ASSERT(
!mParams.get_ContinuePrimaryKeyParams().primaryKey().IsUnset());
MOZ_ASSERT(mCursor->mDirection == IDBCursorDirection::Next ||
mCursor->mDirection == IDBCursorDirection::Prev);
hasContinueKey = true;
hasContinuePrimaryKey = true;
explicitContinueKey = mParams.get_ContinuePrimaryKeyParams().key();
break;
case CursorRequestParams::TAdvanceParams:
break;
default:
MOZ_CRASH("Should never get here!");
}
// TODO: Whether it makes sense to preload depends on the kind of the
// subsequent operations, not of the current operation. We could assume that
// the subsequent operations are:
// - the same as the current operation (with the same parameter values)
// - as above, except for Advance, where we assume the count will be 1 on the
// next call
// - basic operations (Advance with count 1 or Continue-without-key)
//
// For now, we implement the second option for now (which correspond to
// !hasContinueKey).
//
// Based on that, we could in both cases either preload for any assumed
// subsequent operations, or only for the basic operations. For now, we
// preload only for an assumed basic operation. Other operations would require
// more work on the client side for invalidation, and may not make any sense
// at all.
const uint32_t maxExtraCount = hasContinueKey ? 0 : mCursor->mMaxExtraCount;
QM_TRY_INSPECT(const auto& stmt,
aConnection->BorrowCachedStatement(
mCursor->mContinueQueries->GetContinueQuery(
hasContinueKey, hasContinuePrimaryKey)));
QM_TRY(MOZ_TO_RESULT(stmt->BindUTF8StringByName(
kStmtParamNameLimit,
IntToCString(advanceCount + mCursor->mMaxExtraCount))));
QM_TRY(MOZ_TO_RESULT(stmt->BindInt64ByName(kStmtParamNameId, mCursor->Id())));
// Bind current key.
const auto& continueKey =
hasContinueKey ? explicitContinueKey
: mCurrentPosition.GetSortKey(mCursor->IsLocaleAware());
QM_TRY(MOZ_TO_RESULT(
continueKey.BindToStatement(&*stmt, kStmtParamNameCurrentKey)));
// Bind range bound if it is specified.
if (!mCursor->mLocaleAwareRangeBound->IsUnset()) {
QM_TRY(MOZ_TO_RESULT(mCursor->mLocaleAwareRangeBound->BindToStatement(
&*stmt, kStmtParamNameRangeBound)));
}
// Bind object store position if duplicates are allowed and we're not
// continuing to a specific key.
if constexpr (IsIndexCursor) {
if (!hasContinueKey && (mCursor->mDirection == IDBCursorDirection::Next ||
mCursor->mDirection == IDBCursorDirection::Prev)) {
QM_TRY(MOZ_TO_RESULT(mCurrentPosition.mObjectStoreKey.BindToStatement(
&*stmt, kStmtParamNameObjectStorePosition)));
} else if (hasContinuePrimaryKey) {
QM_TRY(MOZ_TO_RESULT(
mParams.get_ContinuePrimaryKeyParams().primaryKey().BindToStatement(
&*stmt, kStmtParamNameObjectStorePosition)));
}
}
// TODO: Why do we query the records we don't need and skip them here, rather
// than using a OFFSET clause in the query?
for (uint32_t index = 0; index < advanceCount; index++) {
QM_TRY_INSPECT(const bool& hasResult,
MOZ_TO_RESULT_INVOKE_MEMBER(&*stmt, ExecuteStep));
if (!hasResult) {
mResponse = void_t();
return NS_OK;
}
}
Key previousKey;
auto* const optPreviousKey =
IsUnique(mCursor->mDirection) ? &previousKey : nullptr;
auto helper = CursorOpBaseHelperBase<CursorType>{*this};
QM_TRY_INSPECT(const auto& responseSize, helper.PopulateResponseFromStatement(
&*stmt, true, optPreviousKey));
helper.PopulateExtraResponses(&*stmt, maxExtraCount, responseSize,
"ContinueOp"_ns, optPreviousKey);
return NS_OK;
}
Utils::Utils()
#ifdef DEBUG
: mActorDestroyed(false)
#endif
{
AssertIsOnBackgroundThread();
}
Utils::~Utils() { MOZ_ASSERT(mActorDestroyed); }
void Utils::ActorDestroy(ActorDestroyReason aWhy) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mActorDestroyed);
#ifdef DEBUG
mActorDestroyed = true;
#endif
}
mozilla::ipc::IPCResult Utils::RecvDeleteMe() {
AssertIsOnBackgroundThread();
MOZ_ASSERT(!mActorDestroyed);
QM_WARNONLY_TRY(OkIf(PBackgroundIndexedDBUtilsParent::Send__delete__(this)));
return IPC_OK();
}
mozilla::ipc::IPCResult Utils::RecvGetFileReferences(
const PersistenceType& aPersistenceType, const nsACString& aOrigin,
const nsAString& aDatabaseName, const int64_t& aFileId, int32_t* aRefCnt,
int32_t* aDBRefCnt, bool* aResult) {
AssertIsOnBackgroundThread();
MOZ_ASSERT(aRefCnt);
MOZ_ASSERT(aDBRefCnt);
MOZ_ASSERT(aResult);
MOZ_ASSERT(!mActorDestroyed);
if (NS_WARN_IF(!IndexedDatabaseManager::Get())) {
return IPC_FAIL(this, "No IndexedDatabaseManager active!");
}
if (NS_WARN_IF(!QuotaManager::Get())) {
return IPC_FAIL(this, "No QuotaManager active!");
}
if (NS_WARN_IF(!StaticPrefs::dom_indexedDB_testing())) {
return IPC_FAIL(this, "IndexedDB is not in testing mode!");
}
if (NS_WARN_IF(!IsValidPersistenceType(aPersistenceType))) {
return IPC_FAIL(this, "PersistenceType is not valid!");
}
if (NS_WARN_IF(aOrigin.IsEmpty())) {
return IPC_FAIL(this, "Origin is empty!");
}
if (NS_WARN_IF(aDatabaseName.IsEmpty())) {
return IPC_FAIL(this, "DatabaseName is empty!");
}
if (NS_WARN_IF(aFileId == 0)) {
return IPC_FAIL(this, "No FileId!");
}
nsresult rv =
DispatchAndReturnFileReferences(aPersistenceType, aOrigin, aDatabaseName,
aFileId, aRefCnt, aDBRefCnt, aResult);
if (NS_WARN_IF(NS_FAILED(rv))) {
return IPC_FAIL(this, "DispatchAndReturnFileReferences failed!");
}
return IPC_OK();
}
mozilla::ipc::IPCResult Utils::RecvDoMaintenance(
DoMaintenanceResolver&& aResolver) {
AssertIsOnBackgroundThread();
QM_TRY(MOZ_TO_RESULT(!QuotaManager::IsShuttingDown()),
ResolveNSResultAndReturn(aResolver));
QM_TRY(QuotaManager::EnsureCreated(), ResolveNSResultAndReturn(aResolver));
QuotaClient* quotaClient = QuotaClient::GetInstance();
QM_TRY(MOZ_TO_RESULT(quotaClient), QM_IPC_FAIL(this));
quotaClient->DoMaintenance()->Then(
GetCurrentSerialEventTarget(), __func__,
[self = RefPtr(this), resolver = std::move(aResolver)](
const BoolPromise::ResolveOrRejectValue& aValue) {
if (!self->CanSend()) {
return;
}
if (aValue.IsResolve()) {
resolver(NS_OK);
} else {
resolver(aValue.RejectValue());
}
});
return IPC_OK();
}
#ifdef DEBUG
NS_IMPL_ISUPPORTS(DEBUGThreadSlower, nsIThreadObserver)
NS_IMETHODIMP
DEBUGThreadSlower::OnDispatchedEvent() { MOZ_CRASH("Should never be called!"); }
NS_IMETHODIMP
DEBUGThreadSlower::OnProcessNextEvent(nsIThreadInternal* /* aThread */,
bool /* aMayWait */) {
return NS_OK;
}
NS_IMETHODIMP
DEBUGThreadSlower::AfterProcessNextEvent(nsIThreadInternal* /* aThread */,
bool /* aEventWasProcessed */) {
MOZ_ASSERT(kDEBUGThreadSleepMS);
MOZ_ALWAYS_TRUE(PR_Sleep(PR_MillisecondsToInterval(kDEBUGThreadSleepMS)) ==
PR_SUCCESS);
return NS_OK;
}
#endif // DEBUG
nsresult FileHelper::Init() {
MOZ_ASSERT(!IsOnBackgroundThread());
auto fileDirectory = mFileManager->GetCheckedDirectory();
if (NS_WARN_IF(!fileDirectory)) {
return NS_ERROR_FAILURE;
}
auto journalDirectory = mFileManager->EnsureJournalDirectory();
if (NS_WARN_IF(!journalDirectory)) {
return NS_ERROR_FAILURE;
}
DebugOnly<bool> exists;
MOZ_ASSERT(NS_SUCCEEDED(journalDirectory->Exists(&exists)));
MOZ_ASSERT(exists);
DebugOnly<bool> isDirectory;
MOZ_ASSERT(NS_SUCCEEDED(journalDirectory->IsDirectory(&isDirectory)));
MOZ_ASSERT(isDirectory);
mFileDirectory.init(WrapNotNullUnchecked(std::move(fileDirectory)));
mJournalDirectory.init(WrapNotNullUnchecked(std::move(journalDirectory)));
return NS_OK;
}
nsCOMPtr<nsIFile> FileHelper::GetFile(const DatabaseFileInfo& aFileInfo) {
MOZ_ASSERT(!IsOnBackgroundThread());
return mFileManager->GetFileForId(mFileDirectory->get(), aFileInfo.Id());
}
nsCOMPtr<nsIFile> FileHelper::GetJournalFile(
const DatabaseFileInfo& aFileInfo) {
MOZ_ASSERT(!IsOnBackgroundThread());
return mFileManager->GetFileForId(mJournalDirectory->get(), aFileInfo.Id());
}
nsresult FileHelper::CreateFileFromStream(nsIFile& aFile, nsIFile& aJournalFile,
nsIInputStream& aInputStream,
bool aCompress,
const Maybe<CipherKey>& aMaybeKey) {
MOZ_ASSERT(!IsOnBackgroundThread());
QM_TRY_INSPECT(const auto& exists,
MOZ_TO_RESULT_INVOKE_MEMBER(aFile, Exists));
// DOM blobs that are being stored in IDB are cached by calling
// IDBDatabase::GetOrCreateFileActorForBlob. So if the same DOM blob is stored
// again under a different key or in a different object store, we just add
// a new reference instead of creating a new copy (all such stored blobs share
// the same id).
// However, it can happen that CreateFileFromStream failed due to quota
// exceeded error and for some reason the orphaned file couldn't be deleted
// immediately. Now, if the operation is being repeated, the DOM blob is
// already cached, so it has the same file id which clashes with the orphaned
// file. We could do some tricks to restore previous copy loop, but it's safer
// to just delete the orphaned file and start from scratch.
// This corner case is partially simulated in test_file_copy_failure.js
if (exists) {
QM_TRY_INSPECT(const auto& isFile,
MOZ_TO_RESULT_INVOKE_MEMBER(aFile, IsFile));
QM_TRY(OkIf(isFile), NS_ERROR_FAILURE);
QM_TRY_INSPECT(const auto& journalExists,
MOZ_TO_RESULT_INVOKE_MEMBER(aJournalFile, Exists));
QM_TRY(OkIf(journalExists), NS_ERROR_FAILURE);
QM_TRY_INSPECT(const auto& journalIsFile,
MOZ_TO_RESULT_INVOKE_MEMBER(aJournalFile, IsFile));
QM_TRY(OkIf(journalIsFile), NS_ERROR_FAILURE);
IDB_WARNING("Deleting orphaned file!");
QM_TRY(MOZ_TO_RESULT(mFileManager->SyncDeleteFile(aFile, aJournalFile)));
}
// Create a journal file first.
QM_TRY(MOZ_TO_RESULT(aJournalFile.Create(nsIFile::NORMAL_FILE_TYPE, 0644)));
// Now try to copy the stream.
QM_TRY_UNWRAP(nsCOMPtr<nsIOutputStream> fileOutputStream,
CreateFileOutputStream(mFileManager->Type(),
mFileManager->OriginMetadata(),
Client::IDB, &aFile));
AutoTArray<char, kFileCopyBufferSize> buffer;
const auto actualOutputStream =
[aCompress, &aMaybeKey, &buffer,
baseOutputStream =
std::move(fileOutputStream)]() mutable -> nsCOMPtr<nsIOutputStream> {
if (aMaybeKey) {
baseOutputStream =
MakeRefPtr<EncryptingOutputStream<IndexedDBCipherStrategy>>(
std::move(baseOutputStream), kEncryptedStreamBlockSize,
*aMaybeKey);
}
if (aCompress) {
auto snappyOutputStream =
MakeRefPtr<SnappyCompressOutputStream>(baseOutputStream);
buffer.SetLength(snappyOutputStream->BlockSize());
return snappyOutputStream;
}
buffer.SetLength(kFileCopyBufferSize);
return std::move(baseOutputStream);
}();
QM_TRY(MOZ_TO_RESULT(SyncCopy(aInputStream, *actualOutputStream,
buffer.Elements(), buffer.Length())));
return NS_OK;
}
class FileHelper::ReadCallback final : public nsIInputStreamCallback {
public:
NS_DECL_THREADSAFE_ISUPPORTS
ReadCallback()
: mMutex("ReadCallback::mMutex"),
mCondVar(mMutex, "ReadCallback::mCondVar"),
mInputAvailable(false) {}
NS_IMETHOD
OnInputStreamReady(nsIAsyncInputStream* aStream) override {
mozilla::MutexAutoLock autolock(mMutex);
mInputAvailable = true;
mCondVar.Notify();
return NS_OK;
}
nsresult AsyncWait(nsIAsyncInputStream* aStream, uint32_t aBufferSize,
nsIEventTarget* aTarget) {
MOZ_ASSERT(aStream);
mozilla::MutexAutoLock autolock(mMutex);
nsresult rv = aStream->AsyncWait(this, 0, aBufferSize, aTarget);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mInputAvailable = false;
while (!mInputAvailable) {
mCondVar.Wait();
}
return NS_OK;
}
private:
~ReadCallback() = default;
mozilla::Mutex mMutex MOZ_UNANNOTATED;
mozilla::CondVar mCondVar;
bool mInputAvailable;
};
NS_IMPL_ADDREF(FileHelper::ReadCallback);
NS_IMPL_RELEASE(FileHelper::ReadCallback);
NS_INTERFACE_MAP_BEGIN(FileHelper::ReadCallback)
NS_INTERFACE_MAP_ENTRY(nsIInputStreamCallback)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIInputStreamCallback)
NS_INTERFACE_MAP_END
nsresult FileHelper::SyncRead(nsIInputStream& aInputStream, char* const aBuffer,
const uint32_t aBufferSize,
uint32_t* const aRead) {
MOZ_ASSERT(!IsOnBackgroundThread());
// Let's try to read, directly.
nsresult rv = aInputStream.Read(aBuffer, aBufferSize, aRead);
if (NS_SUCCEEDED(rv) || rv != NS_BASE_STREAM_WOULD_BLOCK) {
return rv;
}
// We need to proceed async.
nsCOMPtr<nsIAsyncInputStream> asyncStream = do_QueryInterface(&aInputStream);
if (!asyncStream) {
return rv;
}
if (!mReadCallback) {
mReadCallback.init(MakeNotNull<RefPtr<ReadCallback>>());
}
// We just need any thread with an event loop for receiving the
// OnInputStreamReady callback. Let's use the I/O thread.
nsCOMPtr<nsIEventTarget> target =
do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
MOZ_ASSERT(target);
rv = (*mReadCallback)->AsyncWait(asyncStream, aBufferSize, target);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return SyncRead(aInputStream, aBuffer, aBufferSize, aRead);
}
nsresult FileHelper::SyncCopy(nsIInputStream& aInputStream,
nsIOutputStream& aOutputStream,
char* const aBuffer, const uint32_t aBufferSize) {
MOZ_ASSERT(!IsOnBackgroundThread());
AUTO_PROFILER_LABEL("FileHelper::SyncCopy", DOM);
nsresult rv;
do {
uint32_t numRead;
rv = SyncRead(aInputStream, aBuffer, aBufferSize, &numRead);
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
if (!numRead) {
break;
}
uint32_t numWrite;
rv = aOutputStream.Write(aBuffer, numRead, &numWrite);
if (rv == NS_ERROR_FILE_NO_DEVICE_SPACE) {
rv = NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR;
}
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
if (NS_WARN_IF(numWrite != numRead)) {
rv = NS_ERROR_FAILURE;
break;
}
} while (true);
if (NS_SUCCEEDED(rv)) {
rv = aOutputStream.Flush();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
nsresult rv2 = aOutputStream.Close();
if (NS_WARN_IF(NS_FAILED(rv2))) {
return NS_SUCCEEDED(rv) ? rv2 : rv;
}
return rv;
}
} // namespace dom::indexedDB
} // namespace mozilla
#undef IDB_MOBILE
#undef IDB_DEBUG_LOG
|