DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Line Code
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
/* 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/. */

"use strict";

/**
 * This file implements a mirror and two-way merger for synced bookmarks. The
 * mirror matches the complete tree stored on the Sync server, and stages new
 * bookmarks changed on the server since the last sync. The merger walks the
 * local tree in Places and the mirrored remote tree, produces a new merged
 * tree, then updates the local tree to reflect the merged tree.
 *
 * Let's start with an overview of the different classes, and how they fit
 * together.
 *
 * - `SyncedBookmarksMirror` sets up the database, validates and upserts new
 *   incoming records, attaches to Places, and applies the changed records.
 *   During application, we fetch the local and remote bookmark trees, merge
 *   them, and update Places to match. Merging and application happen in a
 *   single transaction, so applying the merged tree won't collide with local
 *   changes. A failure at this point aborts the merge and leaves Places
 *   unchanged.
 *
 * - A `BookmarkTree` is a fully rooted tree that also notes deletions. A
 *   `BookmarkNode` represents a local item in Places, or a remote item in the
 *   mirror.
 *
 * - A `MergedBookmarkNode` holds a local node, a remote node, and a
 *   `MergeState` that indicates which node to prefer when updating Places and
 *   the server to match the merged tree.
 *
 * - `BookmarkObserverRecorder` records all changes made to Places during the
 *   merge, then dispatches `nsINavBookmarkObserver` notifications. Places uses
 *   these notifications to update the UI and internal caches. We can't dispatch
 *   during the merge because observers won't see the changes until the merge
 *   transaction commits and the database is consistent again.
 *
 * - After application, we flag all applied incoming items as merged, create
 *   Sync records for the locally new and updated items in Places, and upload
 *   the records to the server. At this point, all outgoing items are flagged as
 *   changed in Places, so the next sync can resume cleanly if the upload is
 *   interrupted or fails.
 *
 * - Once upload succeeds, we update the mirror with the uploaded records, so
 *   that the mirror matches the server again. An interruption or error here
 *   will leave the uploaded items flagged as changed in Places, so we'll merge
 *   them again on the next sync. This is redundant work, but shouldn't cause
 *   issues.
 */

var EXPORTED_SYMBOLS = ["SyncedBookmarksMirror"];

Cu.importGlobalProperties(["URL"]);

ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetters(this, {
  Async: "resource://services-common/async.js",
  AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
  Log: "resource://gre/modules/Log.jsm",
  OS: "resource://gre/modules/osfile.jsm",
  PlacesSyncUtils: "resource://gre/modules/PlacesSyncUtils.jsm",
  PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
  Sqlite: "resource://gre/modules/Sqlite.jsm",
});

XPCOMUtils.defineLazyGetter(this, "MirrorLog", () =>
  Log.repository.getLogger("Sync.Engine.Bookmarks.Mirror")
);

XPCOMUtils.defineLazyGetter(this, "UserContentRootsAsSqlList", () =>
  PlacesUtils.bookmarks.userContentRoots.map(v => `'${v}'`).join(",")
);

// These can be removed once they're exposed in a central location (bug
// 1375896).
const DB_URL_LENGTH_MAX = 65536;
const DB_TITLE_LENGTH_MAX = 4096;
const DB_DESCRIPTION_LENGTH_MAX = 256;

const SQLITE_MAX_VARIABLE_NUMBER = 999;

// The current mirror database schema version. Bump for migrations, then add
// migration code to `migrateMirrorSchema`.
const MIRROR_SCHEMA_VERSION = 1;

// Use a shared jankYielder in these functions
XPCOMUtils.defineLazyGetter(this, "maybeYield", () => Async.jankYielder());
function yieldingIterator(collection) {
  return Async.yieldingIterator(collection, maybeYield);
}

/**
 * A mirror maintains a copy of the complete tree as stored on the Sync server.
 * It is persistent.
 *
 * The mirror schema is a hybrid of how Sync and Places represent bookmarks.
 * The `items` table contains item attributes (title, kind, description,
 * URL, etc.), while the `structure` table stores parent-child relationships and
 * position. This is similar to how iOS encodes "value" and "structure" state,
 * though we handle these differently when merging. See `BookmarkMerger` for
 * details.
 *
 * There's no guarantee that the remote state is consistent. We might be missing
 * parents or children, or a bookmark and its parent might disagree about where
 * it belongs. This means we need a strategy to handle missing parents and
 * children.
 *
 * We treat the `children` of the last parent we see as canonical, and ignore
 * the child's `parentid` entirely. We also ignore missing children, and
 * temporarily reparent bookmarks with missing parents to "unfiled". When we
 * eventually see the missing items, either during a later sync or as part of
 * repair, we'll fill in the mirror's gaps and fix up the local tree.
 *
 * During merging, we won't intentionally try to fix inconsistencies on the
 * server, and opt to build as complete a tree as we can from the remote state,
 * even if we diverge from what's in the mirror. See bug 1433512 for context.
 *
 * If a sync is interrupted, we resume downloading from the server collection
 * last modified time, or the server last modified time of the most recent
 * record if newer. New incoming records always replace existing records in the
 * mirror.
 *
 * We delete the mirror database on client reset, including when the sync ID
 * changes on the server, and when the user is node reassigned, disables the
 * bookmarks engine, or signs out.
 */
class SyncedBookmarksMirror {
  constructor(db, { recordTelemetryEvent, finalizeAt =
                      AsyncShutdown.profileBeforeChange } = {}) {
    this.db = db;
    this.recordTelemetryEvent = recordTelemetryEvent;

    // Automatically close the database connection on shutdown.
    this.finalizeAt = finalizeAt;
    this.finalizeBound = () => this.finalize();
    this.finalizeAt.addBlocker("SyncedBookmarksMirror: finalize",
                               this.finalizeBound);
  }

  /**
   * Sets up the mirror database connection and upgrades the mirror to the
   * newest schema version. Automatically recreates the mirror if it's corrupt;
   * throws on failure.
   *
   * @param  {String} options.path
   *         The full path to the mirror database file.
   * @param  {Function} options.recordTelemetryEvent
   *         A function with the signature `(object: String, method: String,
   *         value: String?, extra: Object?)`, used to emit telemetry events.
   * @param  {AsyncShutdown.Barrier} [options.finalizeAt]
   *         A shutdown phase, barrier, or barrier client that should
   *         automatically finalize the mirror when triggered. Exposed for
   *         testing.
   * @return {SyncedBookmarksMirror}
   *         A mirror ready for use.
   */
  static async open(options) {
    let db = await Sqlite.cloneStorageConnection({
      connection: PlacesUtils.history.DBConnection,
      readOnly: false,
    });
    try {
      try {
        await db.execute(`ATTACH :mirrorPath AS mirror`,
                         { mirrorPath: options.path });
      } catch (ex) {
        if (ex.errors && isDatabaseCorrupt(ex.errors[0])) {
          MirrorLog.warn("Error attaching mirror to Places; removing and " +
                         "recreating mirror", ex);
          options.recordTelemetryEvent("mirror", "open", "error",
                                       { why: "corrupt" });
          await OS.File.remove(options.path);
          await db.execute(`ATTACH :mirrorPath AS mirror`,
                           { mirrorPath: options.path });
        } else {
          MirrorLog.warn("Unrecoverable error attaching mirror to Places", ex);
          throw ex;
        }
      }
      await db.execute(`PRAGMA foreign_keys = ON`);
      await db.executeTransaction(async function() {
        await migrateMirrorSchema(db);
        await initializeTempMirrorEntities(db);
      });
    } catch (ex) {
      options.recordTelemetryEvent("mirror", "open", "error",
                                   { why: "initialize" });
      await db.close();
      throw ex;
    }
    return new SyncedBookmarksMirror(db, options);
  }

  /**
   * Returns the newer of the bookmarks collection last modified time, or the
   * server modified time of the newest record. The bookmarks engine uses this
   * timestamp as the "high water mark" for all downloaded records. Each sync
   * downloads and stores records that are strictly newer than this time.
   *
   * @return {Number}
   *         The high water mark time, in seconds.
   */
  async getCollectionHighWaterMark() {
    // The first case, where we have records with server modified times newer
    // than the collection last modified time, occurs when a sync is interrupted
    // before we call `setCollectionLastModified`. We subtract one second, the
    // maximum time precision guaranteed by the server, so that we don't miss
    // other records with the same time as the newest one we downloaded.
    let rows = await this.db.executeCached(`
      SELECT MAX(
        IFNULL((SELECT MAX(serverModified) - 1000 FROM items), 0),
        IFNULL((SELECT CAST(value AS INTEGER) FROM meta
                WHERE key = :modifiedKey), 0)
      ) AS highWaterMark`,
      { modifiedKey: SyncedBookmarksMirror.META_KEY.LAST_MODIFIED });
    let highWaterMark = rows[0].getResultByName("highWaterMark");
    return highWaterMark / 1000;
  }

  /**
   * Updates the bookmarks collection last modified time. Note that this may
   * be newer than the modified time of the most recent record.
   *
   * @param {Number|String} lastModifiedSeconds
   *        The collection last modified time, in seconds.
   */
  async setCollectionLastModified(lastModifiedSeconds) {
    let lastModified = Math.floor(lastModifiedSeconds * 1000);
    if (!Number.isInteger(lastModified)) {
      throw new TypeError("Invalid collection last modified time");
    }
    await this.db.executeBeforeShutdown(
      "SyncedBookmarksMirror: setCollectionLastModified",
      db => db.executeCached(`
        REPLACE INTO meta(key, value)
        VALUES(:modifiedKey, :lastModified)`,
        { modifiedKey: SyncedBookmarksMirror.META_KEY.LAST_MODIFIED,
          lastModified })
    );
  }

  /**
   * Returns the bookmarks collection sync ID. This corresponds to
   * `PlacesSyncUtils.bookmarks.getSyncId`.
   *
   * @return {String}
   *         The sync ID, or `""` if one isn't set.
   */
  async getSyncId() {
    let rows = await this.db.executeCached(`
      SELECT value FROM meta WHERE key = :syncIdKey`,
      { syncIdKey: SyncedBookmarksMirror.META_KEY.SYNC_ID });
    return rows.length ? rows[0].getResultByName("value") : "";
  }

  /**
   * Ensures that the sync ID in the mirror is up-to-date with the server and
   * Places, and discards the mirror on mismatch.
   *
   * The bookmarks engine store the same sync ID in Places and the mirror to
   * "tie" the two together. This allows Sync to do the right thing if the
   * database files are copied between profiles connected to different accounts.
   *
   * See `PlacesSyncUtils.bookmarks.ensureCurrentSyncId` for an explanation of
   * how Places handles sync ID mismatches.
   *
   * @param {String} newSyncId
   *        The server's sync ID.
   */
  async ensureCurrentSyncId(newSyncId) {
    if (!newSyncId || typeof newSyncId != "string") {
      throw new TypeError("Invalid new bookmarks sync ID");
    }
    let existingSyncId = await this.getSyncId();
    if (existingSyncId == newSyncId) {
      MirrorLog.trace("Sync ID up-to-date in mirror", { existingSyncId });
      return;
    }
    MirrorLog.info("Sync ID changed from ${existingSyncId} to " +
                   "${newSyncId}; resetting mirror",
                   { existingSyncId, newSyncId });
    await this.db.executeBeforeShutdown(
      "SyncedBookmarksMirror: ensureCurrentSyncId",
      db => db.executeTransaction(async function() {
        await resetMirror(db);
        await db.execute(`
          REPLACE INTO meta(key, value)
          VALUES(:syncIdKey, :newSyncId)`,
          { syncIdKey: SyncedBookmarksMirror.META_KEY.SYNC_ID, newSyncId });
      })
    );
  }

  /**
   * Stores incoming or uploaded Sync records in the mirror. Rejects if any
   * records are invalid.
   *
   * @param {PlacesItem[]} records
   *        Sync records to store in the mirror.
   * @param {Boolean} [options.needsMerge]
   *        Indicates if the records were changed remotely since the last sync,
   *        and should be merged into the local tree. This option is set to
   *       `true` for incoming records, and `false` for successfully uploaded
   *        records. Tests can also pass `false` to set up an existing mirror.
   */
  async store(records, { needsMerge = true } = {}) {
    let options = { needsMerge };
    await this.db.executeBeforeShutdown(
      "SyncedBookmarksMirror: store",
      db => db.executeTransaction(async () => {
        for await (let record of yieldingIterator(records)) {
          switch (record.type) {
            case "bookmark":
              MirrorLog.trace("Storing bookmark in mirror", record.cleartext);
              await this.storeRemoteBookmark(record, options);
              continue;

            case "query":
              MirrorLog.trace("Storing query in mirror", record.cleartext);
              await this.storeRemoteQuery(record, options);
              continue;

            case "folder":
              MirrorLog.trace("Storing folder in mirror", record.cleartext);
              await this.storeRemoteFolder(record, options);
              continue;

            case "livemark":
              MirrorLog.trace("Storing livemark in mirror", record.cleartext);
              await this.storeRemoteLivemark(record, options);
              continue;

            case "separator":
              MirrorLog.trace("Storing separator in mirror", record.cleartext);
              await this.storeRemoteSeparator(record, options);
              continue;

            default:
              if (record.deleted) {
                MirrorLog.trace("Storing tombstone in mirror",
                                record.cleartext);
                await this.storeRemoteTombstone(record, options);
                continue;
              }
          }
          MirrorLog.warn("Ignoring record with unknown type", record.type);
          this.recordTelemetryEvent("mirror", "ignore", "unknown",
                                    { why: "kind" });
        }
      })
    );
  }

  /**
   * Builds a complete merged tree from the local and remote trees, resolves
   * value and structure conflicts, dedupes local items, applies the merged
   * tree back to Places, and notifies observers about the changes.
   *
   * Merging and application happen in a transaction, meaning code that uses the
   * main Places connection, including the UI, will fail to write to the
   * database until the transaction commits. Asynchronous consumers will retry
   * on `SQLITE_BUSY`; synchronous consumers will fail after waiting for 100ms.
   * See bug 1305563, comment 122 for details.
   *
   * @param  {Number} [options.localTimeSeconds]
   *         The current local time, in seconds.
   * @param  {Number} [options.remoteTimeSeconds]
   *         The current server time, in seconds.
   * @param  {String[]} [options.weakUpload]
   *         GUIDs of bookmarks to weakly upload.
   * @return {Object.<String, BookmarkChangeRecord>}
   *         A changeset containing locally changed and reconciled records to
   *         upload to the server, and to store in the mirror once upload
   *         succeeds.
   */
  async apply({ localTimeSeconds = Date.now() / 1000,
                remoteTimeSeconds = 0,
                weakUpload = [] } = {}) {
    let hasChanges = weakUpload.length > 0 || (await this.hasChanges());
    if (!hasChanges) {
      MirrorLog.debug("No changes detected in both mirror and Places");
      return {};
    }
    // We intentionally don't use `executeBeforeShutdown` in this function,
    // since merging can take a while for large trees, and we don't want to
    // block shutdown. Since all new items are in the mirror, we'll just try
    // to merge again on the next sync.
    let { missingParents, missingChildren } = await this.fetchRemoteOrphans();
    if (missingParents.length) {
      MirrorLog.warn("Temporarily reparenting remote items with missing " +
                     "parents to unfiled", missingParents);
      this.recordTelemetryEvent("mirror", "orphans", "parents",
                                { count: String(missingParents.length) });
    }
    if (missingChildren.length) {
      MirrorLog.warn("Remote tree missing items", missingChildren);
      this.recordTelemetryEvent("mirror", "orphans", "children",
                                { count: String(missingChildren.length) });
    }

    let { missingLocal, missingRemote, wrongSyncStatus } =
      await this.fetchInconsistencies();
    if (missingLocal.length) {
      MirrorLog.warn("Remote tree has merged items that don't exist locally",
                     missingLocal);
      this.recordTelemetryEvent("mirror", "inconsistencies", "local",
                                { count: String(missingLocal.length) });
    }
    if (missingRemote.length) {
      MirrorLog.warn("Local tree has synced items that don't exist remotely",
                     missingRemote);
      this.recordTelemetryEvent("mirror", "inconsistencies", "remote",
                                { count: String(missingRemote.length) });
    }
    if (wrongSyncStatus.length) {
      MirrorLog.warn("Local tree has wrong sync statuses for items that " +
                     "exist remotely", wrongSyncStatus);
      this.recordTelemetryEvent("mirror", "inconsistencies", "syncStatus",
                                { count: String(wrongSyncStatus.length) });
    }

    // It's safe to build the remote tree outside the transaction because
    // `fetchRemoteTree` doesn't join to Places, only Sync writes to the
    // mirror, and we're holding the Sync lock at this point.
    MirrorLog.debug("Building remote tree from mirror");
    let remoteTree = await this.fetchRemoteTree(remoteTimeSeconds);
    if (MirrorLog.level <= Log.Level.Trace) {
      MirrorLog.trace("Built remote tree from mirror\n" +
                      remoteTree.toASCIITreeString());
    }

    let observersToNotify = new BookmarkObserverRecorder(this.db);

    let changeRecords = await this.db.executeTransaction(async () => {
      MirrorLog.debug("Building local tree from Places");
      let localTree = await this.fetchLocalTree(localTimeSeconds);
      if (MirrorLog.level <= Log.Level.Trace) {
        MirrorLog.trace("Built local tree from Places\n" +
                        localTree.toASCIITreeString());
      }

      MirrorLog.debug("Fetching content info for new mirror items");
      let newRemoteContents = await this.fetchNewRemoteContents();

      MirrorLog.debug("Fetching content info for new Places items");
      let newLocalContents = await this.fetchNewLocalContents();

      MirrorLog.debug("Building complete merged tree");
      let merger = new BookmarkMerger(localTree, newLocalContents,
                                      remoteTree, newRemoteContents);
      let mergedRoot;
      try {
        mergedRoot = await merger.merge();
      } finally {
        for (let { value, extra } of merger.telemetryEvents) {
          this.recordTelemetryEvent("mirror", "merge", value, extra);
        }
      }

      if (MirrorLog.level <= Log.Level.Trace) {
        MirrorLog.trace([
          "Built new merged tree",
          mergedRoot.toASCIITreeString(),
          ...merger.deletionsToStrings(),
        ].join("\n"));
      }

      // The merged tree should know about all items mentioned in the local
      // and remote trees. Otherwise, it's incomplete, and we'll corrupt
      // Places or lose data on the server if we try to apply it.
      if (!await merger.subsumes(localTree)) {
        throw new SyncedBookmarksMirror.ConsistencyError(
          "Merged tree doesn't mention all items from local tree");
      }
      if (!await merger.subsumes(remoteTree)) {
        throw new SyncedBookmarksMirror.ConsistencyError(
          "Merged tree doesn't mention all items from remote tree");
      }

      MirrorLog.debug("Applying merged tree");
      let localDeletions = Array.from(merger.deleteLocally).map(guid =>
        ({ guid, level: localTree.levelForGuid(guid) })
      );
      let remoteDeletions = Array.from(merger.deleteRemotely);
      await this.updateLocalItemsInPlaces(mergedRoot, localDeletions,
                                          remoteDeletions);

      // At this point, the database is consistent, and we can fetch info to
      // pass to observers. Note that we can't fetch observer info in the
      // triggers above, because the structure might not be complete yet. An
      // incomplete structure might cause us to miss or record wrong parents and
      // positions.

      MirrorLog.debug("Recording observer notifications");
      await this.noteObserverChanges(observersToNotify);

      MirrorLog.debug("Staging locally changed items for upload");
      await this.stageItemsToUpload(weakUpload);

      MirrorLog.debug("Fetching records for local items to upload");
      let changeRecords = await this.fetchLocalChangeRecords();

      await this.db.execute(`DELETE FROM mergeStates`);
      await this.db.execute(`DELETE FROM itemsAdded`);
      await this.db.execute(`DELETE FROM guidsChanged`);
      await this.db.execute(`DELETE FROM itemsChanged`);
      await this.db.execute(`DELETE FROM itemsRemoved`);
      await this.db.execute(`DELETE FROM itemsMoved`);
      await this.db.execute(`DELETE FROM annosChanged`);
      await this.db.execute(`DELETE FROM itemsToWeaklyReupload`);
      await this.db.execute(`DELETE FROM itemsToUpload`);

      return changeRecords;
    });

    MirrorLog.debug("Replaying recorded observer notifications");
    try {
      await observersToNotify.notifyAll();
    } catch (ex) {
      MirrorLog.error("Error notifying Places observers", ex);
    }

    return changeRecords;
  }

  /**
   * Discards the mirror contents. This is called when the user is node
   * reassigned, disables the bookmarks engine, or signs out.
   */
  async reset() {
    await this.db.executeBeforeShutdown(
      "SyncedBookmarksMirror: reset",
      db => db.executeTransaction(() => resetMirror(db))
    );
  }

  /**
   * Fetches the GUIDs of all items in the remote tree that need to be merged
   * into the local tree.
   *
   * @return {String[]}
   *         Remotely changed GUIDs that need to be merged into Places.
   */
  async fetchUnmergedGuids() {
    let rows = await this.db.execute(`SELECT guid FROM items WHERE needsMerge`);
    return rows.map(row => row.getResultByName("guid"));
  }

  async storeRemoteBookmark(record, { needsMerge }) {
    let guid = validateGuid(record.id);
    if (!guid) {
      MirrorLog.warn("Ignoring bookmark with invalid ID", record.id);
      this.recordTelemetryEvent("mirror", "ignore", "bookmark",
                                { why: "id" });
      return;
    }

    let url = validateURL(record.bmkUri);
    if (!url) {
      MirrorLog.warn("Ignoring bookmark ${guid} with invalid URL ${url}",
                     { guid, url: record.bmkUri });
      this.recordTelemetryEvent("mirror", "ignore", "bookmark",
                                { why: "url" });
      return;
    }

    await this.maybeStoreRemoteURL(url);

    let serverModified = determineServerModified(record);
    let dateAdded = determineDateAdded(record);
    let title = validateTitle(record.title);
    let keyword = validateKeyword(record.keyword);
    let description = validateDescription(record.description);
    let loadInSidebar = record.loadInSidebar === true ? "1" : null;

    await this.db.executeCached(`
      REPLACE INTO items(guid, serverModified, needsMerge, kind,
                         dateAdded, title, keyword,
                         urlId, description, loadInSidebar)
      VALUES(:guid, :serverModified, :needsMerge, :kind,
             :dateAdded, NULLIF(:title, ""), :keyword,
             (SELECT id FROM urls
              WHERE hash = hash(:url) AND
                    url = :url),
             :description, :loadInSidebar)`,
      { guid, serverModified, needsMerge,
        kind: SyncedBookmarksMirror.KIND.BOOKMARK, dateAdded, title, keyword,
        url: url.href, description, loadInSidebar });

    let tags = record.tags;
    if (tags && Array.isArray(tags)) {
      for (let rawTag of tags) {
        let tag = validateTag(rawTag);
        if (!tag) {
          continue;
        }
        await this.db.executeCached(`
          INSERT INTO tags(itemId, tag)
          SELECT id, :tag FROM items
          WHERE guid = :guid`,
          { tag, guid });
      }
    }
  }

  async storeRemoteQuery(record, { needsMerge }) {
    let guid = validateGuid(record.id);
    if (!guid) {
      MirrorLog.warn("Ignoring query with invalid ID", record.id);
      this.recordTelemetryEvent("mirror", "ignore", "query",
                                { why: "id" });
      return;
    }

    let url = validateURL(record.bmkUri);
    if (!url) {
      MirrorLog.warn("Ignoring query ${guid} with invalid URL ${url}",
                     { guid, url: record.bmkUri });
      this.recordTelemetryEvent("mirror", "ignore", "query",
                                { why: "url" });
      return;
    }

    await this.maybeStoreRemoteURL(url);

    let serverModified = determineServerModified(record);
    let dateAdded = determineDateAdded(record);
    let title = validateTitle(record.title);
    let tagFolderName = validateTag(record.folderName);
    let description = validateDescription(record.description);
    let smartBookmarkName = typeof record.queryId == "string" ?
                            record.queryId : null;

    await this.db.executeCached(`
      REPLACE INTO items(guid, serverModified, needsMerge, kind,
                         dateAdded, title, tagFolderName,
                         urlId, description, smartBookmarkName)
      VALUES(:guid, :serverModified, :needsMerge, :kind,
             :dateAdded, NULLIF(:title, ""), :tagFolderName,
             (SELECT id FROM urls
              WHERE hash = hash(:url) AND
                    url = :url),
             :description, :smartBookmarkName)`,
      { guid, serverModified, needsMerge,
        kind: SyncedBookmarksMirror.KIND.QUERY, dateAdded, title, tagFolderName,
        url: url.href, description, smartBookmarkName });
  }

  async storeRemoteFolder(record, { needsMerge }) {
    let guid = validateGuid(record.id);
    if (!guid) {
      MirrorLog.warn("Ignoring folder with invalid ID", record.id);
      this.recordTelemetryEvent("mirror", "ignore", "folder",
                                { why: "id" });
      return;
    }
    if (guid == PlacesUtils.bookmarks.rootGuid) {
      // The Places root shouldn't be synced at all.
      MirrorLog.warn("Ignoring Places root record", record);
      this.recordTelemetryEvent("mirror", "ignore", "folder",
                                { why: "root" });
      return;
    }

    let serverModified = determineServerModified(record);
    let dateAdded = determineDateAdded(record);
    let title = validateTitle(record.title);
    let description = validateDescription(record.description);

    await this.db.executeCached(`
      REPLACE INTO items(guid, serverModified, needsMerge, kind,
                         dateAdded, title, description)
      VALUES(:guid, :serverModified, :needsMerge, :kind,
             :dateAdded, NULLIF(:title, ""),
             :description)`,
      { guid, serverModified, needsMerge, kind: SyncedBookmarksMirror.KIND.FOLDER,
        dateAdded, title, description });

    let children = record.children;
    if (children && Array.isArray(children)) {
      for (let position = 0; position < children.length; ++position) {
        await maybeYield();
        let childRecordId = children[position];
        let childGuid = validateGuid(childRecordId);
        if (!childGuid) {
          MirrorLog.warn("Ignoring child of folder ${parentGuid} with " +
                         "invalid ID ${childRecordId}", { parentGuid: guid,
                                                          childRecordId });
          this.recordTelemetryEvent("mirror", "ignore", "child",
                                    { why: "id" });
          continue;
        }
        await this.db.executeCached(`
          REPLACE INTO structure(guid, parentGuid, position)
          VALUES(:childGuid, :parentGuid, :position)`,
          { childGuid, parentGuid: guid, position });
      }
    }
    // parentChild relationships are usually determined via the children list
    // in the parent. However, this doesn't work for an item that is directly
    // under the root - such items are invalid, but we still want to store
    // them so we can ignore that entire sub-tree - so such items need special
    // treatment.
    let parentGuid = validateGuid(record.parentid);
    if (parentGuid == PlacesUtils.bookmarks.rootGuid) {
        await this.db.executeCached(`
          INSERT OR IGNORE INTO structure(guid, parentGuid, position)
          VALUES(:guid, :parentGuid, -1)`,
          { guid, parentGuid });
      }
  }

  async storeRemoteLivemark(record, { needsMerge }) {
    let guid = validateGuid(record.id);
    if (!guid) {
      MirrorLog.warn("Ignoring livemark with invalid ID", record.id);
      this.recordTelemetryEvent("mirror", "ignore", "livemark",
                                { why: "id" });
      return;
    }

    let feedURL = validateURL(record.feedUri);
    if (!feedURL) {
      MirrorLog.warn("Ignoring livemark ${guid} with invalid feed URL ${url}",
                     { guid, url: record.feedUri });
      this.recordTelemetryEvent("mirror", "ignore", "livemark",
                                { why: "feed" });
      return;
    }

    let serverModified = determineServerModified(record);
    let dateAdded = determineDateAdded(record);
    let title = validateTitle(record.title);
    let description = validateDescription(record.description);
    let siteURL = validateURL(record.siteUri);

    await this.db.executeCached(`
      REPLACE INTO items(guid, serverModified, needsMerge, kind, dateAdded,
                         title, description, feedURL, siteURL)
      VALUES(:guid, :serverModified, :needsMerge, :kind, :dateAdded,
             NULLIF(:title, ""), :description, :feedURL, :siteURL)`,
      { guid, serverModified, needsMerge,
        kind: SyncedBookmarksMirror.KIND.LIVEMARK,
        dateAdded, title, description, feedURL: feedURL.href,
        siteURL: siteURL ? siteURL.href : null });
  }

  async storeRemoteSeparator(record, { needsMerge }) {
    let guid = validateGuid(record.id);
    if (!guid) {
      MirrorLog.warn("Ignoring separator with invalid ID", record.id);
      this.recordTelemetryEvent("mirror", "ignore", "separator",
                                { why: "id" });
      return;
    }

    let serverModified = determineServerModified(record);
    let dateAdded = determineDateAdded(record);

    await this.db.executeCached(`
      REPLACE INTO items(guid, serverModified, needsMerge, kind,
                         dateAdded)
      VALUES(:guid, :serverModified, :needsMerge, :kind,
             :dateAdded)`,
      { guid, serverModified, needsMerge, kind: SyncedBookmarksMirror.KIND.SEPARATOR,
        dateAdded });
  }

  async storeRemoteTombstone(record, { needsMerge }) {
    let guid = validateGuid(record.id);
    if (!guid) {
      MirrorLog.warn("Ignoring tombstone with invalid ID", record.id);
      this.recordTelemetryEvent("mirror", "ignore", "tombstone",
                                { why: "id" });
      return;
    }

    if (PlacesUtils.bookmarks.userContentRoots.includes(guid)) {
      MirrorLog.warn("Ignoring tombstone for syncable root", guid);
      this.recordTelemetryEvent("mirror", "ignore", "tombstone",
                                { why: "root" });
      return;
    }

    await this.db.executeCached(`
      REPLACE INTO items(guid, serverModified, needsMerge, isDeleted)
      VALUES(:guid, :serverModified, :needsMerge, 1)`,
      { guid, serverModified: determineServerModified(record), needsMerge });
  }

  async maybeStoreRemoteURL(url) {
    await this.db.executeCached(`
      INSERT OR IGNORE INTO urls(guid, url, hash, revHost)
      VALUES(IFNULL((SELECT guid FROM urls
                     WHERE hash = hash(:url) AND
                                  url = :url),
                    GENERATE_GUID()), :url, hash(:url), :revHost)`,
      { url: url.href, revHost: PlacesUtils.getReversedHost(url) });
  }

  async fetchRemoteOrphans() {
    let infos = {
      missingParents: [],
      missingChildren: [],
    };

    let orphanRows = await this.db.execute(`
      SELECT v.guid AS guid, 1 AS missingParent, 0 AS missingChild
      FROM items v
      LEFT JOIN structure s ON s.guid = v.guid
      WHERE NOT v.isDeleted AND
            s.guid IS NULL
      UNION ALL
      SELECT s.guid AS guid, 0 AS missingParent, 1 AS missingChild
      FROM structure s
      LEFT JOIN items v ON v.guid = s.guid
      WHERE v.guid IS NULL`);

    for await (let row of yieldingIterator(orphanRows)) {
      let guid = row.getResultByName("guid");
      let missingParent = row.getResultByName("missingParent");
      if (missingParent) {
        infos.missingParents.push(guid);
      }
      let missingChild = row.getResultByName("missingChild");
      if (missingChild) {
        infos.missingChildren.push(guid);
      }
    }

    return infos;
  }

  /**
   * Checks the sync statuses of all items for consistency. All merged items in
   * the remote tree should exist as either items or tombstones in the local
   * tree, and all NORMAL items and tombstones in the local tree should exist
   * in the remote tree, if the mirror has any merged items.
   *
   * @return {Object.<String, String[]>}
   *         An object containing GUIDs for each problem type:
   *           - `missingLocal`: Merged items in the remote tree that aren't
   *             mentioned in the local tree.
   *           - `missingRemote`: NORMAL items in the local tree that aren't
   *             mentioned in the remote tree.
   */
  async fetchInconsistencies() {
    let infos = {
      missingLocal: [],
      missingRemote: [],
      wrongSyncStatus: [],
    };

    let problemRows = await this.db.execute(`
      SELECT v.guid, 1 AS missingLocal, 0 AS missingRemote, 0 AS wrongSyncStatus
      FROM items v
      LEFT JOIN moz_bookmarks b ON b.guid = v.guid
      LEFT JOIN moz_bookmarks_deleted d ON d.guid = v.guid
      WHERE NOT v.needsMerge AND
            NOT v.isDeleted AND
            b.guid IS NULL AND
            d.guid IS NULL
      UNION ALL
      SELECT b.guid, 0 AS missingLocal, 1 AS missingRemote, 0 AS wrongSyncStatus
      FROM moz_bookmarks b
      LEFT JOIN items v ON v.guid = b.guid
      WHERE EXISTS(SELECT 1 FROM items
                   WHERE NOT needsMerge AND
                         guid <> :rootGuid) AND
            b.syncStatus = :syncStatus AND
            v.guid IS NULL
      UNION ALL
      SELECT d.guid, 0 AS missingLocal, 1 AS missingRemote, 0 AS wrongSyncStatus
      FROM moz_bookmarks_deleted d
      LEFT JOIN items v ON v.guid = d.guid
      WHERE EXISTS(SELECT 1 FROM items
                   WHERE NOT needsMerge AND
                         guid <> :rootGuid) AND
            v.guid IS NULL
      UNION ALL
      SELECT b.guid, 0 AS missingLocal, 0 AS missingRemote, 1 AS wrongSyncStatus
      FROM moz_bookmarks b
      JOIN items v ON v.guid = b.guid
      WHERE EXISTS(SELECT 1 FROM items
                   WHERE NOT needsMerge AND
                         guid <> :rootGuid) AND
            b.guid <> :rootGuid AND
            b.syncStatus <> :syncStatus`,
      { syncStatus: PlacesUtils.bookmarks.SYNC_STATUS.NORMAL,
        rootGuid: PlacesUtils.bookmarks.rootGuid });

    for await (let row of yieldingIterator(problemRows)) {
      let guid = row.getResultByName("guid");
      let missingLocal = row.getResultByName("missingLocal");
      if (missingLocal) {
        infos.missingLocal.push(guid);
      }
      let missingRemote = row.getResultByName("missingRemote");
      if (missingRemote) {
        infos.missingRemote.push(guid);
      }
      let wrongSyncStatus = row.getResultByName("wrongSyncStatus");
      if (wrongSyncStatus) {
        infos.wrongSyncStatus.push(guid);
      }
    }

    return infos;
  }

  /*
   * Checks if Places or mirror have any unsynced/unmerged changes.
   *
   * @return {Boolean}
   *         `true` if something has changed.
   */
  async hasChanges() {
    // In the first subquery, we check incoming items with needsMerge = true
    // except the tombstones who don't correspond to any local bookmark because
    // we don't store them yet, hence never "merged" (see bug 1343103).
    let rows = await this.db.execute(`
      SELECT
      EXISTS (
       SELECT 1
       FROM items v
       LEFT JOIN moz_bookmarks b ON v.guid = b.guid
       WHERE v.needsMerge AND
       (NOT v.isDeleted OR b.guid NOT NULL)
      ) OR EXISTS (
       WITH RECURSIVE
       syncedItems(id, syncChangeCounter) AS (
         SELECT b.id, b.syncChangeCounter FROM moz_bookmarks b
         WHERE b.guid IN (${UserContentRootsAsSqlList})
         UNION ALL
         SELECT b.id, b.syncChangeCounter FROM moz_bookmarks b
         JOIN syncedItems s ON b.parent = s.id
       )
       SELECT 1
       FROM syncedItems
       WHERE syncChangeCounter > 0
      ) OR EXISTS (
       SELECT 1
       FROM moz_bookmarks_deleted
      )
      AS hasChanges
    `);
    return !!rows[0].getResultByName("hasChanges");
  }

  /**
   * Builds a fully rooted, consistent tree from the items and tombstones in the
   * mirror.
   *
   * @param  {Number} remoteTimeSeconds
   *         The current server time, in seconds.
   * @return {BookmarkTree}
   *         The remote bookmark tree.
   */
  async fetchRemoteTree(remoteTimeSeconds) {
    let remoteTree = new BookmarkTree(BookmarkNode.root());
    let startTime = Cu.now();

    // First, build a flat mapping of parents to children. The `LEFT JOIN`
    // includes items orphaned by an interrupted upload on another device.
    // We keep the orphans in "unfiled" until the other device returns and
    // uploads the missing parent.
    // Note that we avoid returning orphaned queries here - there's a really
    // good chance that orphaned queries are actually left-pane queries with
    // the left-pane root missing.
    // In some bizarre edge-cases this might mean some legitimate queries are
    // lost for the user, but this should happen far less often than us finding
    // illegitimate left-pane queries - and if the actual parents ever do
    // appear, they will spring back into life.
    let itemRows = await this.db.execute(`
      SELECT v.guid, IFNULL(s.parentGuid, :unfiledGuid) AS parentGuid,
             IFNULL(s.position, -1) AS position, v.serverModified, v.kind,
             v.needsMerge
      FROM items v
      LEFT JOIN structure s ON s.guid = v.guid
      WHERE NOT v.isDeleted AND
            v.guid <> :rootGuid AND
            (s.parentGuid IS NOT NULL OR v.kind <> :queryKind)
      ORDER BY parentGuid, position = -1, position, v.guid`,
      { rootGuid: PlacesUtils.bookmarks.rootGuid,
        unfiledGuid: PlacesUtils.bookmarks.unfiledGuid,
        queryKind: SyncedBookmarksMirror.KIND.QUERY });

    let pseudoTree = new Map();
    for await (let row of yieldingIterator(itemRows)) {
      let parentGuid = row.getResultByName("parentGuid");
      let node = BookmarkNode.fromRemoteRow(row, remoteTimeSeconds);
      if (pseudoTree.has(parentGuid)) {
        let nodes = pseudoTree.get(parentGuid);
        nodes.push(node);
      } else {
        pseudoTree.set(parentGuid, [node]);
      }
    }

    // Second, build a complete tree from the pseudo-tree. We could do these
    // two steps in SQL, but it's extremely inefficient. An equivalent
    // recursive query, with joins in the base and recursive clauses, takes
    // 10 seconds for a mirror with 5k items. Building the pseudo-tree and
    // the pseudo-tree and recursing in JS takes 30ms for 5k items.
    // (Note: Timing was done before adding maybeYield calls)
    await inflateTree(remoteTree, pseudoTree, PlacesUtils.bookmarks.rootGuid);

    // Note tombstones for remotely deleted items.
    let tombstoneRows = await this.db.execute(`
      SELECT guid FROM items
      WHERE isDeleted AND
            needsMerge`);

    for await (let row of yieldingIterator(tombstoneRows)) {
      let guid = row.getResultByName("guid");
      remoteTree.noteDeleted(guid);
    }

    let elapsedTime = Cu.now() - startTime;
    let totalRows = itemRows.length + tombstoneRows.length;
    this.recordTelemetryEvent("mirror", "fetch", "remoteTree",
                              { time: String(elapsedTime),
                                count: String(totalRows) });

    return remoteTree;
  }

  /**
   * Fetches content info for all items in the mirror that changed since the
   * last sync and don't exist locally.
   *
   * @return {Map.<String, BookmarkContent>}
   *         Changed items in the mirror that don't exist in Places, keyed by
   *         their GUIDs.
   */
  async fetchNewRemoteContents() {
    let newRemoteContents = new Map();
    let startTime = Cu.now();

    let rows = await this.db.execute(`
      SELECT v.guid, IFNULL(v.title, "") AS title, u.url, v.smartBookmarkName,
             IFNULL(s.position, -1) AS position
      FROM items v
      LEFT JOIN urls u ON u.id = v.urlId
      LEFT JOIN structure s ON s.guid = v.guid
      LEFT JOIN moz_bookmarks b ON b.guid = v.guid
      WHERE NOT v.isDeleted AND
            v.needsMerge AND
            b.guid IS NULL AND
            IFNULL(s.parentGuid, :unfiledGuid) <> :rootGuid`,
      { unfiledGuid: PlacesUtils.bookmarks.unfiledGuid,
        rootGuid: PlacesUtils.bookmarks.rootGuid });

    for await (let row of yieldingIterator(rows)) {
      let guid = row.getResultByName("guid");
      let content = BookmarkContent.fromRow(row);
      newRemoteContents.set(guid, content);
    }

    let elapsedTime = Cu.now() - startTime;
    this.recordTelemetryEvent("mirror", "fetch", "newRemoteContents",
                              { time: String(elapsedTime),
                                count: String(rows.length) });

    return newRemoteContents;
  }

  /**
   * Builds a fully rooted, consistent tree from the items and tombstones in
   * Places.
   *
   * @param  {Number} localTimeSeconds
   *         The current local time, in seconds.
   * @return {BookmarkTree}
   *         The local bookmark tree.
   */
  async fetchLocalTree(localTimeSeconds) {
    let localTree = new BookmarkTree(BookmarkNode.root());
    let startTime = Cu.now();

    // This unsightly query collects all descendants and maps their Places types
    // to the Sync record kinds. We start with the roots, and work our way down.
    // The list of roots in `syncedItems` should be updated if we add new
    // syncable roots to Places.
    let itemRows = await this.db.execute(`
      WITH RECURSIVE
      syncedItems(id, level) AS (
        SELECT b.id, 0 AS level FROM moz_bookmarks b
        WHERE b.guid IN (${UserContentRootsAsSqlList})
        UNION ALL
        SELECT b.id, s.level + 1 AS level FROM moz_bookmarks b
        JOIN syncedItems s ON s.id = b.parent
      )
      SELECT b.id, b.guid, p.guid AS parentGuid,
             /* Map Places item types to Sync record kinds. */
             (CASE b.type
                WHEN :bookmarkType THEN (
                  CASE SUBSTR((SELECT h.url FROM moz_places h
                               WHERE h.id = b.fk), 1, 6)
                  /* Queries are bookmarks with a "place:" URL scheme. */
                  WHEN 'place:' THEN :queryKind
                  ELSE :bookmarkKind END)
                WHEN :folderType THEN (
                  CASE WHEN EXISTS(
                    /* Livemarks are folders with a feed URL annotation. */
                    SELECT 1 FROM moz_items_annos a
                    JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id
                    WHERE a.item_id = b.id AND
                          n.name = :feedURLAnno
                  ) THEN :livemarkKind
                  ELSE :folderKind END)
                ELSE :separatorKind END) AS kind,
             b.lastModified / 1000 AS localModified, b.syncChangeCounter
      FROM moz_bookmarks b
      JOIN moz_bookmarks p ON p.id = b.parent
      JOIN syncedItems s ON s.id = b.id
      ORDER BY s.level, b.parent, b.position`,
      { bookmarkType: PlacesUtils.bookmarks.TYPE_BOOKMARK,
        queryKind: SyncedBookmarksMirror.KIND.QUERY,
        bookmarkKind: SyncedBookmarksMirror.KIND.BOOKMARK,
        folderType: PlacesUtils.bookmarks.TYPE_FOLDER,
        feedURLAnno: PlacesUtils.LMANNO_FEEDURI,
        livemarkKind: SyncedBookmarksMirror.KIND.LIVEMARK,
        folderKind: SyncedBookmarksMirror.KIND.FOLDER,
        separatorKind: SyncedBookmarksMirror.KIND.SEPARATOR });

    for await (let row of yieldingIterator(itemRows)) {
      let parentGuid = row.getResultByName("parentGuid");
      let node = BookmarkNode.fromLocalRow(row, localTimeSeconds);
      localTree.insert(parentGuid, node);
    }

    // Note tombstones for locally deleted items.
    let tombstoneRows = await this.db.execute(`
      SELECT guid FROM moz_bookmarks_deleted`);

    for await (let row of yieldingIterator(tombstoneRows)) {
      let guid = row.getResultByName("guid");
      localTree.noteDeleted(guid);
    }

    let elapsedTime = Cu.now() - startTime;
    let totalRows = itemRows.length + tombstoneRows.length;
    this.recordTelemetryEvent("mirror", "fetch", "localTree",
                              { time: String(elapsedTime),
                                count: String(totalRows) });

    return localTree;
  }

  /**
   * Fetches content info for all NEW and UNKNOWN local items that don't exist
   * in the mirror. We'll try to dedupe them to changed items with similar
   * contents and different GUIDs in the mirror.
   *
   * @return {Map.<String, BookmarkContent>}
   *         New items in Places that don't exist in the mirror, keyed by their
   *         GUIDs.
   */
  async fetchNewLocalContents() {
    let newLocalContents = new Map();
    let startTime = Cu.now();

    let rows = await this.db.execute(`
      SELECT b.guid, IFNULL(b.title, "") AS title, h.url,
             (SELECT a.content FROM moz_items_annos a
              JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id
              WHERE a.item_id = b.id AND
                    n.name = :smartBookmarkAnno) AS smartBookmarkName,
             b.position
      FROM moz_bookmarks b
      JOIN moz_bookmarks p ON p.id = b.parent
      LEFT JOIN moz_places h ON h.id = b.fk
      LEFT JOIN items v ON v.guid = b.guid
      WHERE v.guid IS NULL AND
            p.guid <> :rootGuid AND
            b.syncStatus <> :syncStatus`,
      { smartBookmarkAnno: PlacesSyncUtils.bookmarks.SMART_BOOKMARKS_ANNO,
        rootGuid: PlacesUtils.bookmarks.rootGuid,
        syncStatus: PlacesUtils.bookmarks.SYNC_STATUS.NORMAL });

    for await (let row of yieldingIterator(rows)) {
      let guid = row.getResultByName("guid");
      let content = BookmarkContent.fromRow(row);
      newLocalContents.set(guid, content);
    }

    let elapsedTime = Cu.now() - startTime;
    this.recordTelemetryEvent("mirror", "fetch", "newLocalContents",
                              { time: String(elapsedTime),
                                count: String(rows.length) });

    return newLocalContents;
  }

  /**
   * Builds a temporary table with the merge states of all nodes in the merged
   * tree, rewrites tag queries, and updates Places to match the merged tree.
   *
   * Conceptually, we examine the merge state of each item, and either keep the
   * complete local state, take the complete remote state, or apply a new
   * structure state and flag the item for reupload.
   *
   * Note that we update Places and flag items *before* upload, while iOS
   * updates the mirror *after* a successful upload. This simplifies our
   * implementation, though we lose idempotent merges. If upload is interrupted,
   * the next sync won't distinguish between new merge states from the previous
   * sync, and local changes. Since this is how Desktop behaved before
   * structured application, that's OK. In the future, we can make this more
   * like iOS.
   *
   * @param {MergedBookmarkNode} mergedRoot
   *        The root of the merged bookmark tree.
   * @param {Object[]} localDeletions
   *        `{ guid, level }` tuples for items to remove from Places and flag as
   *        merged.
   * @param {String[]} remoteDeletions
   *        Remotely deleted GUIDs that should be flagged as merged.
   */
  async updateLocalItemsInPlaces(mergedRoot, localDeletions, remoteDeletions) {
    MirrorLog.debug("Setting up merge states table");
    let mergeStatesParams = Array.from(mergedRoot.mergeStatesParams());
    if (mergeStatesParams.length) {
      await this.db.execute(`
        INSERT INTO mergeStates(localGuid, mergedGuid, parentGuid, level,
                                position, valueState, structureState)
        VALUES(IFNULL(:localGuid, :mergedGuid), :mergedGuid, :parentGuid,
               :level, :position, :valueState, :structureState)`,
        mergeStatesParams);
    }

    MirrorLog.debug("Rewriting tag queries in mirror");
    await this.rewriteRemoteTagQueries();

    MirrorLog.debug("Inserting new URLs into Places");
    await this.db.execute(`
      INSERT OR IGNORE INTO moz_places(url, url_hash, rev_host, hidden,
                                       frecency, guid)
      SELECT u.url, u.hash, u.revHost, 0,
             (CASE v.kind WHEN :queryKind THEN 0 ELSE -1 END),
             IFNULL((SELECT h.guid FROM moz_places h
                     WHERE h.url_hash = u.hash AND
                           h.url = u.url), u.guid)
      FROM items v
      JOIN urls u ON u.id = v.urlId
      JOIN mergeStates r ON r.mergedGuid = v.guid
      WHERE r.valueState = :valueState`,
      { queryKind: SyncedBookmarksMirror.KIND.QUERY,
        valueState: BookmarkMergeState.TYPE.REMOTE });
    await this.db.execute(`DELETE FROM moz_updatehostsinsert_temp`);

    // Deleting from `itemsToMerge` fires the `insertNewLocalItems` and
    // `updateExistingLocalItems` triggers.
    MirrorLog.debug("Updating value states for local bookmarks");
    await this.db.execute(`DELETE FROM itemsToMerge`);

    // Update the structure. The mirror stores structure info in a separate
    // table, like iOS, while Places stores structure info on children. We don't
    // check the parent's merge state here because our merged tree might
    // diverge from the server if we're missing children, or moved children
    // without parents to "unfiled". In that case, we *don't* want to reupload
    // the new local structure to the server.
    MirrorLog.debug("Updating structure states for local bookmarks");
    await this.db.execute(`DELETE FROM structureToMerge`);

    MirrorLog.debug("Removing remotely deleted items from Places");
    for (let chunk of PlacesSyncUtils.chunkArray(localDeletions,
      SQLITE_MAX_VARIABLE_NUMBER)) {

      let guids = chunk.map(({ guid }) => guid);

      // Record item removed notifications.
      await this.db.execute(`
        WITH
        guidsWithLevelsToDelete(guid, level) AS (
          VALUES ${chunk.map(({ level }) => `(?, ${level})`).join(",")}
        )
        INSERT INTO itemsRemoved(itemId, parentId, position, type, placeId,
                                 guid, parentGuid, level)
        SELECT b.id, b.parent, b.position, b.type, b.fk, b.guid, p.guid,
               o.level
        FROM moz_bookmarks b
        JOIN moz_bookmarks p ON p.id = b.parent
        JOIN guidsWithLevelsToDelete o ON o.guid = b.guid`,
        guids);

      // Recalculate frecencies. The `isUntagging` check is a formality, since
      // tags shouldn't have annos or tombstones, should not appear in local
      // deletions, and should not affect frecency. This can go away with
      // bug 1293445.
      await this.db.execute(`
        UPDATE moz_places SET
          frecency = -1
        WHERE id IN (SELECT placeId FROM itemsRemoved
                     WHERE NOT isUntagging)`);

      // Remove annos for the deleted items.
      await this.db.execute(`
        DELETE FROM moz_items_annos
        WHERE item_id IN (SELECT itemId FROM itemsRemoved
                          WHERE NOT isUntagging)`);

      // Remove any local tombstones for deleted items.
      await this.db.execute(`
        DELETE FROM moz_bookmarks_deleted
        WHERE guid IN (SELECT guid FROM itemsRemoved)`);

      await this.db.execute(`
        DELETE FROM moz_bookmarks
        WHERE id IN (SELECT itemId FROM itemsRemoved
                     WHERE NOT isUntagging)`);

      // Flag locally deleted items as merged.
      await this.db.execute(`
        UPDATE items SET
          needsMerge = 0
        WHERE needsMerge AND
              guid IN (SELECT guid FROM itemsRemoved
                       WHERE NOT isUntagging)`);
    }

    MirrorLog.debug("Flagging remotely deleted items as merged");
    for (let chunk of PlacesSyncUtils.chunkArray(remoteDeletions,
      SQLITE_MAX_VARIABLE_NUMBER)) {

      await this.db.execute(`
        UPDATE items SET
          needsMerge = 0
        WHERE needsMerge AND
              guid IN (${new Array(chunk.length).fill("?").join(",")})`,
        chunk);
    }
  }

  /**
   * Creates local tag folders mentioned in remotely changed tag queries, then
   * rewrites the query URLs in the mirror to point to the new local folders.
   *
   * For example, an incoming tag query of, say, "place:type=6&folder=3" means
   * it is a query for whatever tag is defined by the local record with id=3
   * (and the incoming record has the actual tag in the folderName field).
   * We need to ensure that the URL is adjusted so the folder ID refers to
   * whatever local folder ID represents that tag.
   *
   * This can be removed once bug 1293445 lands.
   */
  async rewriteRemoteTagQueries() {
    // Create local tag folders that don't already exist. This fires the
    // `tagLocalPlace` trigger.
    await this.db.execute(`
      INSERT INTO localTags(tag)
      SELECT v.tagFolderName FROM items v
      JOIN mergeStates r ON r.mergedGuid = v.guid
      WHERE r.valueState = :valueState AND
            v.tagFolderName NOT NULL`,
      { valueState: BookmarkMergeState.TYPE.REMOTE });

    let queryRows = await this.db.execute(`
      SELECT u.id AS urlId, u.url, b.id AS newTagFolderId FROM urls u
      JOIN items v ON v.urlId = u.id
      JOIN mergeStates r ON r.mergedGuid = v.guid
      JOIN moz_bookmarks b ON b.title = v.tagFolderName
      JOIN moz_bookmarks p ON p.id = b.parent
      WHERE p.guid = :tagsGuid AND
            r.valueState = :valueState AND
            v.kind = :queryKind AND
            v.tagFolderName NOT NULL`,
      { tagsGuid: PlacesUtils.bookmarks.tagsGuid,
        valueState: BookmarkMergeState.TYPE.REMOTE,
        queryKind: SyncedBookmarksMirror.KIND.QUERY });

    let urlsParams = [];
    for (let row of queryRows) {
      let url = new URL(row.getResultByName("url"));
      let tagQueryParams = new URLSearchParams(url.pathname);
      let type = Number(tagQueryParams.get("type"));
      if (type != Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_CONTENTS) {
        continue;
      }

      // Rewrite the query URL to point to the new folder.
      let newTagFolderId = row.getResultByName("newTagFolderId");
      tagQueryParams.set("folder", newTagFolderId);

      let newURLHref = url.protocol + tagQueryParams;
      urlsParams.push({
        urlId: row.getResultByName("urlId"),
        url: newURLHref,
      });
    }

    if (urlsParams.length) {
      await this.db.execute(`
        UPDATE urls SET
          url = :url,
          hash = hash(:url)
        WHERE id = :urlId`,
        urlsParams);
    }
  }

  /**
   * Records Places observer notifications for removed, added, moved, and
   * changed items.
   *
   * @param {BookmarkObserverRecorder} observersToNotify
   */
  async noteObserverChanges(observersToNotify) {
    MirrorLog.debug("Recording observer notifications for removed items");
    // `ORDER BY v.level DESC` sorts deleted children before parents, to ensure
    // that we update caches in the correct order (bug 1297941). We also order
    // by parent and position so that the notifications are well-ordered for
    // tests.
    let removedItemRows = await this.db.execute(`
      SELECT v.itemId AS id, v.parentId, v.parentGuid, v.position, v.type,
             h.url, v.guid, v.isUntagging
      FROM itemsRemoved v
      LEFT JOIN moz_places h ON h.id = v.placeId
      ORDER BY v.level DESC, v.parentId, v.position`);
    for await (let row of yieldingIterator(removedItemRows)) {
      let info = {
        id: row.getResultByName("id"),
        parentId: row.getResultByName("parentId"),
        position: row.getResultByName("position"),
        type: row.getResultByName("type"),
        urlHref: row.getResultByName("url"),
        guid: row.getResultByName("guid"),
        parentGuid: row.getResultByName("parentGuid"),
        isUntagging: row.getResultByName("isUntagging"),
      };
      observersToNotify.noteItemRemoved(info);
    }

    MirrorLog.debug("Recording observer notifications for changed GUIDs");
    let changedGuidRows = await this.db.execute(`
      SELECT b.id, b.lastModified, b.type, b.guid AS newGuid,
             c.oldGuid, p.id AS parentId, p.guid AS parentGuid
      FROM guidsChanged c
      JOIN moz_bookmarks b ON b.id = c.itemId
      JOIN moz_bookmarks p ON p.id = b.parent
      ORDER BY c.level, p.id, b.position`);
    for await (let row of yieldingIterator(changedGuidRows)) {
      let info = {
        id: row.getResultByName("id"),
        lastModified: row.getResultByName("lastModified"),
        type: row.getResultByName("type"),
        newGuid: row.getResultByName("newGuid"),
        oldGuid: row.getResultByName("oldGuid"),
        parentId: row.getResultByName("parentId"),
        parentGuid: row.getResultByName("parentGuid"),
      };
      observersToNotify.noteGuidChanged(info);
    }

    MirrorLog.debug("Recording observer notifications for new items");
    let newItemRows = await this.db.execute(`
      SELECT b.id, p.id AS parentId, b.position, b.type, h.url,
             IFNULL(b.title, "") AS title, b.dateAdded, b.guid,
             p.guid AS parentGuid, n.isTagging
      FROM itemsAdded n
      JOIN moz_bookmarks b ON b.guid = n.guid
      JOIN moz_bookmarks p ON p.id = b.parent
      LEFT JOIN moz_places h ON h.id = b.fk
      ORDER BY n.level, p.id, b.position`);
    for await (let row of yieldingIterator(newItemRows)) {
      let info = {
        id: row.getResultByName("id"),
        parentId: row.getResultByName("parentId"),
        position: row.getResultByName("position"),
        type: row.getResultByName("type"),
        urlHref: row.getResultByName("url"),
        title: row.getResultByName("title"),
        dateAdded: row.getResultByName("dateAdded"),
        guid: row.getResultByName("guid"),
        parentGuid: row.getResultByName("parentGuid"),
        isTagging: row.getResultByName("isTagging"),
      };
      observersToNotify.noteItemAdded(info);
    }

    MirrorLog.debug("Recording observer notifications for moved items");
    let movedItemRows = await this.db.execute(`
      SELECT b.id, b.guid, b.type, p.id AS newParentId, c.oldParentId,
             p.guid AS newParentGuid, c.oldParentGuid,
             b.position AS newPosition, c.oldPosition
      FROM itemsMoved c
      JOIN moz_bookmarks b ON b.id = c.itemId
      JOIN moz_bookmarks p ON p.id = b.parent
      ORDER BY c.level, newParentId, newPosition`);
    for await (let row of yieldingIterator(movedItemRows)) {
      let info = {
        id: row.getResultByName("id"),
        guid: row.getResultByName("guid"),
        type: row.getResultByName("type"),
        newParentId: row.getResultByName("newParentId"),
        oldParentId: row.getResultByName("oldParentId"),
        newParentGuid: row.getResultByName("newParentGuid"),
        oldParentGuid: row.getResultByName("oldParentGuid"),
        newPosition: row.getResultByName("newPosition"),
        oldPosition: row.getResultByName("oldPosition"),
      };
      observersToNotify.noteItemMoved(info);
    }

    MirrorLog.debug("Recording observer notifications for changed items");
    let changedItemRows = await this.db.execute(`
      SELECT b.id, b.guid, b.lastModified, b.type,
             IFNULL(b.title, "") AS newTitle,
             IFNULL(c.oldTitle, "") AS oldTitle,
             h.url AS newURL, i.url AS oldURL,
             p.id AS parentId, p.guid AS parentGuid
      FROM itemsChanged c
      JOIN moz_bookmarks b ON b.id = c.itemId
      JOIN moz_bookmarks p ON p.id = b.parent
      LEFT JOIN moz_places h ON h.id = b.fk
      LEFT JOIN moz_places i ON i.id = c.oldPlaceId
      ORDER BY c.level, p.id, b.position`);
    for await (let row of yieldingIterator(changedItemRows)) {
      let info = {
        id: row.getResultByName("id"),
        guid: row.getResultByName("guid"),
        lastModified: row.getResultByName("lastModified"),
        type: row.getResultByName("type"),
        newTitle: row.getResultByName("newTitle"),
        oldTitle: row.getResultByName("oldTitle"),
        newURLHref: row.getResultByName("newURL"),
        oldURLHref: row.getResultByName("oldURL"),
        parentId: row.getResultByName("parentId"),
        parentGuid: row.getResultByName("parentGuid"),
      };
      observersToNotify.noteItemChanged(info);
    }

    MirrorLog.debug("Recording observer notifications for changed annos");
    let annoRows = await this.db.execute(`
      SELECT itemId, annoName, wasRemoved FROM annosChanged
      ORDER BY itemId`);
    for await (let row of yieldingIterator(annoRows)) {
      let id = row.getResultByName("itemId");
      let name = row.getResultByName("annoName");
      if (row.getResultByName("wasRemoved")) {
        observersToNotify.noteAnnoRemoved(id, name);
      } else {
        observersToNotify.noteAnnoSet(id, name);
      }
    }

    MirrorLog.debug("Recording notifications for changed keywords");
    let keywordsChangedRows = await this.db.execute(`
      SELECT EXISTS(SELECT 1 FROM itemsAdded WHERE keywordChanged) OR
             EXISTS(SELECT 1 FROM itemsChanged WHERE keywordChanged)
             AS keywordsChanged`);
    observersToNotify.shouldInvalidateKeywords =
      !!keywordsChangedRows[0].getResultByName("keywordsChanged");
  }

  /**
   * Stores a snapshot of all locally changed items in a temporary table for
   * upload. This is called from within the merge transaction, to ensure that
   * structure changes made during the sync don't cause us to upload an
   * inconsistent tree.
   *
   * For an example of why we use a temporary table instead of reading directly
   * from Places, consider a user adding a bookmark, then changing its parent
   * folder. We first add the bookmark to the default folder, bump the change
   * counter of the new bookmark and the default folder, then trigger a sync.
   * Depending on how quickly the user picks the new parent, we might upload
   * a record for the default folder, commit the move, then upload the bookmark.
   * We'll still upload the new parent on the next sync, but, in the meantime,
   * we've introduced a parent-child disagreement. This can also happen if the
   * user moves many items between folders.
   *
   * Conceptually, `itemsToUpload` is a transient "view" of locally changed
   * items. The change counter in Places is the persistent record of items that
   * we need to upload, so, if upload is interrupted or fails, we'll stage the
   * items again on the next sync.
   *
   * @param  {String[]} weakUpload
   *         GUIDs of bookmarks to weakly upload.
   */
  async stageItemsToUpload(weakUpload) {
    // Stage explicit weak uploads such as repair responses.
    for (let chunk of PlacesSyncUtils.chunkArray(weakUpload,
      SQLITE_MAX_VARIABLE_NUMBER)) {
      await this.db.execute(`
        INSERT INTO itemsToWeaklyReupload(id)
        SELECT b.id FROM moz_bookmarks b
        WHERE b.guid IN (${new Array(chunk.length).fill("?").join(",")})`,
        chunk);
    }

    // Stage remotely changed items with older local creation dates. These are
    // tracked "weakly": if the upload is interrupted or fails, we won't
    // reupload the record on the next sync.
    await this.db.execute(`
      INSERT OR IGNORE INTO itemsToWeaklyReupload(id)
      SELECT b.id FROM moz_bookmarks b
      JOIN mergeStates r ON r.mergedGuid = b.guid
      JOIN items v ON v.guid = r.mergedGuid
      WHERE r.valueState = :valueState AND
            /* "b.dateAdded" is in microseconds; "v.dateAdded" is in
               milliseconds. */
            b.dateAdded / 1000 < v.dateAdded`,
      { valueState: BookmarkMergeState.TYPE.REMOTE });

    // Stage remaining locally changed items for upload.
    await this.db.execute(`
      WITH RECURSIVE
      syncedItems(id, level) AS (
        SELECT b.id, 0 AS level FROM moz_bookmarks b
        WHERE b.guid IN (${UserContentRootsAsSqlList})
        UNION ALL
        SELECT b.id, s.level + 1 AS level FROM moz_bookmarks b
        JOIN syncedItems s ON s.id = b.parent
      )
      INSERT INTO itemsToUpload(id, guid, syncChangeCounter, parentGuid,
                                parentTitle, dateAdded, type, title, isQuery,
                                url, tags, description, loadInSidebar,
                                smartBookmarkName, keyword, feedURL, siteURL,
                                position)
      SELECT b.id, b.guid, b.syncChangeCounter, p.guid, p.title,
             b.dateAdded / 1000, b.type, b.title,
             IFNULL(SUBSTR(h.url, 1, 6) = 'place:', 0), h.url,
             (SELECT GROUP_CONCAT(t.title, ',') FROM moz_bookmarks e
              JOIN moz_bookmarks t ON t.id = e.parent
              JOIN moz_bookmarks r ON r.id = t.parent
              WHERE b.type = :bookmarkType AND
                    r.guid = :tagsGuid AND
                    e.fk = h.id),
             (SELECT a.content FROM moz_items_annos a
              JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id
              WHERE b.type IN (:bookmarkType, :folderType) AND
                    a.item_id = b.id AND
                    n.name = :descriptionAnno),
             IFNULL((SELECT a.content FROM moz_items_annos a
                     JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id
                     WHERE a.item_id = b.id AND
                           n.name = :sidebarAnno), 0),
             (SELECT a.content FROM moz_items_annos a
              JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id
              WHERE a.item_id = b.id AND
                    n.name = :smartBookmarkAnno),
             (SELECT keyword FROM moz_keywords WHERE place_id = h.id),
             (SELECT a.content FROM moz_items_annos a
              JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id
              WHERE b.type = :folderType AND
                    a.item_id = b.id AND
                    n.name = :feedURLAnno),
             (SELECT a.content FROM moz_items_annos a
              JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id
              WHERE b.type = :folderType AND
                    a.item_id = b.id AND
                    n.name = :siteURLAnno),
             b.position
      FROM moz_bookmarks b
      JOIN moz_bookmarks p ON p.id = b.parent
      JOIN syncedItems s ON s.id = b.id
      LEFT JOIN moz_places h ON h.id = b.fk
      LEFT JOIN itemsToWeaklyReupload w ON w.id = b.id
      WHERE b.syncChangeCounter >= 1 OR
            w.id NOT NULL`,
      { bookmarkType: PlacesUtils.bookmarks.TYPE_BOOKMARK,
        tagsGuid: PlacesUtils.bookmarks.tagsGuid,
        descriptionAnno: PlacesSyncUtils.bookmarks.DESCRIPTION_ANNO,
        sidebarAnno: PlacesSyncUtils.bookmarks.SIDEBAR_ANNO,
        smartBookmarkAnno: PlacesSyncUtils.bookmarks.SMART_BOOKMARKS_ANNO,
        folderType: PlacesUtils.bookmarks.TYPE_FOLDER,
        feedURLAnno: PlacesUtils.LMANNO_FEEDURI,
        siteURLAnno: PlacesUtils.LMANNO_SITEURI });

    // Record tag folder names for tag queries. Parsing query URLs one by one
    // is inefficient, but queries aren't common today, and we can remove this
    // logic entirely once bug 1293445 lands.
    let queryRows = await this.db.execute(`
      SELECT id, url FROM itemsToUpload
      WHERE isQuery`);

    let tagFolderNameParams = [];
    for (let row of queryRows) {
      let url = new URL(row.getResultByName("url"));
      let tagQueryParams = new URLSearchParams(url.pathname);
      let type = Number(tagQueryParams.get("type"));
      if (type == Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_CONTENTS) {
        continue;
      }
      let tagFolderId = Number(tagQueryParams.get("folder"));
      tagFolderNameParams.push({
        id: row.getResultByName("id"),
        tagFolderId,
        folderType: PlacesUtils.bookmarks.TYPE_FOLDER,
      });
    }

    if (tagFolderNameParams.length) {
      await this.db.execute(`
        UPDATE itemsToUpload SET
          tagFolderName = (SELECT b.title FROM moz_bookmarks b
                           WHERE b.id = :tagFolderId AND
                                 b.type = :folderType)
        WHERE id = :id`, tagFolderNameParams);
    }

    // Record the child GUIDs of locally changed folders, which we use to
    // populate the `children` array in the record.
    await this.db.execute(`
      INSERT INTO structureToUpload(guid, parentId, position)
      SELECT b.guid, b.parent, b.position FROM moz_bookmarks b
      JOIN itemsToUpload o ON o.id = b.parent`);

    // Finally, stage tombstones for deleted items. Ignore conflicts if we have
    // tombstones for undeleted items; Places Maintenance should clean these up.
    await this.db.execute(`
      INSERT OR IGNORE INTO itemsToUpload(guid, syncChangeCounter, isDeleted,
                                          dateAdded)
      SELECT guid, 1, 1, dateRemoved / 1000 FROM moz_bookmarks_deleted`);
  }

  /**
   * Inflates Sync records for all staged outgoing items.
   *
   * @return {Object.<String, BookmarkChangeRecord>}
   *         A changeset containing Sync record cleartexts for outgoing items
   *         and tombstones, keyed by their Sync record IDs.
   */
  async fetchLocalChangeRecords() {
    let changeRecords = {};
    let childRecordIdsByLocalParentId = new Map();

    let childGuidRows = await this.db.execute(`
      SELECT parentId, guid FROM structureToUpload
      ORDER BY parentId, position`);

    for (let row of childGuidRows) {
      let localParentId = row.getResultByName("parentId");
      let childRecordId = PlacesSyncUtils.bookmarks.guidToRecordId(
        row.getResultByName("guid"));
      if (childRecordIdsByLocalParentId.has(localParentId)) {
        let childRecordIds = childRecordIdsByLocalParentId.get(localParentId);
        childRecordIds.push(childRecordId);
      } else {
        childRecordIdsByLocalParentId.set(localParentId, [childRecordId]);
      }
    }

    let itemRows = await this.db.execute(`
      SELECT id, syncChangeCounter, guid, isDeleted, type, isQuery,
             smartBookmarkName, tagFolderName,
             loadInSidebar, keyword, tags, url, IFNULL(title, "") AS title,
             description, feedURL, siteURL, position, parentGuid,
             IFNULL(parentTitle, "") AS parentTitle, dateAdded
      FROM itemsToUpload`);

    for await (let row of yieldingIterator(itemRows)) {
      let syncChangeCounter = row.getResultByName("syncChangeCounter");

      let guid = row.getResultByName("guid");
      let recordId = PlacesSyncUtils.bookmarks.guidToRecordId(guid);

      // Tombstones don't carry additional properties.
      let isDeleted = row.getResultByName("isDeleted");
      if (isDeleted) {
        changeRecords[recordId] = new BookmarkChangeRecord(syncChangeCounter, {
          id: recordId,
          deleted: true,
        });
        continue;
      }

      let parentGuid = row.getResultByName("parentGuid");
      let parentRecordId = PlacesSyncUtils.bookmarks.guidToRecordId(parentGuid);

      let type = row.getResultByName("type");
      switch (type) {
        case PlacesUtils.bookmarks.TYPE_BOOKMARK: {
          let isQuery = row.getResultByName("isQuery");
          if (isQuery) {
            let queryCleartext = {
              id: recordId,
              type: "query",
              // We ignore `parentid` and use the parent's `children`, but older
              // Desktops and Android use `parentid` as the canonical parent.
              // iOS is stricter and requires both `children` and `parentid` to
              // match.
              parentid: parentRecordId,
              // Older Desktops use `hasDupe` (along with `parentName` for
              // deduping), if hasDupe is true, then they won't attempt deduping
              // (since they believe that a duplicate for this record should
              // exist). We set it to true to prevent them from applying their
              // deduping logic.
              hasDupe: true,
              parentName: row.getResultByName("parentTitle"),
              // Omit `dateAdded` from the record if it's not set locally.
              dateAdded: row.getResultByName("dateAdded") || undefined,
              bmkUri: row.getResultByName("url"),
              title: row.getResultByName("title"),
              queryId: row.getResultByName("smartBookmarkName"),
              // folderName should never be an empty string or null
              folderName: row.getResultByName("tagFolderName") || undefined,
            };
            let description = row.getResultByName("description");
            if (description) {
              queryCleartext.description = description;
            }
            changeRecords[recordId] = new BookmarkChangeRecord(
              syncChangeCounter, queryCleartext);
            continue;
          }

          let bookmarkCleartext = {
            id: recordId,
            type: "bookmark",
            parentid: parentRecordId,
            hasDupe: true,
            parentName: row.getResultByName("parentTitle"),
            dateAdded: row.getResultByName("dateAdded") || undefined,
            bmkUri: row.getResultByName("url"),
            title: row.getResultByName("title"),
          };
          let description = row.getResultByName("description");
          if (description) {
            bookmarkCleartext.description = description;
          }
          let loadInSidebar = row.getResultByName("loadInSidebar");
          if (loadInSidebar) {
            bookmarkCleartext.loadInSidebar = true;
          }
          let keyword = row.getResultByName("keyword");
          if (keyword) {
            bookmarkCleartext.keyword = keyword;
          }
          let tags = row.getResultByName("tags");
          if (tags) {
            bookmarkCleartext.tags = tags.split(",");
          }
          changeRecords[recordId] = new BookmarkChangeRecord(
            syncChangeCounter, bookmarkCleartext);
          continue;
        }

        case PlacesUtils.bookmarks.TYPE_FOLDER: {
          let feedURLHref = row.getResultByName("feedURL");
          if (feedURLHref) {
            // Places stores livemarks as folders with feed and site URL annos.
            // See bug 1072833 for discussion about changing them to queries.
            let livemarkCleartext = {
              id: recordId,
              type: "livemark",
              parentid: parentRecordId,
              hasDupe: true,
              parentName: row.getResultByName("parentTitle"),
              dateAdded: row.getResultByName("dateAdded") || undefined,
              title: row.getResultByName("title"),
              feedUri: feedURLHref,
            };
            let description = row.getResultByName("description");
            if (description) {
              livemarkCleartext.description = description;
            }
            let siteURLHref = row.getResultByName("siteURL");
            if (siteURLHref) {
              livemarkCleartext.siteUri = siteURLHref;
            }
            changeRecords[recordId] = new BookmarkChangeRecord(
              syncChangeCounter, livemarkCleartext);
            continue;
          }

          let folderCleartext = {
            id: recordId,
            type: "folder",
            parentid: parentRecordId,
            hasDupe: true,
            parentName: row.getResultByName("parentTitle"),
            dateAdded: row.getResultByName("dateAdded") || undefined,
            title: row.getResultByName("title"),
          };
          let description = row.getResultByName("description");
          if (description) {
            folderCleartext.description = description;
          }
          let localId = row.getResultByName("id");
          let childRecordIds = childRecordIdsByLocalParentId.get(localId);
          folderCleartext.children = childRecordIds || [];
          changeRecords[recordId] = new BookmarkChangeRecord(
            syncChangeCounter, folderCleartext);
          continue;
        }

        case PlacesUtils.bookmarks.TYPE_SEPARATOR: {
          let separatorCleartext = {
            id: recordId,
            type: "separator",
            parentid: parentRecordId,
            hasDupe: true,
            parentName: row.getResultByName("parentTitle"),
            dateAdded: row.getResultByName("dateAdded") || undefined,
            // Older Desktops use `pos` for deduping.
            pos: row.getResultByName("position"),
          };
          changeRecords[recordId] = new BookmarkChangeRecord(
            syncChangeCounter, separatorCleartext);
          continue;
        }

        default:
          throw new TypeError("Can't create record for unknown Places item");
      }
    }

    return changeRecords;
  }

  /**
   * Closes the mirror database connection. This is called automatically on
   * shutdown, but may also be called explicitly when the mirror is no longer
   * needed.
   */
  finalize() {
    if (!this.finalizePromise) {
      this.finalizePromise = (async () => {
        await this.db.close();
        this.finalizeAt.removeBlocker(this.finalizeBound);
      })();
    }
    return this.finalizePromise;
  }
}

this.SyncedBookmarksMirror = SyncedBookmarksMirror;

/** Synced item kinds. Each corresponds to a Sync record type. */
SyncedBookmarksMirror.KIND = {
  BOOKMARK: 1,
  QUERY: 2,
  FOLDER: 3,
  LIVEMARK: 4,
  SEPARATOR: 5,
};

/** Key names for the key-value `meta` table. */
SyncedBookmarksMirror.META_KEY = {
  LAST_MODIFIED: "collection/lastModified",
  SYNC_ID: "collection/syncId",
};

/**
 * An error thrown when the merge can't proceed because the local or remote
 * tree is inconsistent.
 */
SyncedBookmarksMirror.ConsistencyError =
  class ConsistencyError extends Error {};

// Indicates if the mirror should be replaced because the database file is
// corrupt.
function isDatabaseCorrupt(error) {
  return error instanceof Ci.mozIStorageError &&
         (error.result == Ci.mozIStorageError.CORRUPT ||
          error.result == Ci.mozIStorageError.NOTADB);
}

/**
 * Migrates the mirror database schema to the latest version.
 *
 * @param {Sqlite.OpenedConnection} db
 *        The mirror database connection.
 */
async function migrateMirrorSchema(db) {
  let currentSchemaVersion = await db.getSchemaVersion("mirror");
  if (currentSchemaVersion < 1) {
    await initializeMirrorDatabase(db);
  }
  // Downgrading from a newer profile to an older profile rolls back the
  // schema version, but leaves all new columns in place. We'll run the
  // migration logic again on the next upgrade.
  await db.setSchemaVersion(MIRROR_SCHEMA_VERSION, "mirror");
}

/**
 * Initializes a new mirror database, creating persistent tables, indexes, and
 * roots.
 *
 * @param {Sqlite.OpenedConnection} db
 *        The mirror database connection.
 */
async function initializeMirrorDatabase(db) {
  // Key-value metadata table. Stores the server collection last modified time
  // and sync ID.
  await db.execute(`CREATE TABLE mirror.meta(
    key TEXT PRIMARY KEY,
    value NOT NULL
  )`);

  await db.execute(`CREATE TABLE mirror.items(
    id INTEGER PRIMARY KEY,
    guid TEXT UNIQUE NOT NULL,
    /* The server modified time, in milliseconds. */
    serverModified INTEGER NOT NULL DEFAULT 0,
    needsMerge BOOLEAN NOT NULL DEFAULT 0,
    isDeleted BOOLEAN NOT NULL DEFAULT 0,
    kind INTEGER NOT NULL DEFAULT -1,
    /* The creation date, in milliseconds. */
    dateAdded INTEGER NOT NULL DEFAULT 0,
    title TEXT,
    urlId INTEGER REFERENCES urls(id)
                  ON DELETE SET NULL,
    keyword TEXT,
    tagFolderName TEXT,
    description TEXT,
    loadInSidebar BOOLEAN,
    smartBookmarkName TEXT,
    feedURL TEXT,
    siteURL TEXT,
    /* Only bookmarks and queries must have URLs. */
    CHECK(CASE WHEN kind IN (${[
                      SyncedBookmarksMirror.KIND.BOOKMARK,
                      SyncedBookmarksMirror.KIND.QUERY,
                    ].join(",")}) THEN urlId NOT NULL
               ELSE urlId IS NULL END)
  )`);

  await db.execute(`CREATE TABLE mirror.structure(
    guid TEXT NOT NULL PRIMARY KEY,
    parentGuid TEXT NOT NULL REFERENCES items(guid)
                             ON DELETE CASCADE,
    position INTEGER NOT NULL
  ) WITHOUT ROWID`);

  await db.execute(`CREATE TABLE mirror.urls(
    id INTEGER PRIMARY KEY,
    guid TEXT NOT NULL,
    url TEXT NOT NULL,
    hash INTEGER NOT NULL,
    revHost TEXT NOT NULL
  )`);

  await db.execute(`CREATE TABLE mirror.tags(
    itemId INTEGER NOT NULL REFERENCES items(id)
                            ON DELETE CASCADE,
    tag TEXT NOT NULL
  )`);

  await db.execute(`CREATE INDEX mirror.urlHashes ON urls(hash)`);

  await createMirrorRoots(db);
}

/**
 * Sets up the syncable roots. All items in the mirror we apply will descend
 * from these roots - however, malformed records from the server which create
 * a different root *will* be created in the mirror - just not applied.
 *
 *
 * @param {Sqlite.OpenedConnection} db
 *        The mirror database connection.
 */
async function createMirrorRoots(db) {
  const syncableRoots = [{
    guid: PlacesUtils.bookmarks.rootGuid,
    // The Places root is its own parent, to satisfy the foreign key and
    // `NOT NULL` constraints on `structure`.
    parentGuid: PlacesUtils.bookmarks.rootGuid,
    position: -1,
    needsMerge: false,
  }, ...PlacesUtils.bookmarks.userContentRoots.map((guid, position) => {
    return {
      guid,
      parentGuid: PlacesUtils.bookmarks.rootGuid,
      position,
      needsMerge: true,
    };
  })];

  for (let { guid, parentGuid, position, needsMerge } of syncableRoots) {
    await db.executeCached(`
      INSERT INTO items(guid, kind, needsMerge)
      VALUES(:guid, :kind, :needsMerge)`,
      { guid, kind: SyncedBookmarksMirror.KIND.FOLDER, needsMerge });

    await db.executeCached(`
      INSERT INTO structure(guid, parentGuid, position)
      VALUES(:guid, :parentGuid, :position)`,
      { guid, parentGuid, position });
  }
}

/**
 * Creates temporary tables, views, and triggers to apply the mirror to Places.
 *
 * The bulk of the logic to apply all remotely changed items is defined in
 * `INSTEAD OF DELETE` triggers on the `itemsToMerge` and `structureToMerge`
 * views. When we execute `DELETE FROM newRemote{Items, Structure}`, SQLite
 * fires the triggers for each row in the view. This is equivalent to, but more
 * efficient than, issuing `SELECT * FROM newRemote{Items, Structure}`,
 * followed by separate `INSERT` and `UPDATE` statements.
 *
 * Using triggers to execute all these statements avoids the overhead of passing
 * results between the storage and main threads, and wrapping each result row in
 * a `mozStorageRow` object.
 *
 * @param {Sqlite.OpenedConnection} db
 *        The mirror database connection.
 */
async function initializeTempMirrorEntities(db) {
  // Columns in `items` that correspond to annos stored in `moz_items_annos`.
  // We use this table to build SQL fragments for the `insertNewLocalItems` and
  // `updateExistingLocalItems` triggers below.
  const syncedAnnoTriggers = [{
    annoName: PlacesSyncUtils.bookmarks.DESCRIPTION_ANNO,
    columnName: "newDescription",
    type: PlacesUtils.annotations.TYPE_STRING,
  }, {
    annoName: PlacesSyncUtils.bookmarks.SIDEBAR_ANNO,
    columnName: "newLoadInSidebar",
    type: PlacesUtils.annotations.TYPE_INT32,
  }, {
    annoName: PlacesSyncUtils.bookmarks.SMART_BOOKMARKS_ANNO,
    columnName: "newSmartBookmarkName",
    type: PlacesUtils.annotations.TYPE_STRING,
  }, {
    annoName: PlacesUtils.LMANNO_FEEDURI,
    columnName: "newFeedURL",
    type: PlacesUtils.annotations.TYPE_STRING,
  }, {
    annoName: PlacesUtils.LMANNO_SITEURI,
    columnName: "newSiteURL",
    type: PlacesUtils.annotations.TYPE_STRING,
  }];

  // Stores the value and structure states of all nodes in the merged tree.
  await db.execute(`CREATE TEMP TABLE mergeStates(
    localGuid TEXT NOT NULL,
    mergedGuid TEXT NOT NULL,
    parentGuid TEXT NOT NULL,
    level INTEGER NOT NULL,
    position INTEGER NOT NULL,
    valueState INTEGER NOT NULL,
    structureState INTEGER NOT NULL,
    PRIMARY KEY(localGuid, mergedGuid)
  ) WITHOUT ROWID`);

  // A view of the value states for all bookmarks in the mirror. We use triggers
  // on this view to update Places. Note that we can't just `REPLACE INTO
  // moz_bookmarks`, because `REPLACE` doesn't fire the `AFTER DELETE` triggers
  // that Places uses to maintain schema coherency.
  await db.execute(`
    CREATE TEMP VIEW itemsToMerge(localId, remoteId, hasRemoteValue, newLevel,
                                  oldGuid, newGuid, newType,
                                  newDateAddedMicroseconds, newTitle,
                                  oldPlaceId, newPlaceId, newKeyword,
                                  newDescription, newLoadInSidebar,
                                  newSmartBookmarkName, newFeedURL,
                                  newSiteURL) AS
    SELECT b.id, v.id, r.valueState = ${BookmarkMergeState.TYPE.REMOTE},
           r.level, r.localGuid, r.mergedGuid,
           (CASE WHEN v.kind IN (${[
                        SyncedBookmarksMirror.KIND.BOOKMARK,
                        SyncedBookmarksMirror.KIND.QUERY,
                      ].join(",")}) THEN ${PlacesUtils.bookmarks.TYPE_BOOKMARK}
                 WHEN v.kind IN (${[
                        SyncedBookmarksMirror.KIND.FOLDER,
                        SyncedBookmarksMirror.KIND.LIVEMARK,
                      ].join(",")}) THEN ${PlacesUtils.bookmarks.TYPE_FOLDER}
                 ELSE ${PlacesUtils.bookmarks.TYPE_SEPARATOR} END),
           /* Take the older creation date. "b.dateAdded" is in microseconds;
              "v.dateAdded" is in milliseconds. */
           (CASE WHEN b.dateAdded / 1000 < v.dateAdded THEN b.dateAdded
                 ELSE v.dateAdded * 1000 END),
           v.title, h.id, u.newPlaceId, v.keyword, v.description,
           v.loadInSidebar, v.smartBookmarkName, v.feedURL, v.siteURL
    FROM items v
    JOIN mergeStates r ON r.mergedGuid = v.guid
    LEFT JOIN moz_bookmarks b ON b.guid = r.localGuid
    LEFT JOIN moz_places h ON h.id = b.fk
    LEFT JOIN (
      SELECT h.id AS newPlaceId, u.id AS urlId
      FROM urls u
      JOIN moz_places h ON h.url_hash = u.hash AND
                           h.url = u.url
    ) u ON u.urlId = v.urlId
    WHERE r.mergedGuid <> '${PlacesUtils.bookmarks.rootGuid}'`);

  // Changes local GUIDs to remote GUIDs, drops local tombstones for revived