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.

Header

Mercurial (b6d82b1a6b02)

VCS Links

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
/* vim: set ts=2 sts=2 et sw=2: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <algorithm>

#include "Predictor.h"

#include "nsAppDirectoryServiceDefs.h"
#include "nsICacheStorage.h"
#include "nsICacheStorageService.h"
#include "nsICachingChannel.h"
#include "nsICancelable.h"
#include "nsIChannel.h"
#include "nsContentUtils.h"
#include "nsIDNSService.h"
#include "mozilla/dom/Document.h"
#include "nsIFile.h"
#include "nsIHttpChannel.h"
#include "nsIInputStream.h"
#include "nsIIOService.h"
#include "nsILoadContext.h"
#include "nsILoadContextInfo.h"
#include "nsILoadGroup.h"
#include "nsINetworkPredictorVerifier.h"
#include "nsIObserverService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsISpeculativeConnect.h"
#include "nsITimer.h"
#include "nsIURI.h"
#include "nsNetUtil.h"
#include "nsServiceManagerUtils.h"
#include "nsStreamUtils.h"
#include "nsString.h"
#include "nsThreadUtils.h"
#include "mozilla/Logging.h"

#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/Telemetry.h"

#include "mozilla/net/NeckoCommon.h"
#include "mozilla/net/NeckoParent.h"

#include "LoadContextInfo.h"
#include "mozilla/ipc/URIUtils.h"
#include "SerializedLoadContext.h"
#include "mozilla/net/NeckoChild.h"

#include "mozilla/dom/ContentParent.h"
#include "mozilla/ClearOnShutdown.h"

#include "CacheControlParser.h"
#include "ReferrerInfo.h"

using namespace mozilla;

namespace mozilla {
namespace net {

Predictor* Predictor::sSelf = nullptr;

static LazyLogModule gPredictorLog("NetworkPredictor");

#define PREDICTOR_LOG(args) \
  MOZ_LOG(gPredictorLog, mozilla::LogLevel::Debug, args)

#define RETURN_IF_FAILED(_rv) \
  do {                        \
    if (NS_FAILED(_rv)) {     \
      return;                 \
    }                         \
  } while (0)

#define NOW_IN_SECONDS() static_cast<uint32_t>(PR_Now() / PR_USEC_PER_SEC)

static const char PREDICTOR_CLEANED_UP_PREF[] = "network.predictor.cleaned-up";

// All these time values are in sec
static const uint32_t ONE_DAY = 86400U;
static const uint32_t ONE_WEEK = 7U * ONE_DAY;
static const uint32_t ONE_MONTH = 30U * ONE_DAY;
static const uint32_t ONE_YEAR = 365U * ONE_DAY;

static const uint32_t STARTUP_WINDOW = 5U * 60U;  // 5min

// Version of metadata entries we expect
static const uint32_t METADATA_VERSION = 1;

// Flags available in entries
// FLAG_PREFETCHABLE - we have determined that this item is eligible for
// prefetch
static const uint32_t FLAG_PREFETCHABLE = 1 << 0;

// We save 12 bits in the "flags" section of our metadata for actual flags, the
// rest are to keep track of a rolling count of which loads a resource has been
// used on to determine if we can prefetch that resource or not;
static const uint8_t kRollingLoadOffset = 12;
static const int32_t kMaxPrefetchRollingLoadCount = 20;
static const uint32_t kFlagsMask = ((1 << kRollingLoadOffset) - 1);

static bool sEsniEnabled = false;

// ID Extensions for cache entries
#define PREDICTOR_ORIGIN_EXTENSION "predictor-origin"

// Get the full origin (scheme, host, port) out of a URI (maybe should be part
// of nsIURI instead?)
static nsresult ExtractOrigin(nsIURI* uri, nsIURI** originUri) {
  nsAutoCString s;
  nsresult rv = nsContentUtils::GetASCIIOrigin(uri, s);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_NewURI(originUri, s);
}

// All URIs we get passed *must* be http or https if they're not null. This
// helps ensure that.
static bool IsNullOrHttp(nsIURI* uri) {
  if (!uri) {
    return true;
  }

  return uri->SchemeIs("http") || uri->SchemeIs("https");
}

// Listener for the speculative DNS requests we'll fire off, which just ignores
// the result (since we're just trying to warm the cache). This also exists to
// reduce round-trips to the main thread, by being something threadsafe the
// Predictor can use.

NS_IMPL_ISUPPORTS(Predictor::DNSListener, nsIDNSListener);

NS_IMETHODIMP
Predictor::DNSListener::OnLookupComplete(nsICancelable* request,
                                         nsIDNSRecord* rec, nsresult status) {
  return NS_OK;
}

NS_IMETHODIMP
Predictor::DNSListener::OnLookupByTypeComplete(nsICancelable* request,
                                               nsIDNSByTypeRecord* res,
                                               nsresult status) {
  return NS_OK;
}

// Class to proxy important information from the initial predictor call through
// the cache API and back into the internals of the predictor. We can't use the
// predictor itself, as it may have multiple actions in-flight, and each action
// has different parameters.
NS_IMPL_ISUPPORTS(Predictor::Action, nsICacheEntryOpenCallback);

Predictor::Action::Action(bool fullUri, bool predict, Predictor::Reason reason,
                          nsIURI* targetURI, nsIURI* sourceURI,
                          nsINetworkPredictorVerifier* verifier,
                          Predictor* predictor)
    : mFullUri(fullUri),
      mPredict(predict),
      mTargetURI(targetURI),
      mSourceURI(sourceURI),
      mVerifier(verifier),
      mStackCount(0),
      mPredictor(predictor) {
  mStartTime = TimeStamp::Now();
  if (mPredict) {
    mPredictReason = reason.mPredict;
  } else {
    mLearnReason = reason.mLearn;
  }
}

Predictor::Action::Action(bool fullUri, bool predict, Predictor::Reason reason,
                          nsIURI* targetURI, nsIURI* sourceURI,
                          nsINetworkPredictorVerifier* verifier,
                          Predictor* predictor, uint8_t stackCount)
    : mFullUri(fullUri),
      mPredict(predict),
      mTargetURI(targetURI),
      mSourceURI(sourceURI),
      mVerifier(verifier),
      mStackCount(stackCount),
      mPredictor(predictor) {
  mStartTime = TimeStamp::Now();
  if (mPredict) {
    mPredictReason = reason.mPredict;
  } else {
    mLearnReason = reason.mLearn;
  }
}

NS_IMETHODIMP
Predictor::Action::OnCacheEntryCheck(nsICacheEntry* entry,
                                     nsIApplicationCache* appCache,
                                     uint32_t* result) {
  *result = nsICacheEntryOpenCallback::ENTRY_WANTED;
  return NS_OK;
}

NS_IMETHODIMP
Predictor::Action::OnCacheEntryAvailable(nsICacheEntry* entry, bool isNew,
                                         nsIApplicationCache* appCache,
                                         nsresult result) {
  MOZ_ASSERT(NS_IsMainThread(), "Got cache entry off main thread!");

  nsAutoCString targetURI, sourceURI;
  mTargetURI->GetAsciiSpec(targetURI);
  if (mSourceURI) {
    mSourceURI->GetAsciiSpec(sourceURI);
  }
  PREDICTOR_LOG(
      ("OnCacheEntryAvailable %p called. entry=%p mFullUri=%d mPredict=%d "
       "mPredictReason=%d mLearnReason=%d mTargetURI=%s "
       "mSourceURI=%s mStackCount=%d isNew=%d result=0x%08" PRIx32,
       this, entry, mFullUri, mPredict, mPredictReason, mLearnReason,
       targetURI.get(), sourceURI.get(), mStackCount, isNew,
       static_cast<uint32_t>(result)));
  if (NS_FAILED(result)) {
    PREDICTOR_LOG(
        ("OnCacheEntryAvailable %p FAILED to get cache entry (0x%08" PRIX32
         "). Aborting.",
         this, static_cast<uint32_t>(result)));
    return NS_OK;
  }
  Telemetry::AccumulateTimeDelta(Telemetry::PREDICTOR_WAIT_TIME, mStartTime);
  if (mPredict) {
    bool predicted =
        mPredictor->PredictInternal(mPredictReason, entry, isNew, mFullUri,
                                    mTargetURI, mVerifier, mStackCount);
    Telemetry::AccumulateTimeDelta(Telemetry::PREDICTOR_PREDICT_WORK_TIME,
                                   mStartTime);
    if (predicted) {
      Telemetry::AccumulateTimeDelta(
          Telemetry::PREDICTOR_PREDICT_TIME_TO_ACTION, mStartTime);
    } else {
      Telemetry::AccumulateTimeDelta(
          Telemetry::PREDICTOR_PREDICT_TIME_TO_INACTION, mStartTime);
    }
  } else {
    mPredictor->LearnInternal(mLearnReason, entry, isNew, mFullUri, mTargetURI,
                              mSourceURI);
    Telemetry::AccumulateTimeDelta(Telemetry::PREDICTOR_LEARN_WORK_TIME,
                                   mStartTime);
  }

  return NS_OK;
}

NS_IMPL_ISUPPORTS(Predictor, nsINetworkPredictor, nsIObserver,
                  nsISpeculativeConnectionOverrider, nsIInterfaceRequestor,
                  nsICacheEntryMetaDataVisitor, nsINetworkPredictorVerifier)

Predictor::Predictor()
    : mInitialized(false),
      mCleanedUp(false),
      mStartupTime(0),
      mLastStartupTime(0),
      mStartupCount(1) {
  MOZ_ASSERT(!sSelf, "multiple Predictor instances!");
  sSelf = this;
}

Predictor::~Predictor() {
  if (mInitialized) Shutdown();

  sSelf = nullptr;
}

// Predictor::nsIObserver

nsresult Predictor::InstallObserver() {
  MOZ_ASSERT(NS_IsMainThread(), "Installing observer off main thread");

  nsresult rv = NS_OK;
  nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  if (!obs) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  rv = obs->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
  NS_ENSURE_SUCCESS(rv, rv);

  mCleanedUp = Preferences::GetBool(PREDICTOR_CLEANED_UP_PREF, false);

  if (!mCleanedUp) {
    NS_NewTimerWithObserver(getter_AddRefs(mCleanupTimer), this, 60 * 1000,
                            nsITimer::TYPE_ONE_SHOT);
  }

  return rv;
}

void Predictor::RemoveObserver() {
  MOZ_ASSERT(NS_IsMainThread(), "Removing observer off main thread");

  nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  if (obs) {
    obs->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
  }

  if (mCleanupTimer) {
    mCleanupTimer->Cancel();
    mCleanupTimer = nullptr;
  }
}

NS_IMETHODIMP
Predictor::Observe(nsISupports* subject, const char* topic,
                   const char16_t* data_unicode) {
  nsresult rv = NS_OK;
  MOZ_ASSERT(NS_IsMainThread(),
             "Predictor observing something off main thread!");

  if (!strcmp(NS_XPCOM_SHUTDOWN_OBSERVER_ID, topic)) {
    Shutdown();
  } else if (!strcmp("timer-callback", topic)) {
    MaybeCleanupOldDBFiles();
    mCleanupTimer = nullptr;
  }

  return rv;
}

// Predictor::nsISpeculativeConnectionOverrider

NS_IMETHODIMP
Predictor::GetIgnoreIdle(bool* ignoreIdle) {
  *ignoreIdle = true;
  return NS_OK;
}

NS_IMETHODIMP
Predictor::GetParallelSpeculativeConnectLimit(
    uint32_t* parallelSpeculativeConnectLimit) {
  *parallelSpeculativeConnectLimit = 6;
  return NS_OK;
}

NS_IMETHODIMP
Predictor::GetIsFromPredictor(bool* isFromPredictor) {
  *isFromPredictor = true;
  return NS_OK;
}

NS_IMETHODIMP
Predictor::GetAllow1918(bool* allow1918) {
  *allow1918 = false;
  return NS_OK;
}

// Predictor::nsIInterfaceRequestor

NS_IMETHODIMP
Predictor::GetInterface(const nsIID& iid, void** result) {
  return QueryInterface(iid, result);
}

// Predictor::nsICacheEntryMetaDataVisitor

#define SEEN_META_DATA "predictor::seen"
#define RESOURCE_META_DATA "predictor::resource-count"
#define META_DATA_PREFIX "predictor::"

static bool IsURIMetadataElement(const char* key) {
  return StringBeginsWith(nsDependentCString(key),
                          NS_LITERAL_CSTRING(META_DATA_PREFIX)) &&
         !NS_LITERAL_CSTRING(SEEN_META_DATA).Equals(key) &&
         !NS_LITERAL_CSTRING(RESOURCE_META_DATA).Equals(key);
}

nsresult Predictor::OnMetaDataElement(const char* asciiKey,
                                      const char* asciiValue) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!IsURIMetadataElement(asciiKey)) {
    // This isn't a bit of metadata we care about
    return NS_OK;
  }

  nsCString key, value;
  key.AssignASCII(asciiKey);
  value.AssignASCII(asciiValue);
  mKeysToOperateOn.AppendElement(key);
  mValuesToOperateOn.AppendElement(value);

  return NS_OK;
}

// Predictor::nsINetworkPredictor

nsresult Predictor::Init() {
  MOZ_DIAGNOSTIC_ASSERT(!IsNeckoChild());

  if (!NS_IsMainThread()) {
    MOZ_ASSERT(false, "Predictor::Init called off the main thread!");
    return NS_ERROR_UNEXPECTED;
  }

  nsresult rv = NS_OK;

  rv = InstallObserver();
  NS_ENSURE_SUCCESS(rv, rv);

  mLastStartupTime = mStartupTime = NOW_IN_SECONDS();

  if (!mDNSListener) {
    mDNSListener = new DNSListener();
  }

  mCacheStorageService =
      do_GetService("@mozilla.org/netwerk/cache-storage-service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  mSpeculativeService = do_GetService("@mozilla.org/network/io-service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = NS_NewURI(getter_AddRefs(mStartupURI), "predictor://startup");
  NS_ENSURE_SUCCESS(rv, rv);

  mDnsService = do_GetService("@mozilla.org/network/dns-service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  Preferences::AddBoolVarCache(&sEsniEnabled, "network.security.esni.enabled");

  mInitialized = true;

  return rv;
}

namespace {
class PredictorThreadShutdownRunner : public Runnable {
 public:
  PredictorThreadShutdownRunner(nsIThread* ioThread, bool success)
      : Runnable("net::PredictorThreadShutdownRunner"),
        mIOThread(ioThread),
        mSuccess(success) {}
  ~PredictorThreadShutdownRunner() = default;

  NS_IMETHOD Run() override {
    MOZ_ASSERT(NS_IsMainThread(), "Shutting down io thread off main thread!");
    if (mSuccess) {
      // This means the cleanup happened. Mark so we don't try in the
      // future.
      Preferences::SetBool(PREDICTOR_CLEANED_UP_PREF, true);
    }
    return mIOThread->AsyncShutdown();
  }

 private:
  nsCOMPtr<nsIThread> mIOThread;
  bool mSuccess;
};

class PredictorOldCleanupRunner : public Runnable {
 public:
  PredictorOldCleanupRunner(nsIThread* ioThread, nsIFile* dbFile)
      : Runnable("net::PredictorOldCleanupRunner"),
        mIOThread(ioThread),
        mDBFile(dbFile) {}

  ~PredictorOldCleanupRunner() = default;

  NS_IMETHOD Run() override {
    MOZ_ASSERT(!NS_IsMainThread(), "Cleaning up old files on main thread!");
    nsresult rv = CheckForAndDeleteOldDBFiles();
    RefPtr<PredictorThreadShutdownRunner> runner =
        new PredictorThreadShutdownRunner(mIOThread, NS_SUCCEEDED(rv));
    NS_DispatchToMainThread(runner);
    return NS_OK;
  }

 private:
  nsresult CheckForAndDeleteOldDBFiles() {
    nsCOMPtr<nsIFile> oldDBFile;
    nsresult rv = mDBFile->GetParent(getter_AddRefs(oldDBFile));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = oldDBFile->AppendNative(NS_LITERAL_CSTRING("seer.sqlite"));
    NS_ENSURE_SUCCESS(rv, rv);

    bool fileExists = false;
    rv = oldDBFile->Exists(&fileExists);
    NS_ENSURE_SUCCESS(rv, rv);

    if (fileExists) {
      rv = oldDBFile->Remove(false);
      NS_ENSURE_SUCCESS(rv, rv);
    }

    fileExists = false;
    rv = mDBFile->Exists(&fileExists);
    NS_ENSURE_SUCCESS(rv, rv);

    if (fileExists) {
      rv = mDBFile->Remove(false);
    }

    return rv;
  }

  nsCOMPtr<nsIThread> mIOThread;
  nsCOMPtr<nsIFile> mDBFile;
};

class PredictorLearnRunnable final : public Runnable {
 public:
  PredictorLearnRunnable(nsIURI* targetURI, nsIURI* sourceURI,
                         PredictorLearnReason reason,
                         const OriginAttributes& oa)
      : Runnable("PredictorLearnRunnable"),
        mTargetURI(targetURI),
        mSourceURI(sourceURI),
        mReason(reason),
        mOA(oa) {}

  ~PredictorLearnRunnable() = default;

  NS_IMETHOD Run() override {
    if (!gNeckoChild) {
      // This may have gone away between when this runnable was dispatched and
      // when it actually runs, so let's be safe here, even though we asserted
      // earlier.
      PREDICTOR_LOG(("predictor::learn (async) gNeckoChild went away"));
      return NS_OK;
    }

    ipc::URIParams serTargetURI;
    SerializeURI(mTargetURI, serTargetURI);

    Maybe<ipc::URIParams> serSourceURI;
    SerializeURI(mSourceURI, serSourceURI);

    PREDICTOR_LOG(("predictor::learn (async) forwarding to parent"));
    gNeckoChild->SendPredLearn(serTargetURI, serSourceURI, mReason, mOA);

    return NS_OK;
  }

 private:
  nsCOMPtr<nsIURI> mTargetURI;
  nsCOMPtr<nsIURI> mSourceURI;
  PredictorLearnReason mReason;
  const OriginAttributes mOA;
};

}  // namespace

void Predictor::MaybeCleanupOldDBFiles() {
  MOZ_ASSERT(NS_IsMainThread());

  if (!StaticPrefs::network_predictor_enabled() || mCleanedUp) {
    return;
  }

  mCleanedUp = true;

  // This is used for cleaning up junk left over from the old backend
  // built on top of sqlite, if necessary.
  nsCOMPtr<nsIFile> dbFile;
  nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
                                       getter_AddRefs(dbFile));
  RETURN_IF_FAILED(rv);
  rv = dbFile->AppendNative(NS_LITERAL_CSTRING("netpredictions.sqlite"));
  RETURN_IF_FAILED(rv);

  nsCOMPtr<nsIThread> ioThread;
  rv = NS_NewNamedThread("NetPredictClean", getter_AddRefs(ioThread));
  RETURN_IF_FAILED(rv);

  RefPtr<PredictorOldCleanupRunner> runner =
      new PredictorOldCleanupRunner(ioThread, dbFile);
  ioThread->Dispatch(runner, NS_DISPATCH_NORMAL);
}

void Predictor::Shutdown() {
  if (!NS_IsMainThread()) {
    MOZ_ASSERT(false, "Predictor::Shutdown called off the main thread!");
    return;
  }

  RemoveObserver();

  mInitialized = false;
}

nsresult Predictor::Create(nsISupports* aOuter, const nsIID& aIID,
                           void** aResult) {
  MOZ_ASSERT(NS_IsMainThread());

  nsresult rv;

  if (aOuter != nullptr) {
    return NS_ERROR_NO_AGGREGATION;
  }

  RefPtr<Predictor> svc = new Predictor();
  if (IsNeckoChild()) {
    NeckoChild::InitNeckoChild();

    // Child threads only need to be call into the public interface methods
    // so we don't bother with initialization
    return svc->QueryInterface(aIID, aResult);
  }

  rv = svc->Init();
  if (NS_FAILED(rv)) {
    PREDICTOR_LOG(("Failed to initialize predictor, predictor will be a noop"));
  }

  // We treat init failure the same as the service being disabled, since this
  // is all an optimization anyway. No need to freak people out. That's why we
  // gladly continue on QI'ing here.
  rv = svc->QueryInterface(aIID, aResult);

  return rv;
}

NS_IMETHODIMP
Predictor::Predict(nsIURI* targetURI, nsIURI* sourceURI,
                   PredictorPredictReason reason,
                   JS::HandleValue originAttributes,
                   nsINetworkPredictorVerifier* verifier, JSContext* aCx) {
  OriginAttributes attrs;

  if (!originAttributes.isObject() || !attrs.Init(aCx, originAttributes)) {
    return NS_ERROR_INVALID_ARG;
  }

  return PredictNative(targetURI, sourceURI, reason, attrs, verifier);
}

// Called from the main thread to initiate predictive actions
NS_IMETHODIMP
Predictor::PredictNative(nsIURI* targetURI, nsIURI* sourceURI,
                         PredictorPredictReason reason,
                         const OriginAttributes& originAttributes,
                         nsINetworkPredictorVerifier* verifier) {
  MOZ_ASSERT(NS_IsMainThread(),
             "Predictor interface methods must be called on the main thread");

  PREDICTOR_LOG(("Predictor::Predict"));

  if (IsNeckoChild()) {
    MOZ_DIAGNOSTIC_ASSERT(gNeckoChild);

    PREDICTOR_LOG(("    called on child process"));

    Maybe<ipc::URIParams> serTargetURI, serSourceURI;
    SerializeURI(targetURI, serTargetURI);
    SerializeURI(sourceURI, serSourceURI);

    // If two different threads are predicting concurently, this will be
    // overwritten. Thankfully, we only use this in tests, which will
    // overwrite mVerifier perhaps multiple times for each individual test;
    // however, within each test, the multiple predict calls should have the
    // same verifier.
    if (verifier) {
      PREDICTOR_LOG(("    was given a verifier"));
      mChildVerifier = verifier;
    }
    PREDICTOR_LOG(("    forwarding to parent process"));
    gNeckoChild->SendPredPredict(serTargetURI, serSourceURI, reason,
                                 originAttributes, verifier);
    return NS_OK;
  }

  PREDICTOR_LOG(("    called on parent process"));

  if (!mInitialized) {
    PREDICTOR_LOG(("    not initialized"));
    return NS_OK;
  }

  if (!StaticPrefs::network_predictor_enabled()) {
    PREDICTOR_LOG(("    not enabled"));
    return NS_OK;
  }

  if (originAttributes.mPrivateBrowsingId > 0) {
    // Don't want to do anything in PB mode
    PREDICTOR_LOG(("    in PB mode"));
    return NS_OK;
  }

  if (!IsNullOrHttp(targetURI) || !IsNullOrHttp(sourceURI)) {
    // Nothing we can do for non-HTTP[S] schemes
    PREDICTOR_LOG(("    got non-http[s] URI"));
    return NS_OK;
  }

  // Ensure we've been given the appropriate arguments for the kind of
  // prediction we're being asked to do
  nsCOMPtr<nsIURI> uriKey = targetURI;
  nsCOMPtr<nsIURI> originKey;
  switch (reason) {
    case nsINetworkPredictor::PREDICT_LINK:
      if (!targetURI || !sourceURI) {
        PREDICTOR_LOG(("    link invalid URI state"));
        return NS_ERROR_INVALID_ARG;
      }
      // Link hover is a special case where we can predict without hitting the
      // db, so let's go ahead and fire off that prediction here.
      PredictForLink(targetURI, sourceURI, originAttributes, verifier);
      return NS_OK;
    case nsINetworkPredictor::PREDICT_LOAD:
      if (!targetURI || sourceURI) {
        PREDICTOR_LOG(("    load invalid URI state"));
        return NS_ERROR_INVALID_ARG;
      }
      break;
    case nsINetworkPredictor::PREDICT_STARTUP:
      if (targetURI || sourceURI) {
        PREDICTOR_LOG(("    startup invalid URI state"));
        return NS_ERROR_INVALID_ARG;
      }
      uriKey = mStartupURI;
      originKey = mStartupURI;
      break;
    default:
      PREDICTOR_LOG(("    invalid reason"));
      return NS_ERROR_INVALID_ARG;
  }

  Predictor::Reason argReason;
  argReason.mPredict = reason;

  // First we open the regular cache entry, to ensure we don't gum up the works
  // waiting on the less-important predictor-only cache entry
  RefPtr<Predictor::Action> uriAction = new Predictor::Action(
      Predictor::Action::IS_FULL_URI, Predictor::Action::DO_PREDICT, argReason,
      targetURI, nullptr, verifier, this);
  nsAutoCString uriKeyStr;
  uriKey->GetAsciiSpec(uriKeyStr);
  PREDICTOR_LOG(("    Predict uri=%s reason=%d action=%p", uriKeyStr.get(),
                 reason, uriAction.get()));

  nsCOMPtr<nsICacheStorage> cacheDiskStorage;

  RefPtr<LoadContextInfo> lci = new LoadContextInfo(false, originAttributes);

  nsresult rv = mCacheStorageService->DiskCacheStorage(
      lci, false, getter_AddRefs(cacheDiskStorage));
  NS_ENSURE_SUCCESS(rv, rv);

  uint32_t openFlags =
      nsICacheStorage::OPEN_READONLY | nsICacheStorage::OPEN_SECRETLY |
      nsICacheStorage::OPEN_PRIORITY | nsICacheStorage::CHECK_MULTITHREADED;
  cacheDiskStorage->AsyncOpenURI(uriKey, EmptyCString(), openFlags, uriAction);

  // Now we do the origin-only (and therefore predictor-only) entry
  nsCOMPtr<nsIURI> targetOrigin;
  rv = ExtractOrigin(uriKey, getter_AddRefs(targetOrigin));
  NS_ENSURE_SUCCESS(rv, rv);
  if (!originKey) {
    originKey = targetOrigin;
  }

  RefPtr<Predictor::Action> originAction = new Predictor::Action(
      Predictor::Action::IS_ORIGIN, Predictor::Action::DO_PREDICT, argReason,
      targetOrigin, nullptr, verifier, this);
  nsAutoCString originKeyStr;
  originKey->GetAsciiSpec(originKeyStr);
  PREDICTOR_LOG(("    Predict origin=%s reason=%d action=%p",
                 originKeyStr.get(), reason, originAction.get()));
  openFlags = nsICacheStorage::OPEN_READONLY | nsICacheStorage::OPEN_SECRETLY |
              nsICacheStorage::CHECK_MULTITHREADED;
  cacheDiskStorage->AsyncOpenURI(originKey,
                                 NS_LITERAL_CSTRING(PREDICTOR_ORIGIN_EXTENSION),
                                 openFlags, originAction);

  PREDICTOR_LOG(("    predict returning"));
  return NS_OK;
}

bool Predictor::PredictInternal(PredictorPredictReason reason,
                                nsICacheEntry* entry, bool isNew, bool fullUri,
                                nsIURI* targetURI,
                                nsINetworkPredictorVerifier* verifier,
                                uint8_t stackCount) {
  MOZ_ASSERT(NS_IsMainThread());

  PREDICTOR_LOG(("Predictor::PredictInternal"));
  bool rv = false;

  nsCOMPtr<nsILoadContextInfo> lci;
  entry->GetLoadContextInfo(getter_AddRefs(lci));

  if (!lci) {
    return rv;
  }

  if (reason == nsINetworkPredictor::PREDICT_LOAD) {
    MaybeLearnForStartup(targetURI, fullUri, *lci->OriginAttributesPtr());
  }

  if (isNew) {
    // nothing else we can do here
    PREDICTOR_LOG(("    new entry"));
    return rv;
  }

  switch (reason) {
    case nsINetworkPredictor::PREDICT_LOAD:
      rv = PredictForPageload(entry, targetURI, stackCount, fullUri, verifier);
      break;
    case nsINetworkPredictor::PREDICT_STARTUP:
      rv = PredictForStartup(entry, fullUri, verifier);
      break;
    default:
      PREDICTOR_LOG(("    invalid reason"));
      MOZ_ASSERT(false, "Got unexpected value for prediction reason");
  }

  return rv;
}

void Predictor::PredictForLink(nsIURI* targetURI, nsIURI* sourceURI,
                               const OriginAttributes& originAttributes,
                               nsINetworkPredictorVerifier* verifier) {
  MOZ_ASSERT(NS_IsMainThread());

  PREDICTOR_LOG(("Predictor::PredictForLink"));
  if (!mSpeculativeService) {
    PREDICTOR_LOG(("    missing speculative service"));
    return;
  }

  if (!StaticPrefs::network_predictor_enable_hover_on_ssl()) {
    if (sourceURI->SchemeIs("https")) {
      // We don't want to predict from an HTTPS page, to avoid info leakage
      PREDICTOR_LOG(("    Not predicting for link hover - on an SSL page"));
      return;
    }
  }

  nsCOMPtr<nsIPrincipal> principal =
      BasePrincipal::CreateContentPrincipal(targetURI, originAttributes);

  mSpeculativeService->SpeculativeConnect(targetURI, principal, nullptr);
  if (verifier) {
    PREDICTOR_LOG(("    sending verification"));
    verifier->OnPredictPreconnect(targetURI);
  }
}

// This is the driver for prediction based on a new pageload.
static const uint8_t MAX_PAGELOAD_DEPTH = 10;
bool Predictor::PredictForPageload(nsICacheEntry* entry, nsIURI* targetURI,
                                   uint8_t stackCount, bool fullUri,
                                   nsINetworkPredictorVerifier* verifier) {
  MOZ_ASSERT(NS_IsMainThread());

  PREDICTOR_LOG(("Predictor::PredictForPageload"));

  if (stackCount > MAX_PAGELOAD_DEPTH) {
    PREDICTOR_LOG(("    exceeded recursion depth!"));
    return false;
  }

  uint32_t lastLoad;
  nsresult rv = entry->GetLastFetched(&lastLoad);
  NS_ENSURE_SUCCESS(rv, false);

  int32_t globalDegradation = CalculateGlobalDegradation(lastLoad);
  PREDICTOR_LOG(("    globalDegradation = %d", globalDegradation));

  int32_t loadCount;
  rv = entry->GetFetchCount(&loadCount);
  NS_ENSURE_SUCCESS(rv, false);

  nsCOMPtr<nsILoadContextInfo> lci;

  rv = entry->GetLoadContextInfo(getter_AddRefs(lci));
  NS_ENSURE_SUCCESS(rv, false);

  nsCOMPtr<nsIURI> redirectURI;
  if (WouldRedirect(entry, loadCount, lastLoad, globalDegradation,
                    getter_AddRefs(redirectURI))) {
    mPreconnects.AppendElement(redirectURI);
    Predictor::Reason reason;
    reason.mPredict = nsINetworkPredictor::PREDICT_LOAD;
    RefPtr<Predictor::Action> redirectAction = new Predictor::Action(
        Predictor::Action::IS_FULL_URI, Predictor::Action::DO_PREDICT, reason,
        redirectURI, nullptr, verifier, this, stackCount + 1);
    nsAutoCString redirectUriString;
    redirectURI->GetAsciiSpec(redirectUriString);

    nsCOMPtr<nsICacheStorage> cacheDiskStorage;

    rv = mCacheStorageService->DiskCacheStorage(
        lci, false, getter_AddRefs(cacheDiskStorage));
    NS_ENSURE_SUCCESS(rv, false);

    PREDICTOR_LOG(("    Predict redirect uri=%s action=%p",
                   redirectUriString.get(), redirectAction.get()));
    uint32_t openFlags =
        nsICacheStorage::OPEN_READONLY | nsICacheStorage::OPEN_SECRETLY |
        nsICacheStorage::OPEN_PRIORITY | nsICacheStorage::CHECK_MULTITHREADED;
    cacheDiskStorage->AsyncOpenURI(redirectURI, EmptyCString(), openFlags,
                                   redirectAction);
    return RunPredictions(nullptr, *lci->OriginAttributesPtr(), verifier);
  }

  CalculatePredictions(entry, targetURI, lastLoad, loadCount, globalDegradation,
                       fullUri);

  return RunPredictions(targetURI, *lci->OriginAttributesPtr(), verifier);
}

// This is the driver for predicting at browser startup time based on pages that
// have previously been loaded close to startup.
bool Predictor::PredictForStartup(nsICacheEntry* entry, bool fullUri,
                                  nsINetworkPredictorVerifier* verifier) {
  MOZ_ASSERT(NS_IsMainThread());

  PREDICTOR_LOG(("Predictor::PredictForStartup"));

  nsCOMPtr<nsILoadContextInfo> lci;

  nsresult rv = entry->GetLoadContextInfo(getter_AddRefs(lci));
  NS_ENSURE_SUCCESS(rv, false);

  int32_t globalDegradation = CalculateGlobalDegradation(mLastStartupTime);
  CalculatePredictions(entry, nullptr, mLastStartupTime, mStartupCount,
                       globalDegradation, fullUri);
  return RunPredictions(nullptr, *lci->OriginAttributesPtr(), verifier);
}

// This calculates how much to degrade our confidence in our data based on
// the last time this top-level resource was loaded. This "global degradation"
// applies to *all* subresources we have associated with the top-level
// resource. This will be in addition to any reduction in confidence we have
// associated with a particular subresource.
int32_t Predictor::CalculateGlobalDegradation(uint32_t lastLoad) {
  MOZ_ASSERT(NS_IsMainThread());

  int32_t globalDegradation;
  uint32_t delta = NOW_IN_SECONDS() - lastLoad;
  if (delta < ONE_DAY) {
    globalDegradation = StaticPrefs::network_predictor_page_degradation_day();
  } else if (delta < ONE_WEEK) {
    globalDegradation = StaticPrefs::network_predictor_page_degradation_week();
  } else if (delta < ONE_MONTH) {
    globalDegradation = StaticPrefs::network_predictor_page_degradation_month();
  } else if (delta < ONE_YEAR) {
    globalDegradation = StaticPrefs::network_predictor_page_degradation_year();
  } else {
    globalDegradation = StaticPrefs::network_predictor_page_degradation_max();
  }

  Telemetry::Accumulate(Telemetry::PREDICTOR_GLOBAL_DEGRADATION,
                        globalDegradation);
  return globalDegradation;
}

// This calculates our overall confidence that a particular subresource will be
// loaded as part of a top-level load.
// @param hitCount - the number of times we have loaded this subresource as part
//                   of this top-level load
// @param hitsPossible - the number of times we have performed this top-level
//                       load
// @param lastHit - the timestamp of the last time we loaded this subresource as
//                  part of this top-level load
// @param lastPossible - the timestamp of the last time we performed this
//                       top-level load
// @param globalDegradation - the degradation for this top-level load as
//                            determined by CalculateGlobalDegradation
int32_t Predictor::CalculateConfidence(uint32_t hitCount, uint32_t hitsPossible,
                                       uint32_t lastHit, uint32_t lastPossible,
                                       int32_t globalDegradation) {
  MOZ_ASSERT(NS_IsMainThread());

  Telemetry::AutoCounter<Telemetry::PREDICTOR_PREDICTIONS_CALCULATED>
      predictionsCalculated;
  ++predictionsCalculated;

  if (!hitsPossible) {
    return 0;
  }

  int32_t baseConfidence = (hitCount * 100) / hitsPossible;
  int32_t maxConfidence = 100;
  int32_t confidenceDegradation = 0;

  if (lastHit < lastPossible) {
    // We didn't load this subresource the last time this top-level load was
    // performed, so let's not bother preconnecting (at the very least).
    maxConfidence =
        StaticPrefs::network_predictor_preconnect_min_confidence() - 1;

    // Now calculate how much we want to degrade our confidence based on how
    // long it's been between the last time we did this top-level load and the
    // last time this top-level load included this subresource.
    PRTime delta = lastPossible - lastHit;
    if (delta == 0) {
      confidenceDegradation = 0;
    } else if (delta < ONE_DAY) {
      confidenceDegradation =
          StaticPrefs::network_predictor_subresource_degradation_day();
    } else if (delta < ONE_WEEK) {
      confidenceDegradation =
          StaticPrefs::network_predictor_subresource_degradation_week();
    } else if (delta < ONE_MONTH) {
      confidenceDegradation =
          StaticPrefs::network_predictor_subresource_degradation_month();
    } else if (delta < ONE_YEAR) {
      confidenceDegradation =
          StaticPrefs::network_predictor_subresource_degradation_year();
    } else {
      confidenceDegradation =
          StaticPrefs::network_predictor_subresource_degradation_max();
      maxConfidence = 0;
    }
  }

  // Calculate our confidence and clamp it to between 0 and maxConfidence
  // (<= 100)
  int32_t confidence =
      baseConfidence - confidenceDegradation - globalDegradation;
  confidence = std::max(confidence, 0);
  confidence = std::min(confidence, maxConfidence);

  Telemetry::Accumulate(Telemetry::PREDICTOR_BASE_CONFIDENCE, baseConfidence);
  Telemetry::Accumulate(Telemetry::PREDICTOR_SUBRESOURCE_DEGRADATION,
                        confidenceDegradation);
  Telemetry::Accumulate(Telemetry::PREDICTOR_CONFIDENCE, confidence);
  return confidence;
}

static void MakeMetadataEntry(const uint32_t hitCount, const uint32_t lastHit,
                              const uint32_t flags, nsCString& newValue) {
  newValue.Truncate();
  newValue.AppendInt(METADATA_VERSION);
  newValue.Append(',');
  newValue.AppendInt(hitCount);
  newValue.Append(',');
  newValue.AppendInt(lastHit);
  newValue.Append(',');
  newValue.AppendInt(flags);
}

// On every page load, the rolling window gets shifted by one bit, leaving the
// lowest bit at 0, to indicate that the subresource in question has not been
// seen on the most recent page load. If, at some point later during the page
// load, the subresource is seen again, we will then set the lowest bit to 1.
// This is how we keep track of how many of the last n pageloads (for n <= 20) a
// particular subresource has been seen. The rolling window is kept in the upper
// 20 bits of the flags element of the metadata. This saves 12 bits for regular
// old flags.
void Predictor::UpdateRollingLoadCount(nsICacheEntry* entry,
                                       const uint32_t flags, const char* key,
                                       const uint32_t hitCount,
                                       const uint32_t lastHit) {
  // Extract just the rolling load count from the flags, shift it to clear the
  // lowest bit, and put the new value with the existing flags.
  uint32_t rollingLoadCount = flags & ~kFlagsMask;
  rollingLoadCount <<= 1;
  uint32_t newFlags = (flags & kFlagsMask) | rollingLoadCount;

  // Finally, update the metadata on the cache entry.
  nsAutoCString newValue;
  MakeMetadataEntry(hitCount, lastHit, newFlags, newValue);
  entry->SetMetaDataElement(key, newValue.BeginReading());
}

uint32_t Predictor::ClampedPrefetchRollingLoadCount() {
  int32_t n = StaticPrefs::network_predictor_prefetch_rolling_load_count();
  if (n < 0) {
    return 0;
  }
  if (n > kMaxPrefetchRollingLoadCount) {
    return kMaxPrefetchRollingLoadCount;
  }
  return n;
}

void Predictor::CalculatePredictions(nsICacheEntry* entry, nsIURI* referrer,
                                     uint32_t lastLoad, uint32_t loadCount,
                                     int32_t globalDegradation, bool fullUri) {
  MOZ_ASSERT(NS_IsMainThread());

  // Since the visitor gets called under a cache lock, all we do there is get
  // copies of the keys/values we care about, and then do the real work here
  entry->VisitMetaData(this);
  nsTArray<nsCString> keysToOperateOn, valuesToOperateOn;
  keysToOperateOn.SwapElements(mKeysToOperateOn);
  valuesToOperateOn.SwapElements(mValuesToOperateOn);

  MOZ_ASSERT(keysToOperateOn.Length() == valuesToOperateOn.Length());
  for (size_t i = 0; i < keysToOperateOn.Length(); ++i) {
    const char* key = keysToOperateOn[i].BeginReading();
    const char* value = valuesToOperateOn[i].BeginReading();

    nsCString uri;
    uint32_t hitCount, lastHit, flags;
    if (!ParseMetaDataEntry(key, value, uri, hitCount, lastHit, flags)) {
      // This failed, get rid of it so we don't waste space
      entry->SetMetaDataElement(key, nullptr);
      continue;
    }

    int32_t confidence = CalculateConfidence(hitCount, loadCount, lastHit,
                                             lastLoad, globalDegradation);
    if (fullUri) {
      UpdateRollingLoadCount(entry, flags, key, hitCount, lastHit);
    }
    PREDICTOR_LOG(("CalculatePredictions key=%s value=%s confidence=%d", key,
                   value, confidence));
    PrefetchIgnoreReason reason = PREFETCH_OK;
    if (!fullUri) {
      // Not full URI - don't prefetch! No sense in it!
      PREDICTOR_LOG(("    forcing non-cacheability - not full URI"));
      if (flags & FLAG_PREFETCHABLE) {
        // This only applies if we had somehow otherwise marked this
        // prefetchable.
        reason = NOT_FULL_URI;
      }
      flags &= ~FLAG_PREFETCHABLE;
    } else if (!referrer) {
      // No referrer means we can't prefetch, so pretend it's non-cacheable,
      // no matter what.
      PREDICTOR_LOG(("    forcing non-cacheability - no referrer"));
      if (flags & FLAG_PREFETCHABLE) {
        // This only applies if we had somehow otherwise marked this
        // prefetchable.
        reason = NO_REFERRER;
      }
      flags &= ~FLAG_PREFETCHABLE;
    } else {
      uint32_t expectedRollingLoadCount =
          (1 << ClampedPrefetchRollingLoadCount()) - 1;
      expectedRollingLoadCount <<= kRollingLoadOffset;
      if ((flags & expectedRollingLoadCount) != expectedRollingLoadCount) {
        PREDICTOR_LOG(("    forcing non-cacheability - missed a load"));
        if (flags & FLAG_PREFETCHABLE) {
          // This only applies if we had somehow otherwise marked this
          // prefetchable.
          reason = MISSED_A_LOAD;
        }
        flags &= ~FLAG_PREFETCHABLE;
      }
    }

    PREDICTOR_LOG(("    setting up prediction"));
    SetupPrediction(confidence, flags, uri, reason);
  }
}

// (Maybe) adds a predictive action to the prediction runner, based on our
// calculated confidence for the subresource in question.
void Predictor::SetupPrediction(int32_t confidence, uint32_t flags,
                                const nsCString& uri,
                                PrefetchIgnoreReason earlyReason) {
  MOZ_ASSERT(NS_IsMainThread());

  nsresult rv = NS_OK;
  PREDICTOR_LOG(
      ("SetupPrediction enable-prefetch=%d prefetch-min-confidence=%d "
       "preconnect-min-confidence=%d preresolve-min-confidence=%d "
       "flags=%d confidence=%d uri=%s",
       StaticPrefs::network_predictor_enable_prefetch(),
       StaticPrefs::network_predictor_prefetch_min_confidence(),
       StaticPrefs::network_predictor_preconnect_min_confidence(),
       StaticPrefs::network_predictor_preresolve_min_confidence(), flags,
       confidence, uri.get()));

  bool prefetchOk = !!(flags & FLAG_PREFETCHABLE);
  PrefetchIgnoreReason reason = earlyReason;
  if (prefetchOk && !StaticPrefs::network_predictor_enable_prefetch()) {
    prefetchOk = false;
    reason = PREFETCH_DISABLED;
  } else if (prefetchOk && !ClampedPrefetchRollingLoadCount() &&
             confidence <
                 StaticPrefs::network_predictor_prefetch_min_confidence()) {
    prefetchOk = false;
    if (!ClampedPrefetchRollingLoadCount()) {
      reason = PREFETCH_DISABLED_VIA_COUNT;
    } else {
      reason = CONFIDENCE_TOO_LOW;
    }
  }

  // prefetchOk == false and reason == PREFETCH_OK indicates that the reason
  // we aren't prefetching this item is because it was marked un-prefetchable in
  // our metadata. We already have separate telemetry on that decision, so we
  // aren't going to accumulate more here. Right now we only care about why
  // something we had marked prefetchable isn't being prefetched.
  if (!prefetchOk && reason != PREFETCH_OK) {
    Telemetry::Accumulate(Telemetry::PREDICTOR_PREFETCH_IGNORE_REASON, reason);
  }

  if (prefetchOk) {
    nsCOMPtr<nsIURI> prefetchURI;
    rv = NS_NewURI(getter_AddRefs(prefetchURI), uri);
    if (NS_SUCCEEDED(rv)) {
      mPrefetches.AppendElement(prefetchURI);
    }
  } else if (confidence >=
             StaticPrefs::network_predictor_preconnect_min_confidence()) {
    nsCOMPtr<nsIURI> preconnectURI;
    rv = NS_NewURI(getter_AddRefs(preconnectURI), uri);
    if (NS_SUCCEEDED(rv)) {
      mPreconnects.AppendElement(preconnectURI);
    }
  } else if (confidence >=
             StaticPrefs::network_predictor_preresolve_min_confidence()) {
    nsCOMPtr<nsIURI> preresolveURI;
    rv = NS_NewURI(getter_AddRefs(preresolveURI), uri);
    if (NS_SUCCEEDED(rv)) {
      mPreresolves.AppendElement(preresolveURI);
    }
  }

  if (NS_FAILED(rv)) {
    PREDICTOR_LOG(
        ("    NS_NewURI returned 0x%" PRIx32, static_cast<uint32_t>(rv)));
  }
}

nsresult Predictor::Prefetch(nsIURI* uri, nsIURI* referrer,
                             const OriginAttributes& originAttributes,
                             nsINetworkPredictorVerifier* verifier) {
  nsAutoCString strUri, strReferrer;
  uri->GetAsciiSpec(strUri);
  referrer->GetAsciiSpec(strReferrer);
  PREDICTOR_LOG(("Predictor::Prefetch uri=%s referrer=%s verifier=%p",
                 strUri.get(), strReferrer.get(), verifier));
  nsCOMPtr<nsIChannel> channel;
  nsresult rv = NS_NewChannel(
      getter_AddRefs(channel), uri, nsContentUtils::GetSystemPrincipal(),
      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
      nsIContentPolicy::TYPE_OTHER, nullptr, /* nsICookieSettings */
      nullptr,                               /* aPerformanceStorage */
      nullptr,                               /* aLoadGroup */
      nullptr,                               /* aCallbacks */
      nsIRequest::LOAD_BACKGROUND);

  if (NS_FAILED(rv)) {
    PREDICTOR_LOG(
        ("    NS_NewChannel failed rv=0x%" PRIX32, static_cast<uint32_t>(rv)));
    return rv;
  }

  nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
  rv = loadInfo->SetOriginAttributes(originAttributes);

  if (NS_FAILED(rv)) {
    PREDICTOR_LOG(
        ("    Set originAttributes into loadInfo failed rv=0x%" PRIX32,
         static_cast<uint32_t>(rv)));
    return rv;
  }

  nsCOMPtr<nsIHttpChannel> httpChannel;
  httpChannel = do_QueryInterface(channel);
  if (!httpChannel) {
    PREDICTOR_LOG(("    Could not get HTTP Channel from new channel!"));
    return NS_ERROR_UNEXPECTED;
  }

  nsCOMPtr<nsIReferrerInfo> referrerInfo = new ReferrerInfo(referrer);
  rv = httpChannel->SetReferrerInfoWithoutClone(referrerInfo);
  NS_ENSURE_SUCCESS(rv, rv);
  // XXX - set a header here to indicate this is a prefetch?

  nsCOMPtr<nsIStreamListener> listener =
      new PrefetchListener(verifier, uri, this);
  PREDICTOR_LOG(("    calling AsyncOpen listener=%p channel=%p", listener.get(),
                 channel.get()));
  rv = channel->AsyncOpen(listener);
  if (NS_FAILED(rv)) {
    PREDICTOR_LOG(
        ("    AsyncOpen failed rv=0x%" PRIX32, static_cast<uint32_t>(rv)));
  }

  return rv;
}

// Runs predictions that have been set up.
bool Predictor::RunPredictions(nsIURI* referrer,
                               const OriginAttributes& originAttributes,
                               nsINetworkPredictorVerifier* verifier) {
  MOZ_ASSERT(NS_IsMainThread(), "Running prediction off main thread");

  PREDICTOR_LOG(("Predictor::RunPredictions"));

  bool predicted = false;
  uint32_t len, i;

  nsTArray<nsCOMPtr<nsIURI>> prefetches, preconnects, preresolves;
  prefetches.SwapElements(mPrefetches);
  preconnects.SwapElements(mPreconnects);
  preresolves.SwapElements(mPreresolves);

  Telemetry::AutoCounter<Telemetry::PREDICTOR_TOTAL_PREDICTIONS>
      totalPredictions;
  Telemetry::AutoCounter<Telemetry::PREDICTOR_TOTAL_PREFETCHES> totalPrefetches;
  Telemetry::AutoCounter<Telemetry::PREDICTOR_TOTAL_PRECONNECTS>
      totalPreconnects;
  Telemetry::AutoCounter<Telemetry::PREDICTOR_TOTAL_PRERESOLVES>
      totalPreresolves;

  len = prefetches.Length();
  for (i = 0; i < len; ++i) {
    PREDICTOR_LOG(("    doing prefetch"));
    nsCOMPtr<nsIURI> uri = prefetches[i];
    if (NS_SUCCEEDED(Prefetch(uri, referrer, originAttributes, verifier))) {
      ++totalPredictions;
      ++totalPrefetches;
      predicted = true;
    }
  }

  len = preconnects.Length();
  for (i = 0; i < len; ++i) {
    PREDICTOR_LOG(("    doing preconnect"));
    nsCOMPtr<nsIURI> uri = preconnects[i];
    ++totalPredictions;
    ++totalPreconnects;
    nsCOMPtr<nsIPrincipal> principal =
        BasePrincipal::CreateContentPrincipal(uri, originAttributes);
    mSpeculativeService->SpeculativeConnect(uri, principal, this);
    predicted = true;
    if (verifier) {
      PREDICTOR_LOG(("    sending preconnect verification"));
      verifier->OnPredictPreconnect(uri);
    }
  }

  len = preresolves.Length();
  for (i = 0; i < len; ++i) {
    nsCOMPtr<nsIURI> uri = preresolves[i];
    ++totalPredictions;
    ++totalPreresolves;
    nsAutoCString hostname;
    uri->GetAsciiHost(hostname);
    PREDICTOR_LOG(("    doing preresolve %s", hostname.get()));
    nsCOMPtr<nsICancelable> tmpCancelable;
    mDnsService->AsyncResolveNative(hostname,
                                    (nsIDNSService::RESOLVE_PRIORITY_MEDIUM |
                                     nsIDNSService::RESOLVE_SPECULATE),
                                    mDNSListener, nullptr, originAttributes,
                                    getter_AddRefs(tmpCancelable));

    // Fetch esni keys if needed.
    if (sEsniEnabled && uri->SchemeIs("https")) {
      nsAutoCString esniHost;
      esniHost.Append("_esni.");
      esniHost.Append(hostname);
      mDnsService->AsyncResolveByTypeNative(
          esniHost, nsIDNSService::RESOLVE_TYPE_TXT,
          (nsIDNSService::RESOLVE_PRIORITY_MEDIUM |
           nsIDNSService::RESOLVE_SPECULATE),
          mDNSListener, nullptr, originAttributes,
          getter_AddRefs(tmpCancelable));
    }

    predicted = true;
    if (verifier) {
      PREDICTOR_LOG(("    sending preresolve verification"));
      verifier->OnPredictDNS(uri);
    }
  }

  return predicted;
}

// Find out if a top-level page is likely to redirect.
bool Predictor::WouldRedirect(nsICacheEntry* entry, uint32_t loadCount,
                              uint32_t lastLoad, int32_t globalDegradation,
                              nsIURI** redirectURI) {
  // TODO - not doing redirects for first go around
  MOZ_ASSERT(NS_IsMainThread());

  return false;
}

NS_IMETHODIMP
Predictor::Learn(nsIURI* targetURI, nsIURI* sourceURI,
                 PredictorLearnReason reason, JS::HandleValue originAttributes,
                 JSContext* aCx) {
  OriginAttributes attrs;

  if (!originAttributes.isObject() || !attrs.Init(aCx, originAttributes)) {
    return NS_ERROR_INVALID_ARG;
  }

  return LearnNative(targetURI, sourceURI, reason, attrs);
}

// Called from the main thread to update the database
NS_IMETHODIMP
Predictor::LearnNative(nsIURI* targetURI, nsIURI* sourceURI,
                       PredictorLearnReason reason,
                       const OriginAttributes& originAttributes) {
  MOZ_ASSERT(NS_IsMainThread(),
             "Predictor interface methods must be called on the main thread");

  PREDICTOR_LOG(("Predictor::Learn"));

  if (IsNeckoChild()) {
    MOZ_DIAGNOSTIC_ASSERT(gNeckoChild);

    PREDICTOR_LOG(("    called on child process"));

    RefPtr<PredictorLearnRunnable> runnable = new PredictorLearnRunnable(
        targetURI, sourceURI, reason, originAttributes);
    SystemGroup::Dispatch(TaskCategory::Other, runnable.forget());

    return NS_OK;
  }

  PREDICTOR_LOG(("    called on parent process"));

  if (!mInitialized) {
    PREDICTOR_LOG(("    not initialized"));
    return NS_OK;
  }

  if (!StaticPrefs::network_predictor_enabled()) {
    PREDICTOR_LOG(("    not enabled"));
    return NS_OK;
  }

  if (originAttributes.mPrivateBrowsingId > 0) {
    // Don't want to do anything in PB mode
    PREDICTOR_LOG(("    in PB mode"));
    return NS_OK;
  }

  if (!IsNullOrHttp(targetURI) || !IsNullOrHttp(sourceURI)) {
    PREDICTOR_LOG(("    got non-HTTP[S] URI"));
    return NS_ERROR_INVALID_ARG;
  }

  nsCOMPtr<nsIURI> targetOrigin;
  nsCOMPtr<nsIURI> sourceOrigin;
  nsCOMPtr<nsIURI> uriKey;
  nsCOMPtr<nsIURI> originKey;
  nsresult rv;

  switch (reason) {
    case nsINetworkPredictor::LEARN_LOAD_TOPLEVEL:
      if (!targetURI || sourceURI) {
        PREDICTOR_LOG(("    load toplevel invalid URI state"));
        return NS_ERROR_INVALID_ARG;
      }
      rv = ExtractOrigin(targetURI, getter_AddRefs(targetOrigin));
      NS_ENSURE_SUCCESS(rv, rv);
      uriKey = targetURI;
      originKey = targetOrigin;
      break;
    case nsINetworkPredictor::LEARN_STARTUP:
      if (!targetURI || sourceURI) {
        PREDICTOR_LOG(("    startup invalid URI state"));
        return NS_ERROR_INVALID_ARG;
      }
      rv = ExtractOrigin(targetURI, getter_AddRefs(targetOrigin));
      NS_ENSURE_SUCCESS(rv, rv);
      uriKey = mStartupURI;
      originKey = mStartupURI;
      break;
    case nsINetworkPredictor::LEARN_LOAD_REDIRECT:
    case nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE:
      if (!targetURI || !sourceURI) {
        PREDICTOR_LOG(("    redirect/subresource invalid URI state"));
        return NS_ERROR_INVALID_ARG;
      }
      rv = ExtractOrigin(targetURI, getter_AddRefs(targetOrigin));
      NS_ENSURE_SUCCESS(rv, rv);
      rv = ExtractOrigin(sourceURI, getter_AddRefs(sourceOrigin));
      NS_ENSURE_SUCCESS(rv, rv);
      uriKey = sourceURI;
      originKey = sourceOrigin;
      break;
    default:
      PREDICTOR_LOG(("    invalid reason"));
      return NS_ERROR_INVALID_ARG;
  }

  Telemetry::AutoCounter<Telemetry::PREDICTOR_LEARN_ATTEMPTS> learnAttempts;
  ++learnAttempts;

  Predictor::Reason argReason;
  argReason.mLearn = reason;

  // We always open the full uri (general cache) entry first, so we don't gum up
  // the works waiting on predictor-only entries to open
  RefPtr<Predictor::Action> uriAction = new Predictor::Action(
      Predictor::Action::IS_FULL_URI, Predictor::Action::DO_LEARN, argReason,
      targetURI, sourceURI, nullptr, this);
  nsAutoCString uriKeyStr, targetUriStr, sourceUriStr;
  uriKey->GetAsciiSpec(uriKeyStr);
  targetURI->GetAsciiSpec(targetUriStr);
  if (sourceURI) {
    sourceURI->GetAsciiSpec(sourceUriStr);
  }
  PREDICTOR_LOG(
      ("    Learn uriKey=%s targetURI=%s sourceURI=%s reason=%d "
       "action=%p",
       uriKeyStr.get(), targetUriStr.get(), sourceUriStr.get(), reason,
       uriAction.get()));

  nsCOMPtr<nsICacheStorage> cacheDiskStorage;

  RefPtr<LoadContextInfo> lci = new LoadContextInfo(false, originAttributes);

  rv = mCacheStorageService->DiskCacheStorage(lci, false,
                                              getter_AddRefs(cacheDiskStorage));
  NS_ENSURE_SUCCESS(rv, rv);

  // For learning full URI things, we *always* open readonly and secretly, as we
  // rely on actual pageloads to update the entry's metadata for us.
  uint32_t uriOpenFlags = nsICacheStorage::OPEN_READONLY |
                          nsICacheStorage::OPEN_SECRETLY |
                          nsICacheStorage::CHECK_MULTITHREADED;
  if (reason == nsINetworkPredictor::LEARN_LOAD_TOPLEVEL) {
    // Learning for toplevel we want to open the full uri entry priority, since
    // it's likely this entry will be used soon anyway, and we want this to be
    // opened ASAP.
    uriOpenFlags |= nsICacheStorage::OPEN_PRIORITY;
  }
  cacheDiskStorage->AsyncOpenURI(uriKey, EmptyCString(), uriOpenFlags,
                                 uriAction);

  // Now we open the origin-only (and therefore predictor-only) entry
  RefPtr<Predictor::Action> originAction = new Predictor::Action(
      Predictor::Action::IS_ORIGIN, Predictor::Action::DO_LEARN, argReason,
      targetOrigin, sourceOrigin, nullptr, this);
  nsAutoCString originKeyStr, targetOriginStr, sourceOriginStr;
  originKey->GetAsciiSpec(originKeyStr);
  targetOrigin->GetAsciiSpec(targetOriginStr);
  if (sourceOrigin) {
    sourceOrigin->GetAsciiSpec(sourceOriginStr);
  }
  PREDICTOR_LOG(
      ("    Learn originKey=%s targetOrigin=%s sourceOrigin=%s reason=%d "
       "action=%p",
       originKeyStr.get(), targetOriginStr.get(), sourceOriginStr.get(), reason,
       originAction.get()));
  uint32_t originOpenFlags;
  if (reason == nsINetworkPredictor::LEARN_LOAD_TOPLEVEL) {
    // This is the only case when we want to update the 'last used' metadata on
    // the cache entry we're getting. This only applies to predictor-specific
    // entries.
    originOpenFlags =
        nsICacheStorage::OPEN_NORMALLY | nsICacheStorage::CHECK_MULTITHREADED;
  } else {
    originOpenFlags = nsICacheStorage::OPEN_READONLY |
                      nsICacheStorage::OPEN_SECRETLY |
                      nsICacheStorage::CHECK_MULTITHREADED;
  }
  cacheDiskStorage->AsyncOpenURI(originKey,
                                 NS_LITERAL_CSTRING(PREDICTOR_ORIGIN_EXTENSION),
                                 originOpenFlags, originAction);

  PREDICTOR_LOG(("Predictor::Learn returning"));
  return NS_OK;
}

void Predictor::LearnInternal(PredictorLearnReason reason, nsICacheEntry* entry,
                              bool isNew, bool fullUri, nsIURI* targetURI,
                              nsIURI* sourceURI) {
  MOZ_ASSERT(NS_IsMainThread());

  PREDICTOR_LOG(("Predictor::LearnInternal"));

  nsCString junk;
  if (!fullUri && reason == nsINetworkPredictor::LEARN_LOAD_TOPLEVEL &&
      NS_FAILED(
          entry->GetMetaDataElement(SEEN_META_DATA, getter_Copies(junk)))) {
    // This is an origin-only entry that we haven't seen before. Let's mark it
    // as seen.
    PREDICTOR_LOG(("    marking new origin entry as seen"));
    nsresult rv = entry->SetMetaDataElement(SEEN_META_DATA, "1");
    if (NS_FAILED(rv)) {
      PREDICTOR_LOG(("    failed to mark origin entry seen"));
      return;
    }

    // Need to ensure someone else can get to the entry if necessary
    entry->MetaDataReady();
    return;
  }

  switch (reason) {
    case nsINetworkPredictor::LEARN_LOAD_TOPLEVEL:
      // This case only exists to be used during tests - code outside the
      // predictor tests should NEVER call Learn with LEARN_LOAD_TOPLEVEL.
      // The predictor xpcshell test needs this branch, however, because we
      // have no real page loads in xpcshell, and this is how we fake it up
      // so that all the work that normally happens behind the scenes in a
      // page load can be done for testing purposes.
      if (fullUri && StaticPrefs::network_predictor_doing_tests()) {
        PREDICTOR_LOG(
            ("    WARNING - updating rolling load count. "
             "If you see this outside tests, you did it wrong"));

        // Since the visitor gets called under a cache lock, all we do there is
        // get copies of the keys/values we care about, and then do the real
        // work here
        entry->VisitMetaData(this);
        nsTArray<nsCString> keysToOperateOn, valuesToOperateOn;
        keysToOperateOn.SwapElements(mKeysToOperateOn);
        valuesToOperateOn.SwapElements(mValuesToOperateOn);

        MOZ_ASSERT(keysToOperateOn.Length() == valuesToOperateOn.Length());
        for (size_t i = 0; i < keysToOperateOn.Length(); ++i) {
          const char* key = keysToOperateOn[i].BeginReading();
          const char* value = valuesToOperateOn[i].BeginReading();

          nsCString uri;
          uint32_t hitCount, lastHit, flags;
          if (!ParseMetaDataEntry(key, value, uri, hitCount, lastHit, flags)) {
            // This failed, get rid of it so we don't waste space
            entry->SetMetaDataElement(key, nullptr);
            continue;
          }
          UpdateRollingLoadCount(entry, flags, key, hitCount, lastHit);
        }
      } else {
        PREDICTOR_LOG(("    nothing to do for toplevel"));
      }
      break;
    case nsINetworkPredictor::LEARN_LOAD_REDIRECT:
      if (fullUri) {
        LearnForRedirect(entry, targetURI);
      }
      break;
    case nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE:
      LearnForSubresource(entry, targetURI);
      break;
    case nsINetworkPredictor::LEARN_STARTUP:
      LearnForStartup(entry, targetURI);
      break;
    default:
      PREDICTOR_LOG(("    unexpected reason value"));
      MOZ_ASSERT(false, "Got unexpected value for learn reason!");
  }
}

NS_IMPL_ISUPPORTS(Predictor::SpaceCleaner, nsICacheEntryMetaDataVisitor)

NS_IMETHODIMP
Predictor::SpaceCleaner::OnMetaDataElement(const char* key, const char* value) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!IsURIMetadataElement(key)) {
    // This isn't a bit of metadata we care about
    return NS_OK;
  }

  nsCString uri;
  uint32_t hitCount, lastHit, flags;
  bool ok =
      mPredictor->ParseMetaDataEntry(key, value, uri, hitCount, lastHit, flags);

  if (!ok) {
    // Couldn't parse this one, just get rid of it
    nsCString nsKey;
    nsKey.AssignASCII(key);
    mLongKeysToDelete.AppendElement(nsKey);
    return NS_OK;
  }

  uint32_t uriLength = uri.Length();
  if (uriLength > StaticPrefs::network_predictor_max_uri_length()) {
    // Default to getting rid of URIs that are too long and were put in before
    // we had our limit on URI length, in order to free up some space.
    nsCString nsKey;
    nsKey.AssignASCII(key);
    mLongKeysToDelete.AppendElement(nsKey);
    return NS_OK;
  }

  if (!mLRUKeyToDelete || lastHit < mLRUStamp) {
    mLRUKeyToDelete = key;
    mLRUStamp = lastHit;
  }

  return NS_OK;
}

void Predictor::SpaceCleaner::Finalize(nsICacheEntry* entry) {
  MOZ_ASSERT(NS_IsMainThread());

  if (mLRUKeyToDelete) {
    entry->SetMetaDataElement(mLRUKeyToDelete, nullptr);
  }

  for (size_t i = 0; i < mLongKeysToDelete.Length(); ++i) {
    entry->SetMetaDataElement(mLongKeysToDelete[i].BeginReading(), nullptr);
  }
}

// Called when a subresource has been hit from a top-level load. Uses the two
// helper functions above to update the database appropriately.
void Predictor::LearnForSubresource(nsICacheEntry* entry, nsIURI* targetURI) {
  MOZ_ASSERT(NS_IsMainThread());

  PREDICTOR_LOG(("Predictor::LearnForSubresource"));

  uint32_t lastLoad;
  nsresult rv = entry->GetLastFetched(&lastLoad);
  RETURN_IF_FAILED(rv);

  int32_t loadCount;
  rv = entry->GetFetchCount(&loadCount);
  RETURN_IF_FAILED(rv);

  nsCString key;
  key.AssignLiteral(META_DATA_PREFIX);
  nsCString uri;
  targetURI->GetAsciiSpec(uri);
  key.Append(uri);
  if (uri.Length() > StaticPrefs::network_predictor_max_uri_length()) {
    // We do this to conserve space/prevent OOMs
    PREDICTOR_LOG(("    uri too long!"));
    entry->SetMetaDataElement(key.BeginReading(), nullptr);
    return;
  }

  nsCString value;
  rv = entry->GetMetaDataElement(key.BeginReading(), getter_Copies(value));

  uint32_t hitCount, lastHit, flags;
  bool isNewResource =
      (NS_FAILED(rv) ||
       !ParseMetaDataEntry(key.BeginReading(), value.BeginReading(), uri,
                           hitCount, lastHit, flags));

  int32_t resourceCount = 0;
  if (isNewResource) {
    // This is a new addition
    PREDICTOR_LOG(("    new resource"));
    nsCString s;
    rv = entry->GetMetaDataElement(RESOURCE_META_DATA, getter_Copies(s));
    if (NS_SUCCEEDED(rv)) {
      resourceCount = atoi(s.BeginReading());
    }
    if (resourceCount >=
        StaticPrefs::network_predictor_max_resources_per_entry()) {
      RefPtr<Predictor::SpaceCleaner> cleaner =
          new Predictor::SpaceCleaner(this);
      entry->VisitMetaData(cleaner);
      cleaner->Finalize(entry);
    } else {
      ++resourceCount;
    }
    nsAutoCString count;
    count.AppendInt(resourceCount);
    rv = entry->SetMetaDataElement(RESOURCE_META_DATA, count.BeginReading());
    if (NS_FAILED(rv)) {
      PREDICTOR_LOG(("    failed to update resource count"));
      return;
    }
    hitCount = 1;
    flags = 0;
  } else {
    PREDICTOR_LOG(("    existing resource"));
    hitCount = std::min(hitCount + 1, static_cast<uint32_t>(loadCount));
  }

  // Update the rolling load count to mark this sub-resource as seen on the
  // most-recent pageload so it can be eligible for prefetch (assuming all
  // the other stars align).
  flags |= (1 << kRollingLoadOffset);

  nsCString newValue;
  MakeMetadataEntry(hitCount, lastLoad, flags, newValue);
  rv = entry->SetMetaDataElement(key.BeginReading(), newValue.BeginReading());
  PREDICTOR_LOG(
      ("    SetMetaDataElement -> 0x%08" PRIX32, static_cast<uint32_t>(rv)));
  if (NS_FAILED(rv) && isNewResource) {
    // Roll back the increment to the resource count we made above.
    PREDICTOR_LOG(("    rolling back resource count update"));
    --resourceCount;
    if (resourceCount == 0) {
      entry->SetMetaDataElement(RESOURCE_META_DATA, nullptr);
    } else {
      nsAutoCString count;
      count.AppendInt(resourceCount);
      entry->SetMetaDataElement(RESOURCE_META_DATA, count.BeginReading());
    }
  }
}

// This is called when a top-level loaded ended up redirecting to a different
// URI so we can keep track of that fact.
void Predictor::LearnForRedirect(nsICacheEntry* entry, nsIURI* targetURI) {
  MOZ_ASSERT(NS_IsMainThread());

  // TODO - not doing redirects for first go around
  PREDICTOR_LOG(("Predictor::LearnForRedirect"));
}

// This will add a page to our list of startup pages if it's being loaded
// before our startup window has expired.
void Predictor::MaybeLearnForStartup(nsIURI* uri, bool fullUri,
                                     const OriginAttributes& originAttributes) {
  MOZ_ASSERT(NS_IsMainThread());

  // TODO - not doing startup for first go around
  PREDICTOR_LOG(("Predictor::MaybeLearnForStartup"));
}

// Add information about a top-level load to our list of startup pages
void Predictor::LearnForStartup(nsICacheEntry* entry, nsIURI* targetURI) {
  MOZ_ASSERT(NS_IsMainThread());

  // These actually do the same set of work, just on different entries, so we
  // can pass through to get the real work done here
  PREDICTOR_LOG(("Predictor::LearnForStartup"));
  LearnForSubresource(entry, targetURI);
}

bool Predictor::ParseMetaDataEntry(const char* key, const char* value,
                                   nsCString& uri, uint32_t& hitCount,
                                   uint32_t& lastHit, uint32_t& flags) {
  MOZ_ASSERT(NS_IsMainThread());

  PREDICTOR_LOG(
      ("Predictor::ParseMetaDataEntry key=%s value=%s", key ? key : "", value));

  const char* comma = strchr(value, ',');
  if (!comma) {
    PREDICTOR_LOG(("    could not find first comma"));
    return false;
  }

  uint32_t version = static_cast<uint32_t>(atoi(value));
  PREDICTOR_LOG(("    version -> %u", version));

  if (version != METADATA_VERSION) {
    PREDICTOR_LOG(
        ("    metadata version mismatch %u != %u", version, METADATA_VERSION));
    return false;
  }

  value = comma + 1;
  comma = strchr(value, ',');
  if (!comma) {
    PREDICTOR_LOG(("    could not find second comma"));
    return false;
  }

  hitCount = static_cast<uint32_t>(atoi(value));
  PREDICTOR_LOG(("    hitCount -> %u", hitCount));

  value = comma + 1;
  comma = strchr(value, ',');
  if (!comma) {
    PREDICTOR_LOG(("    could not find third comma"));
    return false;
  }

  lastHit = static_cast<uint32_t>(atoi(value));
  PREDICTOR_LOG(("    lastHit -> %u", lastHit));

  value = comma + 1;
  flags = static_cast<uint32_t>(atoi(value));
  PREDICTOR_LOG(("    flags -> %u", flags));

  if (key) {
    const char* uriStart = key + (sizeof(META_DATA_PREFIX) - 1);
    uri.AssignASCII(uriStart);
    PREDICTOR_LOG(("    uri -> %s", uriStart));
  } else {
    uri.Truncate();
  }

  return true;
}

NS_IMETHODIMP
Predictor::Reset() {
  MOZ_ASSERT(NS_IsMainThread(),
             "Predictor interface methods must be called on the main thread");

  PREDICTOR_LOG(("Predictor::Reset"));

  if (IsNeckoChild()) {
    MOZ_DIAGNOSTIC_ASSERT(gNeckoChild);

    PREDICTOR_LOG(("    forwarding to parent process"));
    gNeckoChild->SendPredReset();
    return NS_OK;
  }

  PREDICTOR_LOG(("    called on parent process"));

  if (!mInitialized) {
    PREDICTOR_LOG(("    not initialized"));
    return NS_OK;
  }

  if (!StaticPrefs::network_predictor_enabled()) {
    PREDICTOR_LOG(("    not enabled"));
    return NS_OK;
  }

  RefPtr<Predictor::Resetter> reset = new Predictor::Resetter(this);
  PREDICTOR_LOG(("    created a resetter"));
  mCacheStorageService->AsyncVisitAllStorages(reset, true);
  PREDICTOR_LOG(("    Cache async launched, returning now"));

  return NS_OK;
}

NS_IMPL_ISUPPORTS(Predictor::Resetter, nsICacheEntryOpenCallback,
                  nsICacheEntryMetaDataVisitor, nsICacheStorageVisitor);

Predictor::Resetter::Resetter(Predictor* predictor)
    : mEntriesToVisit(0), mPredictor(predictor) {}

NS_IMETHODIMP
Predictor::Resetter::OnCacheEntryCheck(nsICacheEntry* entry,
                                       nsIApplicationCache* appCache,
                                       uint32_t* result) {
  *result = nsICacheEntryOpenCallback::ENTRY_WANTED;
  return NS_OK;
}

NS_IMETHODIMP
Predictor::Resetter::OnCacheEntryAvailable(nsICacheEntry* entry, bool isNew,
                                           nsIApplicationCache* appCache,
                                           nsresult result) {
  MOZ_ASSERT(NS_IsMainThread());

  if (NS_FAILED(result)) {
    // This can happen when we've tried to open an entry that doesn't exist for
    // some non-reset operation, and then get reset shortly thereafter (as
    // happens in some of our tests).
    --mEntriesToVisit;
    if (!mEntriesToVisit) {
      Complete();
    }
    return NS_OK;
  }

  entry->VisitMetaData(this);
  nsTArray<nsCString> keysToDelete;
  keysToDelete.SwapElements(mKeysToDelete);

  for (size_t i = 0; i < keysToDelete.Length(); ++i) {
    const char* key = keysToDelete[i].BeginReading();
    entry->SetMetaDataElement(key, nullptr);
  }

  --mEntriesToVisit;
  if (!mEntriesToVisit) {
    Complete();
  }

  return NS_OK;
}

NS_IMETHODIMP
Predictor::Resetter::OnMetaDataElement(const char* asciiKey,
                                       const char* asciiValue) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!StringBeginsWith(nsDependentCString(asciiKey),
                        NS_LITERAL_CSTRING(META_DATA_PREFIX))) {
    // Not a metadata entry we care about, carry on
    return NS_OK;
  }

  nsCString key;
  key.AssignASCII(asciiKey);
  mKeysToDelete.AppendElement(key);

  return NS_OK;
}

NS_IMETHODIMP
Predictor::Resetter::OnCacheStorageInfo(uint32_t entryCount,
                                        uint64_t consumption, uint64_t capacity,
                                        nsIFile* diskDirectory) {
  MOZ_ASSERT(NS_IsMainThread());

  return NS_OK;
}

NS_IMETHODIMP
Predictor::Resetter::OnCacheEntryInfo(nsIURI* uri, const nsACString& idEnhance,
                                      int64_t dataSize, int32_t fetchCount,
                                      uint32_t lastModifiedTime,
                                      uint32_t expirationTime, bool aPinned,
                                      nsILoadContextInfo* aInfo) {
  MOZ_ASSERT(NS_IsMainThread());

  nsresult rv;

  // The predictor will only ever touch entries with no idEnhance ("") or an
  // idEnhance of PREDICTOR_ORIGIN_EXTENSION, so we filter out any entries that
  // don't match that to avoid doing extra work.
  if (idEnhance.EqualsLiteral(PREDICTOR_ORIGIN_EXTENSION)) {
    // This is an entry we own, so we can just doom it entirely
    nsCOMPtr<nsICacheStorage> cacheDiskStorage;

    rv = mPredictor->mCacheStorageService->DiskCacheStorage(
        aInfo, false, getter_AddRefs(cacheDiskStorage));

    NS_ENSURE_SUCCESS(rv, rv);
    cacheDiskStorage->AsyncDoomURI(uri, idEnhance, nullptr);
  } else if (idEnhance.IsEmpty()) {
    // This is an entry we don't own, so we have to be a little more careful and
    // just get rid of our own metadata entries. Append it to an array of things
    // to operate on and then do the operations later so we don't end up calling
    // Complete() multiple times/too soon.
    ++mEntriesToVisit;
    mURIsToVisit.AppendElement(uri);
    mInfosToVisit.AppendElement(aInfo);
  }

  return NS_OK;
}

NS_IMETHODIMP
Predictor::Resetter::OnCacheEntryVisitCompleted() {
  MOZ_ASSERT(NS_IsMainThread());

  nsresult rv;

  nsTArray<nsCOMPtr<nsIURI>> urisToVisit;
  urisToVisit.SwapElements(mURIsToVisit);

  MOZ_ASSERT(mEntriesToVisit == urisToVisit.Length());

  nsTArray<nsCOMPtr<nsILoadContextInfo>> infosToVisit;
  infosToVisit.SwapElements(mInfosToVisit);

  MOZ_ASSERT(mEntriesToVisit == infosToVisit.Length());

  if (!mEntriesToVisit) {
    Complete();
    return NS_OK;
  }

  uint32_t entriesToVisit = urisToVisit.Length();
  for (uint32_t i = 0; i < entriesToVisit; ++i) {
    nsCString u;
    nsCOMPtr<nsICacheStorage> cacheDiskStorage;

    rv = mPredictor->mCacheStorageService->DiskCacheStorage(
        infosToVisit[i], false, getter_AddRefs(cacheDiskStorage));
    NS_ENSURE_SUCCESS(rv, rv);

    urisToVisit[i]->GetAsciiSpec(u);
    cacheDiskStorage->AsyncOpenURI(urisToVisit[i], EmptyCString(),
                                   nsICacheStorage::OPEN_READONLY |
                                       nsICacheStorage::OPEN_SECRETLY |
                                       nsICacheStorage::CHECK_MULTITHREADED,
                                   this);
  }

  return NS_OK;
}

void Predictor::Resetter::Complete() {
  MOZ_ASSERT(NS_IsMainThread());

  nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  if (!obs) {
    PREDICTOR_LOG(("COULD NOT GET OBSERVER SERVICE!"));
    return;
  }

  obs->NotifyObservers(nullptr, "predictor-reset-complete", nullptr);
}

// Helper functions to make using the predictor easier from native code

static StaticRefPtr<nsINetworkPredictor> sPredictor;

static nsresult EnsureGlobalPredictor(nsINetworkPredictor** aPredictor) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!sPredictor) {
    nsresult rv;
    nsCOMPtr<nsINetworkPredictor> predictor =
        do_GetService("@mozilla.org/network/predictor;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    sPredictor = predictor;
    ClearOnShutdown(&sPredictor);
  }

  nsCOMPtr<nsINetworkPredictor> predictor = sPredictor.get();
  predictor.forget(aPredictor);
  return NS_OK;
}

nsresult PredictorPredict(nsIURI* targetURI, nsIURI* sourceURI,
                          PredictorPredictReason reason,
                          const OriginAttributes& originAttributes,
                          nsINetworkPredictorVerifier* verifier) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!IsNullOrHttp(targetURI) || !IsNullOrHttp(sourceURI)) {
    return NS_OK;
  }

  nsCOMPtr<nsINetworkPredictor> predictor;
  nsresult rv = EnsureGlobalPredictor(getter_AddRefs(predictor));
  NS_ENSURE_SUCCESS(rv, rv);

  return predictor->PredictNative(targetURI, sourceURI, reason,
                                  originAttributes, verifier);
}

nsresult PredictorLearn(nsIURI* targetURI, nsIURI* sourceURI,
                        PredictorLearnReason reason,
                        const OriginAttributes& originAttributes) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!IsNullOrHttp(targetURI) || !IsNullOrHttp(sourceURI)) {
    return NS_OK;
  }

  nsCOMPtr<nsINetworkPredictor> predictor;
  nsresult rv = EnsureGlobalPredictor(getter_AddRefs(predictor));
  NS_ENSURE_SUCCESS(rv, rv);

  return predictor->LearnNative(targetURI, sourceURI, reason, originAttributes);
}

nsresult PredictorLearn(nsIURI* targetURI, nsIURI* sourceURI,
                        PredictorLearnReason reason, nsILoadGroup* loadGroup) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!IsNullOrHttp(targetURI) || !IsNullOrHttp(sourceURI)) {
    return NS_OK;
  }

  nsCOMPtr<nsINetworkPredictor> predictor;
  nsresult rv = EnsureGlobalPredictor(getter_AddRefs(predictor));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsILoadContext> loadContext;
  OriginAttributes originAttributes;

  if (loadGroup) {
    nsCOMPtr<nsIInterfaceRequestor> callbacks;
    loadGroup->GetNotificationCallbacks(getter_AddRefs(callbacks));
    if (callbacks) {
      loadContext = do_GetInterface(callbacks);

      if (loadContext) {
        loadContext->GetOriginAttributes(originAttributes);
      }
    }
  }

  return predictor->LearnNative(targetURI, sourceURI, reason, originAttributes);
}

nsresult PredictorLearn(nsIURI* targetURI, nsIURI* sourceURI,
                        PredictorLearnReason reason, dom::Document* document) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!IsNullOrHttp(targetURI) || !IsNullOrHttp(sourceURI)) {
    return NS_OK;
  }

  nsCOMPtr<nsINetworkPredictor> predictor;
  nsresult rv = EnsureGlobalPredictor(getter_AddRefs(predictor));
  NS_ENSURE_SUCCESS(rv, rv);

  OriginAttributes originAttributes;

  if (document) {
    nsCOMPtr<nsIPrincipal> docPrincipal = document->NodePrincipal();

    if (docPrincipal) {
      originAttributes = docPrincipal->OriginAttributesRef();
    }
  }

  return predictor->LearnNative(targetURI, sourceURI, reason, originAttributes);
}

nsresult PredictorLearnRedirect(nsIURI* targetURI, nsIChannel* channel,
                                const OriginAttributes& originAttributes) {
  MOZ_ASSERT(NS_IsMainThread());

  nsCOMPtr<nsIURI> sourceURI;
  nsresult rv = channel->GetOriginalURI(getter_AddRefs(sourceURI));
  NS_ENSURE_SUCCESS(rv, rv);

  bool sameUri;
  rv = targetURI->Equals(sourceURI, &sameUri);
  NS_ENSURE_SUCCESS(rv, rv);

  if (sameUri) {
    return NS_OK;
  }

  if (!IsNullOrHttp(targetURI) || !IsNullOrHttp(sourceURI)) {
    return NS_OK;
  }

  nsCOMPtr<nsINetworkPredictor> predictor;
  rv = EnsureGlobalPredictor(getter_AddRefs(predictor));
  NS_ENSURE_SUCCESS(rv, rv);

  return predictor->LearnNative(targetURI, sourceURI,
                                nsINetworkPredictor::LEARN_LOAD_REDIRECT,
                                originAttributes);
}

// nsINetworkPredictorVerifier

/**
 * Call through to the child's verifier (only during tests)
 */
NS_IMETHODIMP
Predictor::OnPredictPrefetch(nsIURI* aURI, uint32_t httpStatus) {
  if (IsNeckoChild()) {
    if (mChildVerifier) {
      // Ideally, we'd assert here. But since we're slowly moving towards a
      // world where we have multiple child processes, and only one child
      // process will be likely to have a verifier, we have to play it safer.
      return mChildVerifier->OnPredictPrefetch(aURI, httpStatus);
    }
    return NS_OK;
  }

  ipc::URIParams serURI;
  SerializeURI(aURI, serURI);

  for (auto* cp : ContentParent::AllProcesses(ContentParent::eLive)) {
    PNeckoParent* neckoParent = SingleManagedOrNull(cp->ManagedPNeckoParent());
    if (!neckoParent) {
      continue;
    }
    if (!neckoParent->SendPredOnPredictPrefetch(serURI, httpStatus)) {
      return NS_ERROR_NOT_AVAILABLE;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
Predictor::OnPredictPreconnect(nsIURI* aURI) {
  if (IsNeckoChild()) {
    if (mChildVerifier) {
      // Ideally, we'd assert here. But since we're slowly moving towards a
      // world where we have multiple child processes, and only one child
      // process will be likely to have a verifier, we have to play it safer.
      return mChildVerifier->OnPredictPreconnect(aURI);
    }
    return NS_OK;
  }

  ipc::URIParams serURI;
  SerializeURI(aURI, serURI);

  for (auto* cp : ContentParent::AllProcesses(ContentParent::eLive)) {
    PNeckoParent* neckoParent = SingleManagedOrNull(cp->ManagedPNeckoParent());
    if (!neckoParent) {
      continue;
    }
    if (!neckoParent->SendPredOnPredictPreconnect(serURI)) {
      return NS_ERROR_NOT_AVAILABLE;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
Predictor::OnPredictDNS(nsIURI* aURI) {
  if (IsNeckoChild()) {
    if (mChildVerifier) {
      // Ideally, we'd assert here. But since we're slowly moving towards a
      // world where we have multiple child processes, and only one child
      // process will be likely to have a verifier, we have to play it safer.
      return mChildVerifier->OnPredictDNS(aURI);
    }
    return NS_OK;
  }

  ipc::URIParams serURI;
  SerializeURI(aURI, serURI);

  for (auto* cp : ContentParent::AllProcesses(ContentParent::eLive)) {
    PNeckoParent* neckoParent = SingleManagedOrNull(cp->ManagedPNeckoParent());
    if (!neckoParent) {
      continue;
    }
    if (!neckoParent->SendPredOnPredictDNS(serURI)) {
      return NS_ERROR_NOT_AVAILABLE;
    }
  }

  return NS_OK;
}

// Predictor::PrefetchListener
// nsISupports
NS_IMPL_ISUPPORTS(Predictor::PrefetchListener, nsIStreamListener,
                  nsIRequestObserver)

// nsIRequestObserver
NS_IMETHODIMP
Predictor::PrefetchListener::OnStartRequest(nsIRequest* aRequest) {
  mStartTime = TimeStamp::Now();
  return NS_OK;
}

NS_IMETHODIMP
Predictor::PrefetchListener::OnStopRequest(nsIRequest* aRequest,
                                           nsresult aStatusCode) {
  PREDICTOR_LOG(("OnStopRequest this=%p aStatusCode=0x%" PRIX32, this,
                 static_cast<uint32_t>(aStatusCode)));
  NS_ENSURE_ARG(aRequest);
  if (NS_FAILED(aStatusCode)) {
    return aStatusCode;
  }
  Telemetry::AccumulateTimeDelta(Telemetry::PREDICTOR_PREFETCH_TIME,
                                 mStartTime);

  nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest);
  if (!httpChannel) {
    PREDICTOR_LOG(("    Could not get HTTP Channel!"));
    return NS_ERROR_UNEXPECTED;
  }
  nsCOMPtr<nsICachingChannel> cachingChannel = do_QueryInterface(httpChannel);
  if (!cachingChannel) {
    PREDICTOR_LOG(("    Could not get caching channel!"));
    return NS_ERROR_UNEXPECTED;
  }

  nsresult rv = NS_OK;
  uint32_t httpStatus;
  rv = httpChannel->GetResponseStatus(&httpStatus);
  if (NS_SUCCEEDED(rv) && httpStatus == 200) {
    rv = cachingChannel->ForceCacheEntryValidFor(
        StaticPrefs::network_predictor_prefetch_force_valid_for());
    PREDICTOR_LOG(("    forcing entry valid for %d seconds rv=%" PRIX32,
                   StaticPrefs::network_predictor_prefetch_force_valid_for(),
                   static_cast<uint32_t>(rv)));
  } else {
    rv = cachingChannel->ForceCacheEntryValidFor(0);
    PREDICTOR_LOG(("    removing any forced validity rv=%" PRIX32,
                   static_cast<uint32_t>(rv)));
  }

  nsAutoCString reqName;
  rv = aRequest->GetName(reqName);
  if (NS_FAILED(rv)) {
    reqName.AssignLiteral("<unknown>");
  }

  PREDICTOR_LOG(("    request %s status %u", reqName.get(), httpStatus));

  if (mVerifier) {
    mVerifier->OnPredictPrefetch(mURI, httpStatus);
  }

  return rv;
}

// nsIStreamListener
NS_IMETHODIMP
Predictor::PrefetchListener::OnDataAvailable(nsIRequest* aRequest,
                                             nsIInputStream* aInputStream,
                                             uint64_t aOffset,
                                             const uint32_t aCount) {
  uint32_t result;
  return aInputStream->ReadSegments(NS_DiscardSegment, nullptr, aCount,
                                    &result);
}

// Miscellaneous Predictor

void Predictor::UpdateCacheability(nsIURI* sourceURI, nsIURI* targetURI,
                                   uint32_t httpStatus,
                                   nsHttpRequestHead& requestHead,
                                   nsHttpResponseHead* responseHead,
                                   nsILoadContextInfo* lci, bool isTracking) {
  MOZ_ASSERT(NS_IsMainThread());

  if (lci && lci->IsPrivate()) {
    PREDICTOR_LOG(("Predictor::UpdateCacheability in PB mode - ignoring"));
    return;
  }

  if (!sourceURI || !targetURI) {
    PREDICTOR_LOG(
        ("Predictor::UpdateCacheability missing source or target uri"));
    return;
  }

  if (!IsNullOrHttp(sourceURI) || !IsNullOrHttp(targetURI)) {
    PREDICTOR_LOG(("Predictor::UpdateCacheability non-http(s) uri"));
    return;
  }

  RefPtr<Predictor> self = sSelf;
  if (self) {
    nsAutoCString method;
    requestHead.Method(method);

    nsAutoCString vary;
    Unused << responseHead->GetHeader(nsHttp::Vary, vary);

    nsAutoCString cacheControlHeader;
    Unused << responseHead->GetHeader(nsHttp::Cache_Control,
                                      cacheControlHeader);
    CacheControlParser cacheControl(cacheControlHeader);

    self->UpdateCacheabilityInternal(sourceURI, targetURI, httpStatus, method,
                                     *lci->OriginAttributesPtr(), isTracking,
                                     !vary.IsEmpty(), cacheControl.NoStore());
  }
}

void Predictor::UpdateCacheabilityInternal(
    nsIURI* sourceURI, nsIURI* targetURI, uint32_t httpStatus,
    const nsCString& method, const OriginAttributes& originAttributes,
    bool isTracking, bool couldVary, bool isNoStore) {
  PREDICTOR_LOG(("Predictor::UpdateCacheability httpStatus=%u", httpStatus));

  nsresult rv;

  if (!mInitialized) {
    PREDICTOR_LOG(("    not initialized"));
    return;
  }

  if (!StaticPrefs::network_predictor_enabled()) {
    PREDICTOR_LOG(("    not enabled"));
    return;
  }

  nsCOMPtr<nsICacheStorage> cacheDiskStorage;

  RefPtr<LoadContextInfo> lci = new LoadContextInfo(false, originAttributes);

  rv = mCacheStorageService->DiskCacheStorage(lci, false,
                                              getter_AddRefs(cacheDiskStorage));
  if (NS_FAILED(rv)) {
    PREDICTOR_LOG(("    cannot get disk cache storage"));
    return;
  }

  uint32_t openFlags = nsICacheStorage::OPEN_READONLY |
                       nsICacheStorage::OPEN_SECRETLY |
                       nsICacheStorage::CHECK_MULTITHREADED;
  RefPtr<Predictor::CacheabilityAction> action =
      new Predictor::CacheabilityAction(targetURI, httpStatus, method,
                                        isTracking, couldVary, isNoStore, this);
  nsAutoCString uri;
  targetURI->GetAsciiSpec(uri);
  PREDICTOR_LOG(("    uri=%s action=%p", uri.get(), action.get()));
  cacheDiskStorage->AsyncOpenURI(sourceURI, EmptyCString(), openFlags, action);
}

NS_IMPL_ISUPPORTS(Predictor::CacheabilityAction, nsICacheEntryOpenCallback,
                  nsICacheEntryMetaDataVisitor);

NS_IMETHODIMP
Predictor::CacheabilityAction::OnCacheEntryCheck(nsICacheEntry* entry,
                                                 nsIApplicationCache* appCache,
                                                 uint32_t* result) {
  *result = nsICacheEntryOpenCallback::ENTRY_WANTED;
  return NS_OK;
}

namespace {
enum PrefetchDecisionReason {
  PREFETCHABLE,
  STATUS_NOT_200,
  METHOD_NOT_GET,
  URL_HAS_QUERY_STRING,
  RESOURCE_IS_TRACKING,
  RESOURCE_COULD_VARY,
  RESOURCE_IS_NO_STORE
};
}

NS_IMETHODIMP
Predictor::CacheabilityAction::OnCacheEntryAvailable(
    nsICacheEntry* entry, bool isNew, nsIApplicationCache* appCache,
    nsresult result) {
  MOZ_ASSERT(NS_IsMainThread());
  // This is being opened read-only, so isNew should always be false
  MOZ_ASSERT(!isNew);

  PREDICTOR_LOG(("CacheabilityAction::OnCacheEntryAvailable this=%p", this));
  if (NS_FAILED(result)) {
    // Nothing to do
    PREDICTOR_LOG(("    nothing to do result=%" PRIX32 " isNew=%d",
                   static_cast<uint32_t>(result), isNew));
    return NS_OK;
  }

  nsCString strTargetURI;
  nsresult rv = mTargetURI->GetAsciiSpec(strTargetURI);
  if (NS_FAILED(rv)) {
    PREDICTOR_LOG(
        ("    GetAsciiSpec returned %" PRIx32, static_cast<uint32_t>(rv)));
    return NS_OK;
  }

  rv = entry->VisitMetaData(this);
  if (NS_FAILED(rv)) {
    PREDICTOR_LOG(
        ("    VisitMetaData returned %" PRIx32, static_cast<uint32_t>(rv)));
    return NS_OK;
  }

  nsTArray<nsCString> keysToCheck, valuesToCheck;
  keysToCheck.SwapElements(mKeysToCheck);
  valuesToCheck.SwapElements(mValuesToCheck);

  bool hasQueryString = false;
  nsAutoCString query;
  if (NS_SUCCEEDED(mTargetURI->GetQuery(query)) && !query.IsEmpty()) {
    hasQueryString = true;
  }

  MOZ_ASSERT(keysToCheck.Length() == valuesToCheck.Length());
  for (size_t i = 0; i < keysToCheck.Length(); ++i) {
    const char* key = keysToCheck[i].BeginReading();
    const char* value = valuesToCheck[i].BeginReading();
    nsCString uri;
    uint32_t hitCount, lastHit, flags;

    if (!mPredictor->ParseMetaDataEntry(key, value, uri, hitCount, lastHit,
                                        flags)) {
      PREDICTOR_LOG(("    failed to parse key=%s value=%s", key, value));
      continue;
    }

    if (strTargetURI.Equals(uri)) {
      bool prefetchable = true;
      PrefetchDecisionReason reason = PREFETCHABLE;

      if (mHttpStatus != 200) {
        prefetchable = false;
        reason = STATUS_NOT_200;
      } else if (!mMethod.EqualsLiteral("GET")) {
        prefetchable = false;
        reason = METHOD_NOT_GET;
      } else if (hasQueryString) {
        prefetchable = false;
        reason = URL_HAS_QUERY_STRING;
      } else if (mIsTracking) {
        prefetchable = false;
        reason = RESOURCE_IS_TRACKING;
      } else if (mCouldVary) {
        prefetchable = false;
        reason = RESOURCE_COULD_VARY;
      } else if (mIsNoStore) {
        // We don't set prefetchable = false yet, because we just want to know
        // what kind of effect this would have on prefetching.
        reason = RESOURCE_IS_NO_STORE;
      }

      Telemetry::Accumulate(Telemetry::PREDICTOR_PREFETCH_DECISION_REASON,
                            reason);

      if (prefetchable) {
        PREDICTOR_LOG(("    marking %s cacheable", key));
        flags |= FLAG_PREFETCHABLE;
      } else {
        PREDICTOR_LOG(("    marking %s uncacheable", key));
        flags &= ~FLAG_PREFETCHABLE;
      }
      nsCString newValue;
      MakeMetadataEntry(hitCount, lastHit, flags, newValue);
      entry->SetMetaDataElement(key, newValue.BeginReading());
      break;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
Predictor::CacheabilityAction::OnMetaDataElement(const char* asciiKey,
                                                 const char* asciiValue) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!IsURIMetadataElement(asciiKey)) {
    return NS_OK;
  }

  nsCString key, value;
  key.AssignASCII(asciiKey);
  value.AssignASCII(asciiValue);
  mKeysToCheck.AppendElement(key);
  mValuesToCheck.AppendElement(value);

  return NS_OK;
}

}  // namespace net
}  // namespace mozilla