hints_manager_unittest.cc 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/optimization_guide/core/hints_manager.h"
  5. #include <string>
  6. #include <utility>
  7. #include "base/base64.h"
  8. #include "base/callback_helpers.h"
  9. #include "base/command_line.h"
  10. #include "base/files/file_util.h"
  11. #include "base/test/gtest_util.h"
  12. #include "base/test/metrics/histogram_tester.h"
  13. #include "base/test/scoped_feature_list.h"
  14. #include "base/test/task_environment.h"
  15. #include "components/optimization_guide/core/bloom_filter.h"
  16. #include "components/optimization_guide/core/hint_cache.h"
  17. #include "components/optimization_guide/core/hints_component_util.h"
  18. #include "components/optimization_guide/core/hints_fetcher.h"
  19. #include "components/optimization_guide/core/hints_fetcher_factory.h"
  20. #include "components/optimization_guide/core/optimization_guide_constants.h"
  21. #include "components/optimization_guide/core/optimization_guide_enums.h"
  22. #include "components/optimization_guide/core/optimization_guide_features.h"
  23. #include "components/optimization_guide/core/optimization_guide_logger.h"
  24. #include "components/optimization_guide/core/optimization_guide_navigation_data.h"
  25. #include "components/optimization_guide/core/optimization_guide_prefs.h"
  26. #include "components/optimization_guide/core/optimization_guide_store.h"
  27. #include "components/optimization_guide/core/optimization_guide_switches.h"
  28. #include "components/optimization_guide/core/proto_database_provider_test_base.h"
  29. #include "components/optimization_guide/core/tab_url_provider.h"
  30. #include "components/optimization_guide/core/top_host_provider.h"
  31. #include "components/prefs/pref_registry_simple.h"
  32. #include "components/sync_preferences/testing_pref_service_syncable.h"
  33. #include "components/ukm/test_ukm_recorder.h"
  34. #include "components/unified_consent/unified_consent_service.h"
  35. #include "components/variations/scoped_variations_ids_provider.h"
  36. #include "services/metrics/public/cpp/ukm_builders.h"
  37. #include "services/metrics/public/cpp/ukm_source.h"
  38. #include "services/network/public/cpp/shared_url_loader_factory.h"
  39. #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
  40. #include "services/network/test/test_url_loader_factory.h"
  41. #include "testing/gtest/include/gtest/gtest.h"
  42. namespace optimization_guide {
  43. namespace {
  44. // Allows for default hour to pass + random delay between 30 and 60 seconds.
  45. constexpr int kUpdateFetchHintsTimeSecs = 61 * 60; // 1 hours and 1 minutes.
  46. const int kDefaultHostBloomFilterNumHashFunctions = 7;
  47. const int kDefaultHostBloomFilterNumBits = 511;
  48. void PopulateBloomFilterWithDefaultHost(BloomFilter* bloom_filter) {
  49. bloom_filter->Add("host.com");
  50. }
  51. void AddBloomFilterToConfig(proto::OptimizationType optimization_type,
  52. const BloomFilter& bloom_filter,
  53. int num_hash_functions,
  54. int num_bits,
  55. bool is_allowlist,
  56. proto::Configuration* config) {
  57. std::string bloom_filter_data(
  58. reinterpret_cast<const char*>(&bloom_filter.bytes()[0]),
  59. bloom_filter.bytes().size());
  60. proto::OptimizationFilter* of_proto =
  61. is_allowlist ? config->add_optimization_allowlists()
  62. : config->add_optimization_blocklists();
  63. of_proto->set_optimization_type(optimization_type);
  64. std::unique_ptr<proto::BloomFilter> bloom_filter_proto =
  65. std::make_unique<proto::BloomFilter>();
  66. bloom_filter_proto->set_num_hash_functions(num_hash_functions);
  67. bloom_filter_proto->set_num_bits(num_bits);
  68. bloom_filter_proto->set_data(bloom_filter_data);
  69. of_proto->set_allocated_bloom_filter(bloom_filter_proto.release());
  70. }
  71. std::unique_ptr<proto::GetHintsResponse> BuildHintsResponse(
  72. const std::vector<std::string>& hosts,
  73. const std::vector<std::string>& urls) {
  74. std::unique_ptr<proto::GetHintsResponse> get_hints_response =
  75. std::make_unique<proto::GetHintsResponse>();
  76. for (const auto& host : hosts) {
  77. proto::Hint* hint = get_hints_response->add_hints();
  78. hint->set_key_representation(proto::HOST);
  79. hint->set_key(host);
  80. proto::PageHint* page_hint = hint->add_page_hints();
  81. page_hint->set_page_pattern("page pattern");
  82. proto::Optimization* opt = page_hint->add_allowlisted_optimizations();
  83. opt->set_optimization_type(proto::DEFER_ALL_SCRIPT);
  84. }
  85. for (const auto& url : urls) {
  86. proto::Hint* hint = get_hints_response->add_hints();
  87. hint->set_key_representation(proto::FULL_URL);
  88. hint->set_key(url);
  89. hint->mutable_max_cache_duration()->set_seconds(60 * 60);
  90. proto::PageHint* page_hint = hint->add_page_hints();
  91. page_hint->set_page_pattern(url);
  92. proto::Optimization* opt = page_hint->add_allowlisted_optimizations();
  93. opt->set_optimization_type(proto::COMPRESS_PUBLIC_IMAGES);
  94. opt->mutable_public_image_metadata()->add_url("someurl");
  95. }
  96. return get_hints_response;
  97. }
  98. void RunHintsFetchedCallbackWithResponse(
  99. HintsFetchedCallback hints_fetched_callback,
  100. std::unique_ptr<proto::GetHintsResponse> response) {
  101. std::move(hints_fetched_callback).Run(std::move(response));
  102. }
  103. // Returns the default params used for the kOptimizationHints feature.
  104. base::FieldTrialParams GetOptimizationHintsDefaultFeatureParams() {
  105. return {{
  106. "max_host_keyed_hint_cache_size",
  107. "1",
  108. }};
  109. }
  110. std::unique_ptr<base::test::ScopedFeatureList>
  111. SetUpDeferStartupActiveTabsHintsFetch(bool is_enabled) {
  112. std::unique_ptr<base::test::ScopedFeatureList> scoped_feature_list =
  113. std::make_unique<base::test::ScopedFeatureList>();
  114. auto params = GetOptimizationHintsDefaultFeatureParams();
  115. params["defer_startup_active_tabs_hints_fetch"] =
  116. is_enabled ? "true" : "false";
  117. scoped_feature_list->InitAndEnableFeatureWithParameters(
  118. features::kOptimizationHints, params);
  119. return scoped_feature_list;
  120. }
  121. } // namespace
  122. // A mock class implementation of TopHostProvider.
  123. class FakeTopHostProvider : public TopHostProvider {
  124. public:
  125. explicit FakeTopHostProvider(const std::vector<std::string>& top_hosts)
  126. : top_hosts_(top_hosts) {}
  127. std::vector<std::string> GetTopHosts() override {
  128. num_top_hosts_called_++;
  129. return top_hosts_;
  130. }
  131. int get_num_top_hosts_called() const { return num_top_hosts_called_; }
  132. private:
  133. std::vector<std::string> top_hosts_;
  134. int num_top_hosts_called_ = 0;
  135. };
  136. // A mock class implementation of TabUrlProvider.
  137. class FakeTabUrlProvider : public TabUrlProvider {
  138. public:
  139. const std::vector<GURL> GetUrlsOfActiveTabs(
  140. const base::TimeDelta& duration_since_last_shown) override {
  141. num_urls_called_++;
  142. return urls_;
  143. }
  144. void SetUrls(const std::vector<GURL>& urls) { urls_ = urls; }
  145. int get_num_urls_called() const { return num_urls_called_; }
  146. private:
  147. std::vector<GURL> urls_;
  148. int num_urls_called_ = 0;
  149. };
  150. enum class HintsFetcherEndState {
  151. kFetchFailed = 0,
  152. kFetchSuccessWithHostHints = 1,
  153. kFetchSuccessWithNoHints = 2,
  154. kFetchSuccessWithURLHints = 3,
  155. };
  156. // A mock class implementation of HintsFetcher. It will iterate through the
  157. // provided fetch states each time it is called. If it reaches the end of the
  158. // loop, it will just continue using the last fetch state.
  159. class TestHintsFetcher : public HintsFetcher {
  160. public:
  161. TestHintsFetcher(
  162. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
  163. GURL optimization_guide_service_url,
  164. PrefService* pref_service,
  165. const std::vector<HintsFetcherEndState>& fetch_states,
  166. OptimizationGuideLogger* optimization_guide_logger)
  167. : HintsFetcher(url_loader_factory,
  168. optimization_guide_service_url,
  169. pref_service,
  170. &optimization_guide_logger_),
  171. fetch_states_(fetch_states) {
  172. DCHECK(!fetch_states_.empty());
  173. }
  174. bool FetchOptimizationGuideServiceHints(
  175. const std::vector<std::string>& hosts,
  176. const std::vector<GURL>& urls,
  177. const base::flat_set<proto::OptimizationType>& optimization_types,
  178. proto::RequestContext request_context,
  179. const std::string& locale,
  180. HintsFetchedCallback hints_fetched_callback) override {
  181. HintsFetcherEndState fetch_state =
  182. num_fetches_requested_ < static_cast<int>(fetch_states_.size())
  183. ? fetch_states_[num_fetches_requested_]
  184. : fetch_states_.back();
  185. num_fetches_requested_++;
  186. locale_requested_ = locale;
  187. request_context_requested_ = request_context;
  188. switch (fetch_state) {
  189. case HintsFetcherEndState::kFetchFailed:
  190. std::move(hints_fetched_callback).Run(absl::nullopt);
  191. return false;
  192. case HintsFetcherEndState::kFetchSuccessWithHostHints:
  193. base::ThreadTaskRunnerHandle::Get()->PostTask(
  194. FROM_HERE, base::BindOnce(&RunHintsFetchedCallbackWithResponse,
  195. std::move(hints_fetched_callback),
  196. BuildHintsResponse({"host.com"}, {})));
  197. return true;
  198. case HintsFetcherEndState::kFetchSuccessWithURLHints:
  199. base::ThreadTaskRunnerHandle::Get()->PostTask(
  200. FROM_HERE,
  201. base::BindOnce(&RunHintsFetchedCallbackWithResponse,
  202. std::move(hints_fetched_callback),
  203. BuildHintsResponse(
  204. {}, {"https://somedomain.org/news/whatever"})));
  205. return true;
  206. case HintsFetcherEndState::kFetchSuccessWithNoHints:
  207. base::ThreadTaskRunnerHandle::Get()->PostTask(
  208. FROM_HERE, base::BindOnce(&RunHintsFetchedCallbackWithResponse,
  209. std::move(hints_fetched_callback),
  210. BuildHintsResponse({}, {})));
  211. return true;
  212. }
  213. return true;
  214. }
  215. int num_fetches_requested() const { return num_fetches_requested_; }
  216. std::string locale_requested() const { return locale_requested_; }
  217. proto::RequestContext request_context_requested() const {
  218. return request_context_requested_;
  219. }
  220. private:
  221. std::vector<HintsFetcherEndState> fetch_states_;
  222. int num_fetches_requested_ = 0;
  223. std::string locale_requested_;
  224. proto::RequestContext request_context_requested_ =
  225. proto::RequestContext::CONTEXT_UNSPECIFIED;
  226. OptimizationGuideLogger optimization_guide_logger_;
  227. };
  228. // A mock class of HintsFetcherFactory that returns instances of
  229. // TestHintsFetchers with the provided fetch state.
  230. class TestHintsFetcherFactory : public HintsFetcherFactory {
  231. public:
  232. TestHintsFetcherFactory(
  233. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
  234. GURL optimization_guide_service_url,
  235. PrefService* pref_service,
  236. const std::vector<HintsFetcherEndState>& fetch_states)
  237. : HintsFetcherFactory(url_loader_factory,
  238. optimization_guide_service_url,
  239. pref_service),
  240. fetch_states_(fetch_states) {}
  241. std::unique_ptr<HintsFetcher> BuildInstance(
  242. OptimizationGuideLogger* optimization_guide_logger) override {
  243. return std::make_unique<TestHintsFetcher>(
  244. url_loader_factory_, optimization_guide_service_url_, pref_service_,
  245. fetch_states_, optimization_guide_logger);
  246. }
  247. private:
  248. std::vector<HintsFetcherEndState> fetch_states_;
  249. };
  250. class HintsManagerTest : public ProtoDatabaseProviderTestBase {
  251. public:
  252. HintsManagerTest() {
  253. scoped_feature_list_.InitWithFeaturesAndParameters(
  254. {{features::kOptimizationHints,
  255. GetOptimizationHintsDefaultFeatureParams()},
  256. {features::kOptimizationHintsComponent,
  257. {{"check_failed_component_version_pref", "true"}}}},
  258. /*disabled_features=*/{});
  259. pref_service_ =
  260. std::make_unique<sync_preferences::TestingPrefServiceSyncable>();
  261. prefs::RegisterProfilePrefs(pref_service_->registry());
  262. unified_consent::UnifiedConsentService::RegisterPrefs(
  263. pref_service_->registry());
  264. }
  265. ~HintsManagerTest() override = default;
  266. HintsManagerTest(const HintsManagerTest&) = delete;
  267. HintsManagerTest& operator=(const HintsManagerTest&) = delete;
  268. void SetUp() override {
  269. ProtoDatabaseProviderTestBase::SetUp();
  270. CreateHintsManager(/*top_host_provider=*/nullptr);
  271. }
  272. void TearDown() override {
  273. ResetHintsManager();
  274. pref_service_.reset();
  275. ProtoDatabaseProviderTestBase::TearDown();
  276. }
  277. void CreateHintsManager(TopHostProvider* top_host_provider) {
  278. if (hints_manager_)
  279. ResetHintsManager();
  280. url_loader_factory_ =
  281. base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
  282. &test_url_loader_factory_);
  283. hint_store_ = std::make_unique<OptimizationGuideStore>(
  284. db_provider_.get(), temp_dir(),
  285. task_environment_.GetMainThreadTaskRunner(), pref_service_.get());
  286. tab_url_provider_ = std::make_unique<FakeTabUrlProvider>();
  287. hints_manager_ = std::make_unique<HintsManager>(
  288. /*is_off_the_record=*/false, /*application_locale=*/"en-US",
  289. pref_service(), hint_store_->AsWeakPtr(), top_host_provider,
  290. tab_url_provider_.get(), url_loader_factory_,
  291. /*push_notification_manager=*/nullptr, &optimization_guide_logger_);
  292. hints_manager_->SetClockForTesting(task_environment_.GetMockClock());
  293. // Run until hint cache is initialized and the HintsManager is ready to
  294. // process hints.
  295. RunUntilIdle();
  296. }
  297. void ResetHintsManager() {
  298. hints_manager_->Shutdown();
  299. hints_manager_.reset();
  300. tab_url_provider_.reset();
  301. hint_store_.reset();
  302. RunUntilIdle();
  303. }
  304. void ProcessInvalidHintsComponentInfo(const std::string& version) {
  305. HintsComponentInfo info(
  306. base::Version(version),
  307. temp_dir().Append(FILE_PATH_LITERAL("notaconfigfile")));
  308. base::RunLoop run_loop;
  309. hints_manager_->ListenForNextUpdateForTesting(run_loop.QuitClosure());
  310. hints_manager_->OnHintsComponentAvailable(info);
  311. run_loop.Run();
  312. }
  313. void ProcessHintsComponentInfoWithBadConfig(const std::string& version) {
  314. HintsComponentInfo info(
  315. base::Version(version),
  316. temp_dir().Append(FILE_PATH_LITERAL("badconfig.pb")));
  317. ASSERT_EQ(7, base::WriteFile(info.path, "garbage", 7));
  318. hints_manager_->OnHintsComponentAvailable(info);
  319. RunUntilIdle();
  320. }
  321. void ProcessHints(const proto::Configuration& config,
  322. const std::string& version,
  323. bool should_wait = true) {
  324. HintsComponentInfo info(
  325. base::Version(version),
  326. temp_dir().Append(FILE_PATH_LITERAL("somefile.pb")));
  327. ASSERT_NO_FATAL_FAILURE(WriteConfigToFile(config, info.path));
  328. base::RunLoop run_loop;
  329. if (should_wait)
  330. hints_manager_->ListenForNextUpdateForTesting(run_loop.QuitClosure());
  331. hints_manager_->OnHintsComponentAvailable(info);
  332. if (should_wait)
  333. run_loop.Run();
  334. }
  335. void InitializeWithDefaultConfig(const std::string& version,
  336. bool should_wait = true) {
  337. proto::Configuration config;
  338. proto::Hint* hint1 = config.add_hints();
  339. hint1->set_key("somedomain.org");
  340. hint1->set_key_representation(proto::HOST);
  341. hint1->set_version("someversion");
  342. proto::PageHint* page_hint1 = hint1->add_page_hints();
  343. page_hint1->set_page_pattern("/news/");
  344. proto::Optimization* default_opt =
  345. page_hint1->add_allowlisted_optimizations();
  346. default_opt->set_optimization_type(proto::NOSCRIPT);
  347. // Add another hint so somedomain.org hint is not in-memory initially.
  348. proto::Hint* hint2 = config.add_hints();
  349. hint2->set_key("somedomain2.org");
  350. hint2->set_key_representation(proto::HOST);
  351. hint2->set_version("someversion");
  352. proto::Optimization* opt = hint2->add_allowlisted_optimizations();
  353. opt->set_optimization_type(proto::NOSCRIPT);
  354. ProcessHints(config, version, should_wait);
  355. }
  356. std::unique_ptr<HintsFetcherFactory> BuildTestHintsFetcherFactory(
  357. const std::vector<HintsFetcherEndState>& fetch_states) {
  358. return std::make_unique<TestHintsFetcherFactory>(
  359. url_loader_factory_, GURL("https://hintsserver.com"), pref_service(),
  360. fetch_states);
  361. }
  362. void MoveClockForwardBy(base::TimeDelta time_delta) {
  363. task_environment_.FastForwardBy(time_delta);
  364. RunUntilIdle();
  365. }
  366. // Creates navigation data for a navigation to |url| with registered
  367. // |optimization_types|.
  368. std::unique_ptr<OptimizationGuideNavigationData> CreateTestNavigationData(
  369. const GURL& url,
  370. const std::vector<proto::OptimizationType>& optimization_types) {
  371. auto navigation_data = std::make_unique<OptimizationGuideNavigationData>(
  372. /*navigation_id=*/1, /*navigation_start*/ base::TimeTicks::Now());
  373. navigation_data->set_navigation_url(url);
  374. navigation_data->set_registered_optimization_types(optimization_types);
  375. return navigation_data;
  376. }
  377. void CallOnNavigationStartOrRedirect(
  378. OptimizationGuideNavigationData* navigation_data,
  379. base::OnceClosure callback) {
  380. hints_manager()->OnNavigationStartOrRedirect(navigation_data,
  381. std::move(callback));
  382. }
  383. HintsManager* hints_manager() const { return hints_manager_.get(); }
  384. int32_t num_batch_update_hints_fetches_initiated() const {
  385. return hints_manager()->num_batch_update_hints_fetches_initiated();
  386. }
  387. TestHintsFetcher* active_tabs_batch_update_hints_fetcher() const {
  388. return static_cast<TestHintsFetcher*>(
  389. hints_manager()->active_tabs_batch_update_hints_fetcher());
  390. }
  391. GURL url_with_hints() const {
  392. return GURL("https://somedomain.org/news/whatever");
  393. }
  394. GURL url_with_url_keyed_hint() const {
  395. return GURL("https://somedomain.org/news/whatever");
  396. }
  397. GURL url_without_hints() const {
  398. return GURL("https://url_without_hints.org/");
  399. }
  400. base::FilePath temp_dir() const { return temp_dir_.GetPath(); }
  401. PrefService* pref_service() const { return pref_service_.get(); }
  402. FakeTabUrlProvider* tab_url_provider() const {
  403. return tab_url_provider_.get();
  404. }
  405. void RunUntilIdle() {
  406. task_environment_.RunUntilIdle();
  407. base::RunLoop().RunUntilIdle();
  408. }
  409. private:
  410. void WriteConfigToFile(const proto::Configuration& config,
  411. const base::FilePath& filePath) {
  412. std::string serialized_config;
  413. ASSERT_TRUE(config.SerializeToString(&serialized_config));
  414. ASSERT_EQ(static_cast<int32_t>(serialized_config.size()),
  415. base::WriteFile(filePath, serialized_config.data(),
  416. serialized_config.size()));
  417. }
  418. base::test::TaskEnvironment task_environment_{
  419. base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  420. base::test::ScopedFeatureList scoped_feature_list_;
  421. std::unique_ptr<OptimizationGuideStore> hint_store_;
  422. std::unique_ptr<FakeTabUrlProvider> tab_url_provider_;
  423. std::unique_ptr<HintsManager> hints_manager_;
  424. std::unique_ptr<sync_preferences::TestingPrefServiceSyncable> pref_service_;
  425. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
  426. network::TestURLLoaderFactory test_url_loader_factory_;
  427. OptimizationGuideLogger optimization_guide_logger_;
  428. };
  429. TEST_F(HintsManagerTest, ProcessHintsWithValidCommandLineOverride) {
  430. base::HistogramTester histogram_tester;
  431. proto::Configuration config;
  432. proto::Hint* hint = config.add_hints();
  433. hint->set_key("somedomain.org");
  434. hint->set_key_representation(proto::HOST);
  435. proto::PageHint* page_hint = hint->add_page_hints();
  436. page_hint->set_page_pattern("noscript_default_2g");
  437. proto::Optimization* optimization =
  438. page_hint->add_allowlisted_optimizations();
  439. optimization->set_optimization_type(proto::NOSCRIPT);
  440. BloomFilter bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  441. kDefaultHostBloomFilterNumBits);
  442. PopulateBloomFilterWithDefaultHost(&bloom_filter);
  443. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, bloom_filter,
  444. kDefaultHostBloomFilterNumHashFunctions,
  445. kDefaultHostBloomFilterNumBits,
  446. /*is_allowlist=*/false, &config);
  447. AddBloomFilterToConfig(proto::PERFORMANCE_HINTS, bloom_filter,
  448. kDefaultHostBloomFilterNumHashFunctions,
  449. kDefaultHostBloomFilterNumBits,
  450. /*is_allowlist=*/true, &config);
  451. std::string encoded_config;
  452. config.SerializeToString(&encoded_config);
  453. base::Base64Encode(encoded_config, &encoded_config);
  454. base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
  455. switches::kHintsProtoOverride, encoded_config);
  456. CreateHintsManager(/*top_host_provider=*/nullptr);
  457. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  458. // The below histogram should not be recorded since hints weren't coming
  459. // directly from the component.
  460. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  461. ProcessHintsComponentResult::kSuccess, 1);
  462. // However, we still expect the local histogram for the hints being updated to
  463. // be recorded.
  464. histogram_tester.ExpectUniqueSample(
  465. "OptimizationGuide.UpdateComponentHints.Result", true, 1);
  466. // Bloom filters passed via command line are processed on the background
  467. // thread so make sure everything has finished before checking if it has been
  468. // loaded.
  469. RunUntilIdle();
  470. EXPECT_TRUE(hints_manager()->HasLoadedOptimizationBlocklist(
  471. proto::LITE_PAGE_REDIRECT));
  472. EXPECT_FALSE(hints_manager()->HasLoadedOptimizationAllowlist(
  473. proto::PERFORMANCE_HINTS));
  474. // Now register a new type with an allowlist that has not yet been loaded.
  475. hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS});
  476. RunUntilIdle();
  477. EXPECT_TRUE(hints_manager()->HasLoadedOptimizationAllowlist(
  478. proto::PERFORMANCE_HINTS));
  479. }
  480. TEST_F(HintsManagerTest, ProcessHintsWithInvalidCommandLineOverride) {
  481. base::HistogramTester histogram_tester;
  482. base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
  483. switches::kHintsProtoOverride, "this-is-not-a-proto");
  484. CreateHintsManager(/*top_host_provider=*/nullptr);
  485. // The below histogram should not be recorded since hints weren't coming
  486. // directly from the component.
  487. histogram_tester.ExpectTotalCount("OptimizationGuide.ProcessHintsResult", 0);
  488. // We also do not expect to update the component hints with bad hints either.
  489. histogram_tester.ExpectTotalCount(
  490. "OptimizationGuide.UpdateComponentHints.Result", 0);
  491. }
  492. TEST_F(HintsManagerTest,
  493. ProcessHintsWithCommandLineOverrideShouldNotBeOverriddenByNewComponent) {
  494. proto::Configuration config;
  495. proto::Hint* hint = config.add_hints();
  496. hint->set_key("somedomain.org");
  497. hint->set_key_representation(proto::HOST);
  498. proto::PageHint* page_hint = hint->add_page_hints();
  499. page_hint->set_page_pattern("noscript_default_2g");
  500. proto::Optimization* optimization =
  501. page_hint->add_allowlisted_optimizations();
  502. optimization->set_optimization_type(proto::NOSCRIPT);
  503. std::string encoded_config;
  504. config.SerializeToString(&encoded_config);
  505. base::Base64Encode(encoded_config, &encoded_config);
  506. {
  507. base::HistogramTester histogram_tester;
  508. base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
  509. switches::kHintsProtoOverride, encoded_config);
  510. CreateHintsManager(/*top_host_provider=*/nullptr);
  511. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  512. ProcessHintsComponentResult::kSuccess,
  513. 1);
  514. histogram_tester.ExpectUniqueSample(
  515. "OptimizationGuide.UpdateComponentHints.Result", true, 1);
  516. }
  517. // Test that a new component coming in does not update the component hints.
  518. {
  519. base::HistogramTester histogram_tester;
  520. InitializeWithDefaultConfig("3.0.0.0");
  521. // The below histograms should not be recorded since component hints
  522. // processing is disabled.
  523. histogram_tester.ExpectTotalCount("OptimizationGuide.ProcessHintsResult",
  524. 0);
  525. histogram_tester.ExpectTotalCount(
  526. "OptimizationGuide.UpdateComponentHints.Result", 0);
  527. }
  528. }
  529. TEST_F(HintsManagerTest, ParseTwoConfigVersions) {
  530. proto::Configuration config;
  531. proto::Hint* hint1 = config.add_hints();
  532. hint1->set_key("somedomain.org");
  533. hint1->set_key_representation(proto::HOST);
  534. hint1->set_version("someversion");
  535. proto::PageHint* page_hint1 = hint1->add_page_hints();
  536. page_hint1->set_page_pattern("/news/");
  537. proto::Optimization* optimization1 =
  538. page_hint1->add_allowlisted_optimizations();
  539. optimization1->set_optimization_type(proto::RESOURCE_LOADING);
  540. // Test the first time parsing the config.
  541. {
  542. base::HistogramTester histogram_tester;
  543. InitializeWithDefaultConfig("1.0.0.0");
  544. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  545. ProcessHintsComponentResult::kSuccess,
  546. 1);
  547. }
  548. // Test the second time parsing the config. This should also update the hints.
  549. {
  550. base::HistogramTester histogram_tester;
  551. InitializeWithDefaultConfig("2.0.0.0");
  552. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  553. ProcessHintsComponentResult::kSuccess,
  554. 1);
  555. }
  556. }
  557. TEST_F(HintsManagerTest, ParseInvalidConfigVersions) {
  558. // Test the first time parsing the config.
  559. {
  560. base::HistogramTester histogram_tester;
  561. InitializeWithDefaultConfig("1.0.0.0");
  562. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  563. ProcessHintsComponentResult::kSuccess,
  564. 1);
  565. }
  566. {
  567. base::HistogramTester histogram_tester;
  568. ProcessHintsComponentInfoWithBadConfig("2.0.0.0");
  569. // If we have already parsed a version later than this version, we expect
  570. // for the hints to not be updated.
  571. histogram_tester.ExpectUniqueSample(
  572. "OptimizationGuide.ProcessHintsResult",
  573. ProcessHintsComponentResult::kFailedInvalidConfiguration, 1);
  574. }
  575. }
  576. TEST_F(HintsManagerTest, ComponentProcessingWhileShutdown) {
  577. base::HistogramTester histogram_tester;
  578. InitializeWithDefaultConfig("10.0.0.0", /*should_wait=*/false);
  579. hints_manager()->Shutdown();
  580. histogram_tester.ExpectUniqueSample(
  581. "OptimizationGuide.ProcessingComponentAtShutdown", true, 1);
  582. EXPECT_TRUE(
  583. pref_service()->GetString(prefs::kPendingHintsProcessingVersion).empty());
  584. }
  585. TEST_F(HintsManagerTest, ParseOlderConfigVersions) {
  586. // Test the first time parsing the config.
  587. {
  588. base::HistogramTester histogram_tester;
  589. InitializeWithDefaultConfig("10.0.0.0");
  590. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  591. ProcessHintsComponentResult::kSuccess,
  592. 1);
  593. }
  594. // Test the second time parsing the config. This will be treated by the cache
  595. // as an older version.
  596. {
  597. base::HistogramTester histogram_tester;
  598. InitializeWithDefaultConfig("2.0.0.0");
  599. // If we have already parsed a version later than this version, we expect
  600. // for the hints to not be updated.
  601. histogram_tester.ExpectUniqueSample(
  602. "OptimizationGuide.ProcessHintsResult",
  603. ProcessHintsComponentResult::kSkippedProcessingHints, 1);
  604. }
  605. }
  606. TEST_F(HintsManagerTest, ParseDuplicateConfigVersions) {
  607. const std::string version = "3.0.0.0";
  608. // Test the first time parsing the config.
  609. {
  610. base::HistogramTester histogram_tester;
  611. InitializeWithDefaultConfig(version);
  612. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  613. ProcessHintsComponentResult::kSuccess,
  614. 1);
  615. }
  616. // Test the second time parsing the config. This will be treated by the cache
  617. // as a duplicate version.
  618. {
  619. base::HistogramTester histogram_tester;
  620. InitializeWithDefaultConfig(version);
  621. histogram_tester.ExpectUniqueSample(
  622. "OptimizationGuide.ProcessHintsResult",
  623. ProcessHintsComponentResult::kSkippedProcessingHints, 1);
  624. }
  625. }
  626. TEST_F(HintsManagerTest, ComponentInfoDidNotContainConfig) {
  627. base::HistogramTester histogram_tester;
  628. ProcessInvalidHintsComponentInfo("1.0.0.0");
  629. histogram_tester.ExpectUniqueSample(
  630. "OptimizationGuide.ProcessHintsResult",
  631. ProcessHintsComponentResult::kFailedReadingFile, 1);
  632. }
  633. TEST_F(HintsManagerTest, ProcessHintsWithExistingPref) {
  634. // Write hints processing pref for version 2.0.0.
  635. pref_service()->SetString(prefs::kPendingHintsProcessingVersion, "2.0.0");
  636. CreateHintsManager(/*top_host_provider=*/nullptr);
  637. // Verify config not processed for same version (2.0.0) and pref not cleared.
  638. {
  639. base::HistogramTester histogram_tester;
  640. InitializeWithDefaultConfig("2.0.0");
  641. histogram_tester.ExpectUniqueSample(
  642. "OptimizationGuide.ProcessHintsResult",
  643. ProcessHintsComponentResult::kFailedFinishProcessing, 1);
  644. EXPECT_FALSE(pref_service()
  645. ->GetString(prefs::kPendingHintsProcessingVersion)
  646. .empty());
  647. }
  648. // Now verify config is processed for different version and pref cleared.
  649. {
  650. base::HistogramTester histogram_tester;
  651. InitializeWithDefaultConfig("3.0.0");
  652. EXPECT_TRUE(pref_service()
  653. ->GetString(prefs::kPendingHintsProcessingVersion)
  654. .empty());
  655. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  656. ProcessHintsComponentResult::kSuccess,
  657. 1);
  658. }
  659. }
  660. TEST_F(HintsManagerTest,
  661. ProcessHintsWithExistingPrefDoesNotClearOrCountAsMidProcessing) {
  662. // Write hints processing pref for version 2.0.0.
  663. pref_service()->SetString(prefs::kPendingHintsProcessingVersion, "2.0.0");
  664. CreateHintsManager(/*top_host_provider=*/nullptr);
  665. // Verify component for same version counts as "failed".
  666. base::HistogramTester histogram_tester;
  667. InitializeWithDefaultConfig("2.0.0", /*should_wait=*/false);
  668. hints_manager()->Shutdown();
  669. histogram_tester.ExpectUniqueSample(
  670. "OptimizationGuide.ProcessHintsResult",
  671. ProcessHintsComponentResult::kFailedFinishProcessing, 1);
  672. // Verify that pref still not cleared at shutdown and was not counted as
  673. // mid-processing.
  674. histogram_tester.ExpectUniqueSample(
  675. "OptimizationGuide.ProcessingComponentAtShutdown", false, 1);
  676. EXPECT_FALSE(
  677. pref_service()->GetString(prefs::kPendingHintsProcessingVersion).empty());
  678. }
  679. TEST_F(HintsManagerTest, ProcessHintsWithInvalidPref) {
  680. // Create pref file with invalid version.
  681. pref_service()->SetString(prefs::kPendingHintsProcessingVersion, "bad-2.0.0");
  682. CreateHintsManager(/*top_host_provider=*/nullptr);
  683. // Verify config is processed with pref cleared.
  684. {
  685. base::HistogramTester histogram_tester;
  686. InitializeWithDefaultConfig("2.0.0");
  687. EXPECT_TRUE(pref_service()
  688. ->GetString(prefs::kPendingHintsProcessingVersion)
  689. .empty());
  690. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  691. ProcessHintsComponentResult::kSuccess,
  692. 1);
  693. }
  694. }
  695. TEST_F(HintsManagerTest,
  696. OnNavigationStartOrRedirectNoTypesRegisteredShouldNotLoadHint) {
  697. base::HistogramTester histogram_tester;
  698. InitializeWithDefaultConfig("3.0.0.0");
  699. auto navigation_data = CreateTestNavigationData(url_with_hints(), {});
  700. base::RunLoop run_loop;
  701. CallOnNavigationStartOrRedirect(navigation_data.get(),
  702. run_loop.QuitClosure());
  703. run_loop.Run();
  704. histogram_tester.ExpectTotalCount("OptimizationGuide.LoadedHint.Result", 0);
  705. }
  706. TEST_F(HintsManagerTest, OnNavigationStartOrRedirectWithHint) {
  707. base::HistogramTester histogram_tester;
  708. InitializeWithDefaultConfig("3.0.0.0");
  709. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  710. auto navigation_data = CreateTestNavigationData(url_with_hints(), {});
  711. base::RunLoop run_loop;
  712. CallOnNavigationStartOrRedirect(navigation_data.get(),
  713. run_loop.QuitClosure());
  714. run_loop.Run();
  715. histogram_tester.ExpectUniqueSample("OptimizationGuide.LoadedHint.Result",
  716. true, 1);
  717. }
  718. TEST_F(HintsManagerTest, OnNavigationStartOrRedirectNoHint) {
  719. base::HistogramTester histogram_tester;
  720. InitializeWithDefaultConfig("3.0.0.0");
  721. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  722. auto navigation_data =
  723. CreateTestNavigationData(GURL("https://notinhints.com"), {});
  724. base::RunLoop run_loop;
  725. CallOnNavigationStartOrRedirect(navigation_data.get(),
  726. run_loop.QuitClosure());
  727. run_loop.Run();
  728. histogram_tester.ExpectUniqueSample("OptimizationGuide.LoadedHint.Result",
  729. false, 1);
  730. }
  731. TEST_F(HintsManagerTest, OnNavigationStartOrRedirectNoHost) {
  732. base::HistogramTester histogram_tester;
  733. InitializeWithDefaultConfig("3.0.0.0");
  734. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  735. auto navigation_data = CreateTestNavigationData(GURL("blargh"), {});
  736. base::RunLoop run_loop;
  737. CallOnNavigationStartOrRedirect(navigation_data.get(),
  738. run_loop.QuitClosure());
  739. run_loop.Run();
  740. histogram_tester.ExpectTotalCount("OptimizationGuide.LoadedHint.Result", 0);
  741. }
  742. TEST_F(HintsManagerTest, OptimizationFiltersAreOnlyLoadedIfTypeIsRegistered) {
  743. proto::Configuration config;
  744. BloomFilter bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  745. kDefaultHostBloomFilterNumBits);
  746. PopulateBloomFilterWithDefaultHost(&bloom_filter);
  747. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, bloom_filter,
  748. kDefaultHostBloomFilterNumHashFunctions,
  749. kDefaultHostBloomFilterNumBits,
  750. /*is_allowlist=*/false, &config);
  751. AddBloomFilterToConfig(proto::NOSCRIPT, bloom_filter,
  752. kDefaultHostBloomFilterNumHashFunctions,
  753. kDefaultHostBloomFilterNumBits,
  754. /*is_allowlist=*/false, &config);
  755. AddBloomFilterToConfig(proto::DEFER_ALL_SCRIPT, bloom_filter,
  756. kDefaultHostBloomFilterNumHashFunctions,
  757. kDefaultHostBloomFilterNumBits,
  758. /*is_allowlist=*/true, &config);
  759. {
  760. base::HistogramTester histogram_tester;
  761. ProcessHints(config, "1.0.0.0");
  762. histogram_tester.ExpectTotalCount(
  763. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", 0);
  764. histogram_tester.ExpectTotalCount(
  765. "OptimizationGuide.OptimizationFilterStatus.NoScript", 0);
  766. histogram_tester.ExpectTotalCount(
  767. "OptimizationGuide.OptimizationFilterStatus.DeferAllScript", 0);
  768. }
  769. // Now register the optimization type and see that it is loaded.
  770. {
  771. base::HistogramTester histogram_tester;
  772. base::RunLoop run_loop;
  773. hints_manager()->ListenForNextUpdateForTesting(run_loop.QuitClosure());
  774. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  775. run_loop.Run();
  776. histogram_tester.ExpectBucketCount(
  777. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  778. OptimizationFilterStatus::kFoundServerFilterConfig, 1);
  779. histogram_tester.ExpectBucketCount(
  780. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  781. OptimizationFilterStatus::kCreatedServerFilter, 1);
  782. histogram_tester.ExpectTotalCount(
  783. "OptimizationGuide.OptimizationFilterStatus.NoScript", 0);
  784. histogram_tester.ExpectTotalCount(
  785. "OptimizationGuide.OptimizationFilterStatus.DeferAllScript", 0);
  786. EXPECT_TRUE(hints_manager()->HasLoadedOptimizationBlocklist(
  787. proto::LITE_PAGE_REDIRECT));
  788. EXPECT_FALSE(
  789. hints_manager()->HasLoadedOptimizationBlocklist(proto::NOSCRIPT));
  790. EXPECT_FALSE(hints_manager()->HasLoadedOptimizationAllowlist(
  791. proto::DEFER_ALL_SCRIPT));
  792. }
  793. // Re-registering the same optimization type does not re-load the filter.
  794. {
  795. base::HistogramTester histogram_tester;
  796. base::RunLoop run_loop;
  797. hints_manager()->ListenForNextUpdateForTesting(run_loop.QuitClosure());
  798. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  799. run_loop.Run();
  800. histogram_tester.ExpectTotalCount(
  801. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", 0);
  802. histogram_tester.ExpectTotalCount(
  803. "OptimizationGuide.OptimizationFilterStatus.NoScript", 0);
  804. histogram_tester.ExpectTotalCount(
  805. "OptimizationGuide.OptimizationFilterStatus.DeferAllScript", 0);
  806. }
  807. // Registering a new optimization type without a filter does not trigger a
  808. // reload of the filter.
  809. {
  810. base::HistogramTester histogram_tester;
  811. base::RunLoop run_loop;
  812. hints_manager()->ListenForNextUpdateForTesting(run_loop.QuitClosure());
  813. hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS});
  814. run_loop.Run();
  815. histogram_tester.ExpectTotalCount(
  816. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", 0);
  817. histogram_tester.ExpectTotalCount(
  818. "OptimizationGuide.OptimizationFilterStatus.NoScript", 0);
  819. histogram_tester.ExpectTotalCount(
  820. "OptimizationGuide.OptimizationFilterStatus.DeferAllScript", 0);
  821. }
  822. // Registering a new optimization types with filters does trigger a
  823. // reload of the filters.
  824. {
  825. base::HistogramTester histogram_tester;
  826. base::RunLoop run_loop;
  827. hints_manager()->ListenForNextUpdateForTesting(run_loop.QuitClosure());
  828. hints_manager()->RegisterOptimizationTypes(
  829. {proto::NOSCRIPT, proto::DEFER_ALL_SCRIPT});
  830. run_loop.Run();
  831. histogram_tester.ExpectBucketCount(
  832. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  833. OptimizationFilterStatus::kFoundServerFilterConfig, 1);
  834. histogram_tester.ExpectBucketCount(
  835. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  836. OptimizationFilterStatus::kCreatedServerFilter, 1);
  837. histogram_tester.ExpectBucketCount(
  838. "OptimizationGuide.OptimizationFilterStatus.NoScript",
  839. OptimizationFilterStatus::kFoundServerFilterConfig, 1);
  840. histogram_tester.ExpectBucketCount(
  841. "OptimizationGuide.OptimizationFilterStatus.NoScript",
  842. OptimizationFilterStatus::kCreatedServerFilter, 1);
  843. histogram_tester.ExpectBucketCount(
  844. "OptimizationGuide.OptimizationFilterStatus.DeferAllScript",
  845. OptimizationFilterStatus::kFoundServerFilterConfig, 1);
  846. histogram_tester.ExpectBucketCount(
  847. "OptimizationGuide.OptimizationFilterStatus.DeferAllScript",
  848. OptimizationFilterStatus::kCreatedServerFilter, 1);
  849. EXPECT_TRUE(hints_manager()->HasLoadedOptimizationBlocklist(
  850. proto::LITE_PAGE_REDIRECT));
  851. EXPECT_TRUE(
  852. hints_manager()->HasLoadedOptimizationBlocklist(proto::NOSCRIPT));
  853. EXPECT_TRUE(hints_manager()->HasLoadedOptimizationAllowlist(
  854. proto::DEFER_ALL_SCRIPT));
  855. }
  856. }
  857. TEST_F(HintsManagerTest, OptimizationFiltersOnlyLoadOncePerType) {
  858. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  859. base::HistogramTester histogram_tester;
  860. proto::Configuration config;
  861. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  862. kDefaultHostBloomFilterNumBits);
  863. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  864. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  865. kDefaultHostBloomFilterNumHashFunctions,
  866. kDefaultHostBloomFilterNumBits,
  867. /*is_allowlist=*/false, &config);
  868. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  869. kDefaultHostBloomFilterNumHashFunctions,
  870. kDefaultHostBloomFilterNumBits,
  871. /*is_allowlist=*/false, &config);
  872. // Make sure it will only load one of an allowlist or a blocklist.
  873. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  874. kDefaultHostBloomFilterNumHashFunctions,
  875. kDefaultHostBloomFilterNumBits,
  876. /*is_allowlist=*/true, &config);
  877. ProcessHints(config, "1.0.0.0");
  878. // We found 2 LPR blocklists: parsed one and duped the other.
  879. histogram_tester.ExpectBucketCount(
  880. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  881. OptimizationFilterStatus::kFoundServerFilterConfig, 3);
  882. histogram_tester.ExpectBucketCount(
  883. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  884. OptimizationFilterStatus::kCreatedServerFilter, 1);
  885. histogram_tester.ExpectBucketCount(
  886. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  887. OptimizationFilterStatus::kFailedServerFilterDuplicateConfig, 2);
  888. }
  889. TEST_F(HintsManagerTest, InvalidOptimizationFilterNotLoaded) {
  890. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  891. base::HistogramTester histogram_tester;
  892. int too_many_bits = features::MaxServerBloomFilterByteSize() * 8 + 1;
  893. proto::Configuration config;
  894. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  895. too_many_bits);
  896. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  897. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  898. kDefaultHostBloomFilterNumHashFunctions, too_many_bits,
  899. /*is_allowlist=*/false, &config);
  900. ProcessHints(config, "1.0.0.0");
  901. histogram_tester.ExpectBucketCount(
  902. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  903. OptimizationFilterStatus::kFoundServerFilterConfig, 1);
  904. histogram_tester.ExpectBucketCount(
  905. "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect",
  906. OptimizationFilterStatus::kFailedServerFilterTooBig, 1);
  907. EXPECT_FALSE(hints_manager()->HasLoadedOptimizationBlocklist(
  908. proto::LITE_PAGE_REDIRECT));
  909. }
  910. TEST_F(HintsManagerTest, CanApplyOptimizationUrlWithNoHost) {
  911. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  912. proto::Configuration config;
  913. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  914. kDefaultHostBloomFilterNumBits);
  915. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  916. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  917. kDefaultHostBloomFilterNumHashFunctions,
  918. kDefaultHostBloomFilterNumBits,
  919. /*is_allowlist=*/false, &config);
  920. ProcessHints(config, "1.0.0.0");
  921. OptimizationTypeDecision optimization_type_decision =
  922. hints_manager()->CanApplyOptimization(GURL("urlwithnohost"),
  923. proto::LITE_PAGE_REDIRECT,
  924. /*optimization_metadata=*/nullptr);
  925. // Make sure decisions are logged correctly.
  926. EXPECT_EQ(OptimizationTypeDecision::kNoHintAvailable,
  927. optimization_type_decision);
  928. }
  929. TEST_F(HintsManagerTest, CanApplyOptimizationHasFilterForTypeButNotLoadedYet) {
  930. proto::Configuration config;
  931. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  932. kDefaultHostBloomFilterNumBits);
  933. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  934. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  935. kDefaultHostBloomFilterNumHashFunctions,
  936. kDefaultHostBloomFilterNumBits,
  937. /*is_allowlist=*/false, &config);
  938. ProcessHints(config, "1.0.0.0");
  939. // Append the switch for processing hints to force the filter to not get
  940. // loaded.
  941. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  942. switches::kHintsProtoOverride);
  943. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  944. OptimizationTypeDecision optimization_type_decision =
  945. hints_manager()->CanApplyOptimization(GURL("https://whatever.com/123"),
  946. proto::LITE_PAGE_REDIRECT,
  947. /*optimization_metadata=*/nullptr);
  948. EXPECT_EQ(OptimizationTypeDecision::kHadOptimizationFilterButNotLoadedInTime,
  949. optimization_type_decision);
  950. // Run until idle to ensure we don't crash because the test object has gone
  951. // away.
  952. RunUntilIdle();
  953. }
  954. TEST_F(HintsManagerTest,
  955. CanApplyOptimizationHasLoadedFilterForTypeUrlInAllowlist) {
  956. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  957. proto::Configuration config;
  958. BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  959. kDefaultHostBloomFilterNumBits);
  960. PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter);
  961. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter,
  962. kDefaultHostBloomFilterNumHashFunctions,
  963. kDefaultHostBloomFilterNumBits,
  964. /*is_allowlist=*/true, &config);
  965. ProcessHints(config, "1.0.0.0");
  966. OptimizationTypeDecision optimization_type_decision =
  967. hints_manager()->CanApplyOptimization(GURL("https://m.host.com/123"),
  968. proto::LITE_PAGE_REDIRECT,
  969. /*optimization_metadata=*/nullptr);
  970. EXPECT_EQ(OptimizationTypeDecision::kAllowedByOptimizationFilter,
  971. optimization_type_decision);
  972. }
  973. TEST_F(HintsManagerTest,
  974. CanApplyOptimizationHasLoadedFilterForTypeUrlInBlocklist) {
  975. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  976. proto::Configuration config;
  977. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  978. kDefaultHostBloomFilterNumBits);
  979. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  980. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  981. kDefaultHostBloomFilterNumHashFunctions,
  982. kDefaultHostBloomFilterNumBits,
  983. /*is_allowlist=*/false, &config);
  984. ProcessHints(config, "1.0.0.0");
  985. OptimizationTypeDecision optimization_type_decision =
  986. hints_manager()->CanApplyOptimization(GURL("https://m.host.com/123"),
  987. proto::LITE_PAGE_REDIRECT,
  988. /*optimization_metadata=*/nullptr);
  989. EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByOptimizationFilter,
  990. optimization_type_decision);
  991. }
  992. TEST_F(HintsManagerTest,
  993. CanApplyOptimizationHasLoadedFilterForTypeUrlNotInAllowlistFilter) {
  994. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  995. proto::Configuration config;
  996. BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  997. kDefaultHostBloomFilterNumBits);
  998. PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter);
  999. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter,
  1000. kDefaultHostBloomFilterNumHashFunctions,
  1001. kDefaultHostBloomFilterNumBits,
  1002. /*is_allowlist=*/true, &config);
  1003. ProcessHints(config, "1.0.0.0");
  1004. OptimizationTypeDecision optimization_type_decision =
  1005. hints_manager()->CanApplyOptimization(GURL("https://whatever.com/123"),
  1006. proto::LITE_PAGE_REDIRECT,
  1007. /*optimization_metadata=*/nullptr);
  1008. EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByOptimizationFilter,
  1009. optimization_type_decision);
  1010. }
  1011. TEST_F(HintsManagerTest,
  1012. CanApplyOptimizationHasLoadedFilterForTypeUrlNotInBlocklistFilter) {
  1013. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  1014. proto::Configuration config;
  1015. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  1016. kDefaultHostBloomFilterNumBits);
  1017. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  1018. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  1019. kDefaultHostBloomFilterNumHashFunctions,
  1020. kDefaultHostBloomFilterNumBits,
  1021. /*is_allowlist=*/false, &config);
  1022. ProcessHints(config, "1.0.0.0");
  1023. OptimizationTypeDecision optimization_type_decision =
  1024. hints_manager()->CanApplyOptimization(GURL("https://whatever.com/123"),
  1025. proto::LITE_PAGE_REDIRECT,
  1026. /*optimization_metadata=*/nullptr);
  1027. EXPECT_EQ(OptimizationTypeDecision::kAllowedByOptimizationFilter,
  1028. optimization_type_decision);
  1029. }
  1030. TEST_F(HintsManagerTest,
  1031. CanApplyOptimizationOptimizationTypeAllowlistedAtTopLevel) {
  1032. proto::Configuration config;
  1033. proto::Hint* hint1 = config.add_hints();
  1034. hint1->set_key("somedomain.org");
  1035. hint1->set_key_representation(proto::HOST);
  1036. hint1->set_version("someversion");
  1037. proto::Optimization* opt1 = hint1->add_allowlisted_optimizations();
  1038. opt1->set_optimization_type(proto::RESOURCE_LOADING);
  1039. ProcessHints(config, "1.0.0.0");
  1040. hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING});
  1041. auto navigation_data =
  1042. CreateTestNavigationData(url_with_hints(), {proto::RESOURCE_LOADING});
  1043. base::RunLoop run_loop;
  1044. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1045. run_loop.QuitClosure());
  1046. run_loop.Run();
  1047. OptimizationMetadata optimization_metadata;
  1048. OptimizationTypeDecision optimization_type_decision =
  1049. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1050. proto::RESOURCE_LOADING,
  1051. &optimization_metadata);
  1052. EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint,
  1053. optimization_type_decision);
  1054. }
  1055. TEST_F(HintsManagerTest, CanApplyOptimizationHasPageHintButNoMatchingOptType) {
  1056. InitializeWithDefaultConfig("1.0.0.0");
  1057. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1058. auto navigation_data =
  1059. CreateTestNavigationData(url_with_hints(), {proto::DEFER_ALL_SCRIPT});
  1060. base::RunLoop run_loop;
  1061. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1062. run_loop.QuitClosure());
  1063. run_loop.Run();
  1064. OptimizationTypeDecision optimization_type_decision =
  1065. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1066. proto::DEFER_ALL_SCRIPT,
  1067. /*optimization_metadata=*/nullptr);
  1068. EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByHint,
  1069. optimization_type_decision);
  1070. }
  1071. TEST_F(HintsManagerTest,
  1072. CanApplyOptimizationAndPopulatesPerformanceHintsMetadata) {
  1073. hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS});
  1074. proto::Configuration config;
  1075. proto::Hint* hint = config.add_hints();
  1076. hint->set_key("somedomain.org");
  1077. hint->set_key_representation(proto::HOST);
  1078. hint->set_version("someversion");
  1079. proto::PageHint* page_hint = hint->add_page_hints();
  1080. page_hint->set_page_pattern("/news/");
  1081. proto::Optimization* opt = page_hint->add_allowlisted_optimizations();
  1082. opt->set_optimization_type(proto::PERFORMANCE_HINTS);
  1083. proto::PerformanceHint* performance_hint =
  1084. opt->mutable_performance_hints_metadata()->add_performance_hints();
  1085. performance_hint->set_wildcard_pattern("somedomain.org");
  1086. performance_hint->set_performance_class(proto::PERFORMANCE_SLOW);
  1087. ProcessHints(config, "1.0.0.0");
  1088. base::RunLoop run_loop;
  1089. auto navigation_data =
  1090. CreateTestNavigationData(url_with_hints(), {proto::PERFORMANCE_HINTS});
  1091. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1092. run_loop.QuitClosure());
  1093. run_loop.Run();
  1094. OptimizationMetadata optimization_metadata;
  1095. OptimizationTypeDecision optimization_type_decision =
  1096. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1097. proto::PERFORMANCE_HINTS,
  1098. &optimization_metadata);
  1099. // Make sure performance hints metadata is populated.
  1100. EXPECT_TRUE(optimization_metadata.performance_hints_metadata().has_value());
  1101. EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint,
  1102. optimization_type_decision);
  1103. }
  1104. TEST_F(HintsManagerTest, CanApplyOptimizationAndPopulatesPublicImageMetadata) {
  1105. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  1106. proto::Configuration config;
  1107. proto::Hint* hint = config.add_hints();
  1108. hint->set_key("somedomain.org");
  1109. hint->set_key_representation(proto::HOST);
  1110. hint->set_version("someversion");
  1111. proto::PageHint* page_hint = hint->add_page_hints();
  1112. page_hint->set_page_pattern("/news/");
  1113. proto::Optimization* opt = page_hint->add_allowlisted_optimizations();
  1114. opt->set_optimization_type(proto::COMPRESS_PUBLIC_IMAGES);
  1115. opt->mutable_public_image_metadata()->add_url("someimage");
  1116. ProcessHints(config, "1.0.0.0");
  1117. auto navigation_data = CreateTestNavigationData(
  1118. url_with_hints(), {proto::COMPRESS_PUBLIC_IMAGES});
  1119. base::RunLoop run_loop;
  1120. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1121. run_loop.QuitClosure());
  1122. run_loop.Run();
  1123. OptimizationMetadata optimization_metadata;
  1124. OptimizationTypeDecision optimization_type_decision =
  1125. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1126. proto::COMPRESS_PUBLIC_IMAGES,
  1127. &optimization_metadata);
  1128. // Make sure public images metadata is populated.
  1129. EXPECT_TRUE(optimization_metadata.public_image_metadata().has_value());
  1130. EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint,
  1131. optimization_type_decision);
  1132. }
  1133. TEST_F(HintsManagerTest,
  1134. CanApplyOptimizationAndPopulatesLoadingPredictorMetadata) {
  1135. hints_manager()->RegisterOptimizationTypes({proto::LOADING_PREDICTOR});
  1136. proto::Configuration config;
  1137. proto::Hint* hint = config.add_hints();
  1138. hint->set_key("somedomain.org");
  1139. hint->set_key_representation(proto::HOST);
  1140. hint->set_version("someversion");
  1141. proto::PageHint* page_hint = hint->add_page_hints();
  1142. page_hint->set_page_pattern("/news/");
  1143. proto::Optimization* opt = page_hint->add_allowlisted_optimizations();
  1144. opt->set_optimization_type(proto::LOADING_PREDICTOR);
  1145. opt->mutable_loading_predictor_metadata()->add_subresources()->set_url(
  1146. "https://resource.com/");
  1147. ProcessHints(config, "1.0.0.0");
  1148. auto navigation_data =
  1149. CreateTestNavigationData(url_with_hints(), {proto::LOADING_PREDICTOR});
  1150. base::RunLoop run_loop;
  1151. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1152. run_loop.QuitClosure());
  1153. run_loop.Run();
  1154. OptimizationMetadata optimization_metadata;
  1155. OptimizationTypeDecision optimization_type_decision =
  1156. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1157. proto::LOADING_PREDICTOR,
  1158. &optimization_metadata);
  1159. // Make sure loading predictor metadata is populated.
  1160. EXPECT_TRUE(optimization_metadata.loading_predictor_metadata().has_value());
  1161. EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint,
  1162. optimization_type_decision);
  1163. }
  1164. TEST_F(HintsManagerTest, CanApplyOptimizationAndPopulatesAnyMetadata) {
  1165. hints_manager()->RegisterOptimizationTypes({proto::LOADING_PREDICTOR});
  1166. proto::Configuration config;
  1167. proto::Hint* hint = config.add_hints();
  1168. hint->set_key("somedomain.org");
  1169. hint->set_key_representation(proto::HOST);
  1170. hint->set_version("someversion");
  1171. proto::PageHint* page_hint = hint->add_page_hints();
  1172. page_hint->set_page_pattern("/news/");
  1173. proto::Optimization* opt = page_hint->add_allowlisted_optimizations();
  1174. opt->set_optimization_type(proto::LOADING_PREDICTOR);
  1175. proto::LoadingPredictorMetadata lp_metadata;
  1176. lp_metadata.add_subresources()->set_url("https://resource.com/");
  1177. lp_metadata.SerializeToString(opt->mutable_any_metadata()->mutable_value());
  1178. opt->mutable_any_metadata()->set_type_url(
  1179. "type.googleapis.com/com.foo.LoadingPredictorMetadata");
  1180. ProcessHints(config, "1.0.0.0");
  1181. auto navigation_data =
  1182. CreateTestNavigationData(url_with_hints(), {proto::LOADING_PREDICTOR});
  1183. base::RunLoop run_loop;
  1184. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1185. run_loop.QuitClosure());
  1186. run_loop.Run();
  1187. OptimizationMetadata optimization_metadata;
  1188. OptimizationTypeDecision optimization_type_decision =
  1189. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1190. proto::LOADING_PREDICTOR,
  1191. &optimization_metadata);
  1192. // Make sure loading predictor metadata is populated.
  1193. EXPECT_TRUE(
  1194. optimization_metadata.ParsedMetadata<proto::LoadingPredictorMetadata>()
  1195. .has_value());
  1196. EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint,
  1197. optimization_type_decision);
  1198. }
  1199. TEST_F(HintsManagerTest, CanApplyOptimizationNoMatchingPageHint) {
  1200. InitializeWithDefaultConfig("1.0.0.0");
  1201. hints_manager()->RegisterOptimizationTypes({proto::NOSCRIPT});
  1202. auto navigation_data =
  1203. CreateTestNavigationData(GURL("https://somedomain.org/nomatch"), {});
  1204. base::RunLoop run_loop;
  1205. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1206. run_loop.QuitClosure());
  1207. run_loop.Run();
  1208. OptimizationTypeDecision optimization_type_decision =
  1209. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1210. proto::NOSCRIPT,
  1211. /*optimization_metadata=*/nullptr);
  1212. EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByHint,
  1213. optimization_type_decision);
  1214. }
  1215. TEST_F(HintsManagerTest,
  1216. CanApplyOptimizationNoHintForNavigationMetadataClearedAnyway) {
  1217. InitializeWithDefaultConfig("1.0.0.0");
  1218. auto navigation_data = CreateTestNavigationData(
  1219. GURL("https://nohint.com"), {proto::COMPRESS_PUBLIC_IMAGES});
  1220. hints_manager()->RegisterOptimizationTypes({proto::NOSCRIPT});
  1221. OptimizationMetadata optimization_metadata;
  1222. proto::PerformanceHintsMetadata hints_metadata;
  1223. auto* hint = hints_metadata.add_performance_hints();
  1224. hint->set_wildcard_pattern("test.com");
  1225. hint->set_performance_class(proto::PERFORMANCE_SLOW);
  1226. OptimizationMetadata metadata;
  1227. optimization_metadata.set_performance_hints_metadata(hints_metadata);
  1228. OptimizationTypeDecision optimization_type_decision =
  1229. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1230. proto::NOSCRIPT,
  1231. &optimization_metadata);
  1232. EXPECT_FALSE(optimization_metadata.performance_hints_metadata().has_value());
  1233. EXPECT_EQ(OptimizationTypeDecision::kNoHintAvailable,
  1234. optimization_type_decision);
  1235. }
  1236. TEST_F(HintsManagerTest, CanApplyOptimizationHasHintInCacheButNotLoaded) {
  1237. InitializeWithDefaultConfig("1.0.0.0");
  1238. hints_manager()->RegisterOptimizationTypes({proto::NOSCRIPT});
  1239. OptimizationMetadata optimization_metadata;
  1240. OptimizationTypeDecision optimization_type_decision =
  1241. hints_manager()->CanApplyOptimization(url_with_hints(), proto::NOSCRIPT,
  1242. &optimization_metadata);
  1243. EXPECT_EQ(OptimizationTypeDecision::kHadHintButNotLoadedInTime,
  1244. optimization_type_decision);
  1245. }
  1246. TEST_F(HintsManagerTest, CanApplyOptimizationFilterTakesPrecedence) {
  1247. auto navigation_data = CreateTestNavigationData(
  1248. GURL("https://m.host.com/urlinfilterandhints"), {});
  1249. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  1250. proto::Configuration config;
  1251. proto::Hint* hint1 = config.add_hints();
  1252. hint1->set_key("host.com");
  1253. hint1->set_key_representation(proto::HOST);
  1254. hint1->set_version("someversion");
  1255. proto::PageHint* page_hint1 = hint1->add_page_hints();
  1256. page_hint1->set_page_pattern("https://m.host.com");
  1257. proto::Optimization* optimization1 =
  1258. page_hint1->add_allowlisted_optimizations();
  1259. optimization1->set_optimization_type(proto::LITE_PAGE_REDIRECT);
  1260. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  1261. kDefaultHostBloomFilterNumBits);
  1262. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  1263. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  1264. kDefaultHostBloomFilterNumHashFunctions,
  1265. kDefaultHostBloomFilterNumBits,
  1266. /*is_allowlist=*/false, &config);
  1267. ProcessHints(config, "1.0.0.0");
  1268. base::RunLoop run_loop;
  1269. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1270. run_loop.QuitClosure());
  1271. run_loop.Run();
  1272. OptimizationTypeDecision optimization_type_decision =
  1273. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1274. proto::LITE_PAGE_REDIRECT,
  1275. /*optimization_metadata=*/nullptr);
  1276. // Make sure decision points logged correctly.
  1277. EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByOptimizationFilter,
  1278. optimization_type_decision);
  1279. }
  1280. TEST_F(HintsManagerTest,
  1281. CanApplyOptimizationFilterTakesPrecedenceMatchesFilter) {
  1282. auto navigation_data =
  1283. CreateTestNavigationData(GURL("https://notfiltered.com/whatever"),
  1284. {proto::COMPRESS_PUBLIC_IMAGES});
  1285. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  1286. proto::Configuration config;
  1287. proto::Hint* hint1 = config.add_hints();
  1288. hint1->set_key("notfiltered.com");
  1289. hint1->set_key_representation(proto::HOST);
  1290. hint1->set_version("someversion");
  1291. proto::PageHint* page_hint1 = hint1->add_page_hints();
  1292. page_hint1->set_page_pattern("https://notfiltered.com");
  1293. proto::Optimization* optimization1 =
  1294. page_hint1->add_allowlisted_optimizations();
  1295. optimization1->set_optimization_type(proto::LITE_PAGE_REDIRECT);
  1296. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  1297. kDefaultHostBloomFilterNumBits);
  1298. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  1299. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  1300. kDefaultHostBloomFilterNumHashFunctions,
  1301. kDefaultHostBloomFilterNumBits,
  1302. /*is_allowlist=*/false, &config);
  1303. ProcessHints(config, "1.0.0.0");
  1304. base::RunLoop run_loop;
  1305. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1306. run_loop.QuitClosure());
  1307. run_loop.Run();
  1308. OptimizationTypeDecision optimization_type_decision =
  1309. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1310. proto::LITE_PAGE_REDIRECT,
  1311. /*optimization_metadata=*/nullptr);
  1312. EXPECT_EQ(OptimizationTypeDecision::kAllowedByOptimizationFilter,
  1313. optimization_type_decision);
  1314. }
  1315. class HintsManagerFetchingDisabledTest : public HintsManagerTest {
  1316. public:
  1317. HintsManagerFetchingDisabledTest() {
  1318. scoped_list_.InitAndDisableFeature(
  1319. features::kRemoteOptimizationGuideFetching);
  1320. }
  1321. private:
  1322. base::test::ScopedFeatureList scoped_list_;
  1323. };
  1324. TEST_F(HintsManagerFetchingDisabledTest,
  1325. HintsFetchNotAllowedIfFeatureIsNotEnabled) {
  1326. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1327. switches::kDisableCheckingUserPermissionsForTesting);
  1328. std::unique_ptr<FakeTopHostProvider> top_host_provider =
  1329. std::make_unique<FakeTopHostProvider>(
  1330. std::vector<std::string>({"example1.com", "example2.com"}));
  1331. CreateHintsManager(top_host_provider.get());
  1332. InitializeWithDefaultConfig("1.0.0");
  1333. // Force timer to expire and schedule a hints fetch.
  1334. MoveClockForwardBy(base::Seconds(kUpdateFetchHintsTimeSecs));
  1335. EXPECT_EQ(0, top_host_provider->get_num_top_hosts_called());
  1336. // Hints fetcher should not even be created.
  1337. EXPECT_FALSE(active_tabs_batch_update_hints_fetcher());
  1338. }
  1339. TEST_F(HintsManagerTest,
  1340. CanApplyOptimizationAsyncReturnsRightAwayIfNotAllowedToFetch) {
  1341. base::HistogramTester histogram_tester;
  1342. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  1343. InitializeWithDefaultConfig("1.0.0.0");
  1344. auto navigation_data = CreateTestNavigationData(
  1345. url_without_hints(), {proto::COMPRESS_PUBLIC_IMAGES});
  1346. hints_manager()->CanApplyOptimizationAsync(
  1347. url_without_hints(), proto::COMPRESS_PUBLIC_IMAGES,
  1348. base::BindOnce([](OptimizationGuideDecision decision,
  1349. const OptimizationMetadata& metadata) {
  1350. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  1351. }));
  1352. RunUntilIdle();
  1353. histogram_tester.ExpectUniqueSample(
  1354. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  1355. OptimizationTypeDecision::kNoHintAvailable, 1);
  1356. }
  1357. TEST_F(
  1358. HintsManagerTest,
  1359. CanApplyOptimizationAsyncReturnsRightAwayIfNotAllowedToFetchAndNotAllowlistedByAvailableHint) {
  1360. base::HistogramTester histogram_tester;
  1361. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  1362. InitializeWithDefaultConfig("1.0.0.0");
  1363. auto navigation_data = CreateTestNavigationData(
  1364. url_with_hints(), {proto::COMPRESS_PUBLIC_IMAGES});
  1365. // Wait for hint to be loaded.
  1366. base::RunLoop run_loop;
  1367. CallOnNavigationStartOrRedirect(navigation_data.get(),
  1368. run_loop.QuitClosure());
  1369. run_loop.Run();
  1370. hints_manager()->CanApplyOptimizationAsync(
  1371. url_with_hints(), proto::COMPRESS_PUBLIC_IMAGES,
  1372. base::BindOnce([](OptimizationGuideDecision decision,
  1373. const OptimizationMetadata& metadata) {
  1374. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  1375. }));
  1376. RunUntilIdle();
  1377. histogram_tester.ExpectUniqueSample(
  1378. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  1379. OptimizationTypeDecision::kNotAllowedByHint, 1);
  1380. }
  1381. TEST_F(HintsManagerTest, RemoveFetchedEntriesByHintKeys_Host) {
  1382. int cache_duration_in_secs = 60;
  1383. GURL url("https://host.com/r/cats");
  1384. std::unique_ptr<proto::GetHintsResponse> get_hints_response =
  1385. std::make_unique<proto::GetHintsResponse>();
  1386. proto::Hint* hint = get_hints_response->add_hints();
  1387. hint->set_key(url.spec());
  1388. hint->set_key_representation(proto::FULL_URL);
  1389. hint->mutable_max_cache_duration()->set_seconds(cache_duration_in_secs);
  1390. proto::PageHint* page_hint = hint->add_page_hints();
  1391. page_hint->add_allowlisted_optimizations()->set_optimization_type(
  1392. proto::PERFORMANCE_HINTS);
  1393. page_hint->set_page_pattern("whatever/*");
  1394. hint = get_hints_response->add_hints();
  1395. hint->set_key_representation(proto::HOST);
  1396. hint->set_key(url.host());
  1397. page_hint = hint->add_page_hints();
  1398. page_hint->set_page_pattern("anything/*");
  1399. std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
  1400. hints_manager()->hint_cache()->UpdateFetchedHints(
  1401. std::move(get_hints_response), base::Time().Now(), {url.host()}, {url},
  1402. run_loop->QuitClosure());
  1403. EXPECT_TRUE(hints_manager()->hint_cache()->HasHint(url.host()));
  1404. EXPECT_TRUE(hints_manager()->hint_cache()->HasURLKeyedEntryForURL(url));
  1405. run_loop = std::make_unique<base::RunLoop>();
  1406. hints_manager()->RemoveFetchedEntriesByHintKeys(
  1407. run_loop->QuitClosure(), proto::KeyRepresentation::HOST, {url.host()});
  1408. run_loop->Run();
  1409. EXPECT_FALSE(hints_manager()->hint_cache()->HasHint(url.host()));
  1410. EXPECT_TRUE(hints_manager()->hint_cache()->HasURLKeyedEntryForURL(url));
  1411. }
  1412. TEST_F(HintsManagerTest, RemoveFetchedEntriesByHintKeys_URL) {
  1413. int cache_duration_in_secs = 60;
  1414. GURL url("https://host.com/r/cats");
  1415. std::unique_ptr<proto::GetHintsResponse> get_hints_response =
  1416. std::make_unique<proto::GetHintsResponse>();
  1417. proto::Hint* hint = get_hints_response->add_hints();
  1418. hint->set_key(url.spec());
  1419. hint->set_key_representation(proto::FULL_URL);
  1420. hint->mutable_max_cache_duration()->set_seconds(cache_duration_in_secs);
  1421. proto::PageHint* page_hint = hint->add_page_hints();
  1422. page_hint->add_allowlisted_optimizations()->set_optimization_type(
  1423. proto::PERFORMANCE_HINTS);
  1424. page_hint->set_page_pattern("whatever/*");
  1425. hint = get_hints_response->add_hints();
  1426. hint->set_key_representation(proto::HOST);
  1427. hint->set_key(url.host());
  1428. page_hint = hint->add_page_hints();
  1429. page_hint->set_page_pattern("anything/*");
  1430. std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
  1431. hints_manager()->hint_cache()->UpdateFetchedHints(
  1432. std::move(get_hints_response), base::Time().Now(), {url.host()}, {url},
  1433. run_loop->QuitClosure());
  1434. EXPECT_TRUE(hints_manager()->hint_cache()->HasHint(url.host()));
  1435. EXPECT_TRUE(hints_manager()->hint_cache()->HasURLKeyedEntryForURL(url));
  1436. run_loop = std::make_unique<base::RunLoop>();
  1437. hints_manager()->RemoveFetchedEntriesByHintKeys(
  1438. run_loop->QuitClosure(), proto::KeyRepresentation::FULL_URL,
  1439. {url.spec()});
  1440. run_loop->Run();
  1441. // Both the host and url entries should have been removed to support upgrading
  1442. // hint keys from HOST to FULL_URL.
  1443. EXPECT_FALSE(hints_manager()->hint_cache()->HasHint(url.host()));
  1444. EXPECT_FALSE(hints_manager()->hint_cache()->HasURLKeyedEntryForURL(url));
  1445. }
  1446. TEST_F(HintsManagerTest, HintFetcherPrefUpdated_URL) {
  1447. base::Time expiry = base::Time::Now() + base::Hours(1);
  1448. HintsFetcher::AddFetchedHostForTesting(pref_service(), "host-key.com",
  1449. expiry);
  1450. HintsFetcher::AddFetchedHostForTesting(pref_service(), "url-key.com", expiry);
  1451. ASSERT_TRUE(
  1452. HintsFetcher::WasHostCoveredByFetch(pref_service(), "host-key.com"));
  1453. ASSERT_TRUE(
  1454. HintsFetcher::WasHostCoveredByFetch(pref_service(), "url-key.com"));
  1455. std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
  1456. hints_manager()->RemoveFetchedEntriesByHintKeys(
  1457. run_loop->QuitClosure(), proto::KeyRepresentation::FULL_URL,
  1458. {
  1459. GURL("https://host-key.com/page").spec(),
  1460. GURL("https://url-key.com/page").spec(),
  1461. });
  1462. run_loop->Run();
  1463. EXPECT_FALSE(
  1464. HintsFetcher::WasHostCoveredByFetch(pref_service(), "host-key.com"));
  1465. EXPECT_FALSE(
  1466. HintsFetcher::WasHostCoveredByFetch(pref_service(), "url-key.com"));
  1467. }
  1468. TEST_F(HintsManagerTest, HintFetcherPrefUpdated_Hosts) {
  1469. base::Time expiry = base::Time::Now() + base::Hours(1);
  1470. HintsFetcher::AddFetchedHostForTesting(pref_service(), "host-key.com",
  1471. expiry);
  1472. HintsFetcher::AddFetchedHostForTesting(pref_service(), "url-key.com", expiry);
  1473. ASSERT_TRUE(
  1474. HintsFetcher::WasHostCoveredByFetch(pref_service(), "host-key.com"));
  1475. ASSERT_TRUE(
  1476. HintsFetcher::WasHostCoveredByFetch(pref_service(), "url-key.com"));
  1477. std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
  1478. hints_manager()->RemoveFetchedEntriesByHintKeys(
  1479. run_loop->QuitClosure(), proto::KeyRepresentation::HOST,
  1480. {
  1481. "host-key.com",
  1482. "url-key.com",
  1483. });
  1484. run_loop->Run();
  1485. EXPECT_FALSE(
  1486. HintsFetcher::WasHostCoveredByFetch(pref_service(), "host-key.com"));
  1487. EXPECT_FALSE(
  1488. HintsFetcher::WasHostCoveredByFetch(pref_service(), "url-key.com"));
  1489. }
  1490. class HintsManagerFetchingTest : public HintsManagerTest {
  1491. public:
  1492. HintsManagerFetchingTest() {
  1493. scoped_list_.InitWithFeaturesAndParameters(
  1494. {
  1495. {
  1496. features::kRemoteOptimizationGuideFetching,
  1497. {{"max_concurrent_page_navigation_fetches", "2"},
  1498. {"max_concurrent_batch_update_fetches", "2"}},
  1499. },
  1500. },
  1501. {features::kRemoteOptimizationGuideFetchingAnonymousDataConsent});
  1502. }
  1503. private:
  1504. variations::ScopedVariationsIdsProvider scoped_variations_ids_provider_{
  1505. variations::VariationsIdsProvider::Mode::kUseSignedInState};
  1506. base::test::ScopedFeatureList scoped_list_;
  1507. };
  1508. TEST_F(HintsManagerFetchingTest,
  1509. HintsFetchNotAllowedIfFeatureIsEnabledButUserNotAllowed) {
  1510. base::CommandLine::ForCurrentProcess()->RemoveSwitch(
  1511. switches::kDisableCheckingUserPermissionsForTesting);
  1512. CreateHintsManager(/*top_host_provider=*/nullptr);
  1513. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1514. hints_manager()->SetHintsFetcherFactoryForTesting(
  1515. BuildTestHintsFetcherFactory(
  1516. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  1517. InitializeWithDefaultConfig("1.0.0");
  1518. // Force timer to expire and schedule a hints fetch.
  1519. MoveClockForwardBy(base::Seconds(kUpdateFetchHintsTimeSecs));
  1520. // Hints fetcher should not even be created.
  1521. EXPECT_FALSE(active_tabs_batch_update_hints_fetcher());
  1522. }
  1523. TEST_F(HintsManagerFetchingTest,
  1524. NoRegisteredOptimizationTypesAndHintsFetchNotAttempted) {
  1525. std::unique_ptr<FakeTopHostProvider> top_host_provider =
  1526. std::make_unique<FakeTopHostProvider>(
  1527. std::vector<std::string>({"example1.com", "example2.com"}));
  1528. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1529. switches::kDisableCheckingUserPermissionsForTesting);
  1530. CreateHintsManager(top_host_provider.get());
  1531. hints_manager()->SetHintsFetcherFactoryForTesting(
  1532. BuildTestHintsFetcherFactory(
  1533. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  1534. InitializeWithDefaultConfig("1.0.0");
  1535. // Force timer to expire and schedule a hints fetch but the fetch is not made.
  1536. MoveClockForwardBy(base::Seconds(kUpdateFetchHintsTimeSecs));
  1537. EXPECT_EQ(0, top_host_provider->get_num_top_hosts_called());
  1538. // Hints fetcher should not even be created.
  1539. EXPECT_FALSE(active_tabs_batch_update_hints_fetcher());
  1540. }
  1541. TEST_F(HintsManagerFetchingTest,
  1542. OnlyFilterTypesRegisteredHintsFetchNotAttempted) {
  1543. proto::Configuration config;
  1544. BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  1545. kDefaultHostBloomFilterNumBits);
  1546. PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter);
  1547. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter,
  1548. kDefaultHostBloomFilterNumHashFunctions,
  1549. kDefaultHostBloomFilterNumBits,
  1550. /*is_allowlist=*/true, &config);
  1551. std::unique_ptr<FakeTopHostProvider> top_host_provider =
  1552. std::make_unique<FakeTopHostProvider>(
  1553. std::vector<std::string>({"example1.com", "example2.com"}));
  1554. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1555. switches::kDisableCheckingUserPermissionsForTesting);
  1556. CreateHintsManager(top_host_provider.get());
  1557. ProcessHints(config, "1.0.0.0");
  1558. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  1559. hints_manager()->SetHintsFetcherFactoryForTesting(
  1560. BuildTestHintsFetcherFactory(
  1561. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  1562. // Force timer to expire after random delay and schedule a hints fetch.
  1563. MoveClockForwardBy(base::Seconds(60 * 2));
  1564. EXPECT_EQ(0, top_host_provider->get_num_top_hosts_called());
  1565. // Hints fetcher should not even be created.
  1566. EXPECT_FALSE(active_tabs_batch_update_hints_fetcher());
  1567. }
  1568. TEST_F(HintsManagerFetchingTest, HintsFetcherEnabledNoHostsOrUrlsToFetch) {
  1569. auto scoped_feature_list = SetUpDeferStartupActiveTabsHintsFetch(false);
  1570. base::HistogramTester histogram_tester;
  1571. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1572. switches::kDisableCheckingUserPermissionsForTesting);
  1573. std::unique_ptr<FakeTopHostProvider> top_host_provider =
  1574. std::make_unique<FakeTopHostProvider>(std::vector<std::string>({}));
  1575. CreateHintsManager(top_host_provider.get());
  1576. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1577. hints_manager()->SetHintsFetcherFactoryForTesting(
  1578. BuildTestHintsFetcherFactory(
  1579. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  1580. InitializeWithDefaultConfig("1.0.0");
  1581. // No hints fetch should happen on startup.
  1582. RunUntilIdle();
  1583. histogram_tester.ExpectTotalCount(
  1584. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 0);
  1585. // Force timer to expire after random delay and schedule a hints fetch.
  1586. MoveClockForwardBy(base::Seconds(60 * 2));
  1587. EXPECT_EQ(1, top_host_provider->get_num_top_hosts_called());
  1588. EXPECT_EQ(1, tab_url_provider()->get_num_urls_called());
  1589. // Hints fetcher should not even be created.
  1590. EXPECT_FALSE(active_tabs_batch_update_hints_fetcher());
  1591. // Move it forward again to make sure timer is scheduled.
  1592. MoveClockForwardBy(base::Seconds(kUpdateFetchHintsTimeSecs));
  1593. EXPECT_EQ(2, top_host_provider->get_num_top_hosts_called());
  1594. EXPECT_EQ(2, tab_url_provider()->get_num_urls_called());
  1595. // Hints fetcher should not even be created.
  1596. EXPECT_FALSE(active_tabs_batch_update_hints_fetcher());
  1597. }
  1598. TEST_F(HintsManagerFetchingTest, HintsFetcherEnabledNoHostsButHasUrlsToFetch) {
  1599. auto scoped_feature_list = SetUpDeferStartupActiveTabsHintsFetch(false);
  1600. base::HistogramTester histogram_tester;
  1601. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1602. switches::kDisableCheckingUserPermissionsForTesting);
  1603. std::unique_ptr<FakeTopHostProvider> top_host_provider =
  1604. std::make_unique<FakeTopHostProvider>(std::vector<std::string>({}));
  1605. CreateHintsManager(top_host_provider.get());
  1606. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1607. hints_manager()->SetHintsFetcherFactoryForTesting(
  1608. BuildTestHintsFetcherFactory(
  1609. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  1610. InitializeWithDefaultConfig("1.0.0");
  1611. tab_url_provider()->SetUrls(
  1612. {GURL("https://a.com"), GURL("https://b.com"), GURL("chrome://new-tab")});
  1613. // No hints fetch should happen on startup.
  1614. RunUntilIdle();
  1615. histogram_tester.ExpectTotalCount(
  1616. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 0);
  1617. // Force timer to expire after random delay and schedule a hints fetch that
  1618. // succeeds.
  1619. MoveClockForwardBy(base::Seconds(60 * 2));
  1620. EXPECT_EQ(1, top_host_provider->get_num_top_hosts_called());
  1621. EXPECT_EQ(1, tab_url_provider()->get_num_urls_called());
  1622. EXPECT_EQ(1,
  1623. active_tabs_batch_update_hints_fetcher()->num_fetches_requested());
  1624. EXPECT_EQ("en-US",
  1625. active_tabs_batch_update_hints_fetcher()->locale_requested());
  1626. EXPECT_EQ(
  1627. proto::RequestContext::CONTEXT_BATCH_UPDATE_ACTIVE_TABS,
  1628. active_tabs_batch_update_hints_fetcher()->request_context_requested());
  1629. histogram_tester.ExpectBucketCount(
  1630. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 2, 1);
  1631. // Move it forward again to make sure timer is scheduled.
  1632. MoveClockForwardBy(base::Seconds(kUpdateFetchHintsTimeSecs));
  1633. EXPECT_EQ(2, top_host_provider->get_num_top_hosts_called());
  1634. EXPECT_EQ(2, tab_url_provider()->get_num_urls_called());
  1635. // Urls didn't change and we have all URLs cached in store.
  1636. EXPECT_EQ(1,
  1637. active_tabs_batch_update_hints_fetcher()->num_fetches_requested());
  1638. histogram_tester.ExpectBucketCount(
  1639. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 0, 1);
  1640. }
  1641. // Verifies hints for active tab URLs is not fetched immediately on startup. It
  1642. // should be fetched after a random delay for the first time, and then continue
  1643. // to be fetched.
  1644. TEST_F(HintsManagerFetchingTest, HintsFetcherTimerFetchOnStartup) {
  1645. auto scoped_feature_list = SetUpDeferStartupActiveTabsHintsFetch(false);
  1646. base::HistogramTester histogram_tester;
  1647. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1648. switches::kDisableCheckingUserPermissionsForTesting);
  1649. std::unique_ptr<FakeTopHostProvider> top_host_provider =
  1650. std::make_unique<FakeTopHostProvider>(std::vector<std::string>({}));
  1651. CreateHintsManager(top_host_provider.get());
  1652. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1653. hints_manager()->SetHintsFetcherFactoryForTesting(
  1654. BuildTestHintsFetcherFactory(
  1655. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  1656. InitializeWithDefaultConfig("1.0.0");
  1657. tab_url_provider()->SetUrls(
  1658. {GURL("https://a.com"), GURL("https://b.com"), GURL("chrome://new-tab")});
  1659. // No hints fetch should happen on startup.
  1660. RunUntilIdle();
  1661. histogram_tester.ExpectTotalCount(
  1662. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 0);
  1663. EXPECT_FALSE(active_tabs_batch_update_hints_fetcher());
  1664. EXPECT_EQ(0, tab_url_provider()->get_num_urls_called());
  1665. // Force timer to expire after random delay and schedule a hints fetch that
  1666. // succeeds.
  1667. MoveClockForwardBy(base::Seconds(60 * 2));
  1668. histogram_tester.ExpectBucketCount(
  1669. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 2, 1);
  1670. EXPECT_EQ(1, tab_url_provider()->get_num_urls_called());
  1671. EXPECT_EQ(1,
  1672. active_tabs_batch_update_hints_fetcher()->num_fetches_requested());
  1673. // Move it forward again to make sure timer is scheduled.
  1674. MoveClockForwardBy(base::Seconds(kUpdateFetchHintsTimeSecs));
  1675. histogram_tester.ExpectBucketCount(
  1676. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 0, 1);
  1677. EXPECT_EQ(2, tab_url_provider()->get_num_urls_called());
  1678. EXPECT_EQ(1,
  1679. active_tabs_batch_update_hints_fetcher()->num_fetches_requested());
  1680. }
  1681. // Verifies the deferred startup mode that fetches hints for active tab URLs on
  1682. // deferred startup (but not on immediate startup). It should continue to be
  1683. // fetched after a refresh duration.
  1684. TEST_F(HintsManagerFetchingTest, HintsFetcherDeferredStartup) {
  1685. auto scoped_feature_list = SetUpDeferStartupActiveTabsHintsFetch(true);
  1686. base::HistogramTester histogram_tester;
  1687. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1688. switches::kDisableCheckingUserPermissionsForTesting);
  1689. std::unique_ptr<FakeTopHostProvider> top_host_provider =
  1690. std::make_unique<FakeTopHostProvider>(std::vector<std::string>({}));
  1691. CreateHintsManager(top_host_provider.get());
  1692. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1693. hints_manager()->SetHintsFetcherFactoryForTesting(
  1694. BuildTestHintsFetcherFactory(
  1695. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  1696. InitializeWithDefaultConfig("1.0.0");
  1697. tab_url_provider()->SetUrls(
  1698. {GURL("https://a.com"), GURL("https://b.com"), GURL("chrome://new-tab")});
  1699. // No hints fetch should happen on startup.
  1700. RunUntilIdle();
  1701. histogram_tester.ExpectTotalCount(
  1702. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 0);
  1703. EXPECT_EQ(0, tab_url_provider()->get_num_urls_called());
  1704. // Hints fetch should be triggered on deferred startup.
  1705. hints_manager()->OnDeferredStartup();
  1706. RunUntilIdle();
  1707. histogram_tester.ExpectBucketCount(
  1708. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 2, 1);
  1709. EXPECT_EQ(1, tab_url_provider()->get_num_urls_called());
  1710. EXPECT_EQ(1,
  1711. active_tabs_batch_update_hints_fetcher()->num_fetches_requested());
  1712. // Move it forward again to make sure timer is scheduled.
  1713. MoveClockForwardBy(base::Seconds(kUpdateFetchHintsTimeSecs));
  1714. histogram_tester.ExpectBucketCount(
  1715. "OptimizationGuide.HintsManager.ActiveTabUrlsToFetchFor", 0, 1);
  1716. EXPECT_EQ(2, tab_url_provider()->get_num_urls_called());
  1717. EXPECT_EQ(1,
  1718. active_tabs_batch_update_hints_fetcher()->num_fetches_requested());
  1719. }
  1720. TEST_F(HintsManagerFetchingTest,
  1721. HintsFetched_RegisteredOptimizationTypes_AllWithOptFilter) {
  1722. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1723. switches::kDisableCheckingUserPermissionsForTesting);
  1724. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  1725. proto::Configuration config;
  1726. BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  1727. kDefaultHostBloomFilterNumBits);
  1728. PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter);
  1729. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter,
  1730. kDefaultHostBloomFilterNumHashFunctions,
  1731. kDefaultHostBloomFilterNumBits,
  1732. /*is_allowlist=*/true, &config);
  1733. ProcessHints(config, "1.0.0.0");
  1734. auto navigation_data = CreateTestNavigationData(url_without_hints(),
  1735. {proto::LITE_PAGE_REDIRECT});
  1736. base::HistogramTester histogram_tester;
  1737. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1738. RunUntilIdle();
  1739. histogram_tester.ExpectTotalCount(
  1740. "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 0);
  1741. histogram_tester.ExpectTotalCount(
  1742. "OptimizationGuide.HintsFetcher.GetHintsRequest.UrlCount", 0);
  1743. histogram_tester.ExpectTotalCount(
  1744. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", 0);
  1745. }
  1746. TEST_F(HintsManagerFetchingTest, HintsFetchedAtNavigationTime) {
  1747. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1748. switches::kDisableCheckingUserPermissionsForTesting);
  1749. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1750. InitializeWithDefaultConfig("1.0.0.0");
  1751. auto navigation_data =
  1752. CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT});
  1753. base::HistogramTester histogram_tester;
  1754. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1755. RunUntilIdle();
  1756. histogram_tester.ExpectUniqueSample(
  1757. "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 1, 1);
  1758. histogram_tester.ExpectUniqueSample(
  1759. "OptimizationGuide.HintsFetcher.GetHintsRequest.UrlCount", 1, 1);
  1760. histogram_tester.ExpectUniqueSample(
  1761. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  1762. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL, 1);
  1763. }
  1764. TEST_F(HintsManagerFetchingTest,
  1765. HintsFetchedAtNavigationTime_FetchNotAttempted) {
  1766. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1767. switches::kDisableCheckingUserPermissionsForTesting);
  1768. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1769. InitializeWithDefaultConfig("1.0.0.0");
  1770. auto navigation_data =
  1771. CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT});
  1772. hints_manager()->SetHintsFetcherFactoryForTesting(
  1773. BuildTestHintsFetcherFactory({HintsFetcherEndState::kFetchFailed}));
  1774. base::HistogramTester histogram_tester;
  1775. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1776. RunUntilIdle();
  1777. histogram_tester.ExpectTotalCount(
  1778. "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 0);
  1779. histogram_tester.ExpectTotalCount(
  1780. "OptimizationGuide.HintsFetcher.GetHintsRequest.UrlCount", 0);
  1781. histogram_tester.ExpectUniqueSample(
  1782. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  1783. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchNotAttempted, 1);
  1784. }
  1785. TEST_F(HintsManagerFetchingTest,
  1786. HintsFetchedAtNavigationTime_HasComponentHintButNotFetched) {
  1787. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1788. switches::kDisableCheckingUserPermissionsForTesting);
  1789. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1790. InitializeWithDefaultConfig("1.0.0.0");
  1791. hints_manager()->SetHintsFetcherFactoryForTesting(
  1792. BuildTestHintsFetcherFactory(
  1793. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  1794. auto navigation_data =
  1795. CreateTestNavigationData(url_with_hints(), {proto::DEFER_ALL_SCRIPT});
  1796. base::HistogramTester histogram_tester;
  1797. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1798. RunUntilIdle();
  1799. histogram_tester.ExpectTotalCount(
  1800. "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 0);
  1801. histogram_tester.ExpectUniqueSample(
  1802. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  1803. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchURL, 1);
  1804. }
  1805. TEST_F(HintsManagerFetchingTest,
  1806. HintsFetchedAtNavigationTime_DoesNotRemoveManualOverride) {
  1807. GURL example_url("http://www.example.com/hasoverride");
  1808. proto::Configuration config;
  1809. proto::Hint* hint = config.add_hints();
  1810. hint->set_key(example_url.spec());
  1811. hint->set_key_representation(proto::FULL_URL);
  1812. proto::PageHint* page_hint = hint->add_page_hints();
  1813. page_hint->set_page_pattern("*");
  1814. proto::Optimization* opt = page_hint->add_allowlisted_optimizations();
  1815. opt->set_optimization_type(proto::DEFER_ALL_SCRIPT);
  1816. std::string encoded_config;
  1817. config.SerializeToString(&encoded_config);
  1818. base::Base64Encode(encoded_config, &encoded_config);
  1819. base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
  1820. switches::kHintsProtoOverride, encoded_config);
  1821. // Re-create hints manager with override.
  1822. CreateHintsManager(/*top_host_provider=*/nullptr);
  1823. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1824. switches::kDisableCheckingUserPermissionsForTesting);
  1825. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1826. auto navigation_data =
  1827. CreateTestNavigationData(example_url, {proto::DEFER_ALL_SCRIPT});
  1828. base::HistogramTester histogram_tester;
  1829. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1830. RunUntilIdle();
  1831. histogram_tester.ExpectUniqueSample(
  1832. "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 1, 1);
  1833. histogram_tester.ExpectUniqueSample(
  1834. "OptimizationGuide.HintsFetcher.GetHintsRequest.UrlCount", 0, 1);
  1835. histogram_tester.ExpectUniqueSample(
  1836. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  1837. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost, 1);
  1838. OptimizationTypeDecision optimization_type_decision =
  1839. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1840. proto::DEFER_ALL_SCRIPT,
  1841. /*optimization_metadata=*/nullptr);
  1842. EXPECT_EQ(optimization_type_decision,
  1843. OptimizationTypeDecision::kAllowedByHint);
  1844. }
  1845. TEST_F(HintsManagerFetchingTest, URLHintsNotFetchedAtNavigationTime) {
  1846. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1847. switches::kDisableCheckingUserPermissionsForTesting);
  1848. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1849. InitializeWithDefaultConfig("1.0.0.0");
  1850. hints_manager()->SetHintsFetcherFactoryForTesting(
  1851. BuildTestHintsFetcherFactory(
  1852. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  1853. {
  1854. base::HistogramTester histogram_tester;
  1855. auto navigation_data =
  1856. CreateTestNavigationData(url_with_hints(), {proto::DEFER_ALL_SCRIPT});
  1857. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1858. RunUntilIdle();
  1859. histogram_tester.ExpectTotalCount(
  1860. "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 0);
  1861. // Make sure navigation data is populated correctly.
  1862. EXPECT_TRUE(navigation_data->hints_fetch_latency().has_value());
  1863. EXPECT_EQ(navigation_data->hints_fetch_attempt_status(),
  1864. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchURL);
  1865. histogram_tester.ExpectBucketCount(
  1866. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  1867. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchURL, 1);
  1868. histogram_tester.ExpectUniqueSample(
  1869. "OptimizationGuide.HintsManager."
  1870. "PageNavigationHintsReturnedBeforeDataFlushed",
  1871. true, 1);
  1872. RunUntilIdle();
  1873. }
  1874. {
  1875. base::HistogramTester histogram_tester;
  1876. auto navigation_data =
  1877. CreateTestNavigationData(url_with_hints(), {proto::DEFER_ALL_SCRIPT});
  1878. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1879. RunUntilIdle();
  1880. histogram_tester.ExpectBucketCount(
  1881. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  1882. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchNotAttempted, 1);
  1883. // Make sure navigation data is populated correctly.
  1884. EXPECT_FALSE(navigation_data->hints_fetch_latency().has_value());
  1885. EXPECT_EQ(
  1886. navigation_data->hints_fetch_attempt_status(),
  1887. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchNotAttempted);
  1888. histogram_tester.ExpectTotalCount(
  1889. "OptimizationGuide.HintsManager."
  1890. "PageNavigationHintsReturnedBeforeDataFlushed",
  1891. 0);
  1892. }
  1893. }
  1894. TEST_F(HintsManagerFetchingTest, URLWithNoHintsNotRefetchedAtNavigationTime) {
  1895. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1896. switches::kDisableCheckingUserPermissionsForTesting);
  1897. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1898. InitializeWithDefaultConfig("1.0.0.0");
  1899. hints_manager()->SetHintsFetcherFactoryForTesting(
  1900. BuildTestHintsFetcherFactory(
  1901. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  1902. base::HistogramTester histogram_tester;
  1903. {
  1904. auto navigation_data = CreateTestNavigationData(url_without_hints(),
  1905. {proto::DEFER_ALL_SCRIPT});
  1906. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1907. RunUntilIdle();
  1908. histogram_tester.ExpectTotalCount(
  1909. "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 0);
  1910. // Make sure navigation data is populated correctly.
  1911. EXPECT_TRUE(navigation_data->hints_fetch_latency().has_value());
  1912. EXPECT_EQ(navigation_data->hints_fetch_attempt_status(),
  1913. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL);
  1914. histogram_tester.ExpectBucketCount(
  1915. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  1916. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL, 1);
  1917. RunUntilIdle();
  1918. }
  1919. {
  1920. auto navigation_data = CreateTestNavigationData(url_without_hints(),
  1921. {proto::DEFER_ALL_SCRIPT});
  1922. base::RunLoop run_loop;
  1923. navigation_data = CreateTestNavigationData(url_without_hints(),
  1924. {proto::DEFER_ALL_SCRIPT});
  1925. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1926. RunUntilIdle();
  1927. histogram_tester.ExpectBucketCount(
  1928. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  1929. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost, 1);
  1930. EXPECT_TRUE(navigation_data->hints_fetch_latency().has_value());
  1931. EXPECT_EQ(navigation_data->hints_fetch_attempt_status(),
  1932. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost);
  1933. }
  1934. }
  1935. TEST_F(HintsManagerFetchingTest, CanApplyOptimizationCalledMidFetch) {
  1936. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1937. switches::kDisableCheckingUserPermissionsForTesting);
  1938. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1939. InitializeWithDefaultConfig("1.0.0.0");
  1940. auto navigation_data =
  1941. CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT});
  1942. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1943. OptimizationTypeDecision optimization_type_decision =
  1944. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1945. proto::DEFER_ALL_SCRIPT,
  1946. /*optimization_metadata=*/nullptr);
  1947. EXPECT_EQ(optimization_type_decision,
  1948. OptimizationTypeDecision::kHintFetchStartedButNotAvailableInTime);
  1949. }
  1950. TEST_F(HintsManagerFetchingTest,
  1951. CanApplyOptimizationCalledPostFetchButNoHintsCameBack) {
  1952. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1953. switches::kDisableCheckingUserPermissionsForTesting);
  1954. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1955. InitializeWithDefaultConfig("1.0.0.0");
  1956. hints_manager()->SetHintsFetcherFactoryForTesting(
  1957. BuildTestHintsFetcherFactory(
  1958. {HintsFetcherEndState::kFetchSuccessWithNoHints}));
  1959. auto navigation_data =
  1960. CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT});
  1961. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1962. RunUntilIdle();
  1963. OptimizationTypeDecision optimization_type_decision =
  1964. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1965. proto::DEFER_ALL_SCRIPT,
  1966. /*optimization_metadata=*/nullptr);
  1967. EXPECT_EQ(optimization_type_decision,
  1968. OptimizationTypeDecision::kNoHintAvailable);
  1969. }
  1970. TEST_F(HintsManagerFetchingTest,
  1971. CanApplyOptimizationCalledPostFetchButFetchFailed) {
  1972. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1973. switches::kDisableCheckingUserPermissionsForTesting);
  1974. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  1975. InitializeWithDefaultConfig("1.0.0.0");
  1976. hints_manager()->SetHintsFetcherFactoryForTesting(
  1977. BuildTestHintsFetcherFactory({HintsFetcherEndState::kFetchFailed}));
  1978. auto navigation_data =
  1979. CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT});
  1980. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  1981. RunUntilIdle();
  1982. OptimizationTypeDecision optimization_type_decision =
  1983. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  1984. proto::DEFER_ALL_SCRIPT,
  1985. /*optimization_metadata=*/nullptr);
  1986. EXPECT_EQ(optimization_type_decision,
  1987. OptimizationTypeDecision::kNoHintAvailable);
  1988. }
  1989. TEST_F(HintsManagerFetchingTest,
  1990. CanApplyOptimizationWithURLKeyedHintApplicableForOptimizationType) {
  1991. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  1992. switches::kDisableCheckingUserPermissionsForTesting);
  1993. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  1994. InitializeWithDefaultConfig("1.0.0");
  1995. hints_manager()->SetHintsFetcherFactoryForTesting(
  1996. BuildTestHintsFetcherFactory(
  1997. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  1998. auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(),
  1999. {proto::DEFER_ALL_SCRIPT});
  2000. // Make sure URL-keyed hint is fetched and processed.
  2001. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2002. RunUntilIdle();
  2003. OptimizationMetadata optimization_metadata;
  2004. OptimizationTypeDecision optimization_type_decision =
  2005. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  2006. proto::COMPRESS_PUBLIC_IMAGES,
  2007. &optimization_metadata);
  2008. // Make sure decisions are logged correctly and metadata is populated off
  2009. // a URL-keyed hint.
  2010. EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint,
  2011. optimization_type_decision);
  2012. EXPECT_TRUE(optimization_metadata.public_image_metadata().has_value());
  2013. }
  2014. TEST_F(HintsManagerFetchingTest,
  2015. CanApplyOptimizationNotAllowedByURLButAllowedByHostKeyedHint) {
  2016. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2017. switches::kDisableCheckingUserPermissionsForTesting);
  2018. hints_manager()->RegisterOptimizationTypes({proto::NOSCRIPT});
  2019. InitializeWithDefaultConfig("1.0.0.0");
  2020. // Make sure both URL-Keyed and host-keyed hints are processed and cached.
  2021. hints_manager()->SetHintsFetcherFactoryForTesting(
  2022. BuildTestHintsFetcherFactory(
  2023. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2024. auto navigation_data =
  2025. CreateTestNavigationData(url_with_url_keyed_hint(), {proto::NOSCRIPT});
  2026. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2027. RunUntilIdle();
  2028. OptimizationMetadata optimization_metadata;
  2029. OptimizationTypeDecision optimization_type_decision =
  2030. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  2031. proto::NOSCRIPT,
  2032. &optimization_metadata);
  2033. EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint,
  2034. optimization_type_decision);
  2035. }
  2036. TEST_F(HintsManagerFetchingTest,
  2037. CanApplyOptimizationNotAllowedByURLOrHostKeyedHint) {
  2038. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2039. switches::kDisableCheckingUserPermissionsForTesting);
  2040. hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING});
  2041. InitializeWithDefaultConfig("1.0.0.0");
  2042. // Make sure both URL-Keyed and host-keyed hints are processed and cached.
  2043. hints_manager()->SetHintsFetcherFactoryForTesting(
  2044. BuildTestHintsFetcherFactory(
  2045. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2046. auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(),
  2047. {proto::RESOURCE_LOADING});
  2048. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2049. RunUntilIdle();
  2050. OptimizationMetadata optimization_metadata;
  2051. OptimizationTypeDecision optimization_type_decision =
  2052. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  2053. proto::RESOURCE_LOADING,
  2054. &optimization_metadata);
  2055. EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByHint,
  2056. optimization_type_decision);
  2057. }
  2058. TEST_F(HintsManagerFetchingTest,
  2059. CanApplyOptimizationNoURLKeyedHintOrHostKeyedHint) {
  2060. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2061. switches::kDisableCheckingUserPermissionsForTesting);
  2062. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2063. InitializeWithDefaultConfig("1.0.0.0");
  2064. hints_manager()->SetHintsFetcherFactoryForTesting(
  2065. BuildTestHintsFetcherFactory(
  2066. {HintsFetcherEndState::kFetchSuccessWithNoHints}));
  2067. auto navigation_data = CreateTestNavigationData(
  2068. url_without_hints(), {proto::COMPRESS_PUBLIC_IMAGES});
  2069. // Attempt to fetch a hint but ensure nothing comes back.
  2070. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2071. RunUntilIdle();
  2072. OptimizationMetadata optimization_metadata;
  2073. OptimizationTypeDecision optimization_type_decision =
  2074. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  2075. proto::COMPRESS_PUBLIC_IMAGES,
  2076. &optimization_metadata);
  2077. EXPECT_EQ(OptimizationTypeDecision::kNoHintAvailable,
  2078. optimization_type_decision);
  2079. }
  2080. TEST_F(HintsManagerFetchingTest,
  2081. CanApplyOptimizationCalledMidFetchForURLKeyedOptimization) {
  2082. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2083. switches::kDisableCheckingUserPermissionsForTesting);
  2084. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2085. InitializeWithDefaultConfig("1.0.0.0");
  2086. // Attempt to fetch a hint but call CanApplyOptimization right away to
  2087. // simulate being mid-fetch.
  2088. auto navigation_data = CreateTestNavigationData(
  2089. url_without_hints(), {proto::COMPRESS_PUBLIC_IMAGES});
  2090. hints_manager()->SetHintsFetcherFactoryForTesting(
  2091. BuildTestHintsFetcherFactory(
  2092. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  2093. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2094. OptimizationMetadata optimization_metadata;
  2095. OptimizationTypeDecision optimization_type_decision =
  2096. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  2097. proto::COMPRESS_PUBLIC_IMAGES,
  2098. &optimization_metadata);
  2099. EXPECT_EQ(OptimizationTypeDecision::kHintFetchStartedButNotAvailableInTime,
  2100. optimization_type_decision);
  2101. }
  2102. TEST_F(HintsManagerFetchingTest,
  2103. OnNavigationStartOrRedirectWontInitiateFetchIfAlreadyStartedForTheURL) {
  2104. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2105. switches::kDisableCheckingUserPermissionsForTesting);
  2106. hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING});
  2107. InitializeWithDefaultConfig("1.0.0.0");
  2108. // Attempt to fetch a hint but initiate the next navigation right away to
  2109. // simulate being mid-fetch.
  2110. auto navigation_data =
  2111. CreateTestNavigationData(url_without_hints(), {proto::RESOURCE_LOADING});
  2112. {
  2113. base::HistogramTester histogram_tester;
  2114. hints_manager()->SetHintsFetcherFactoryForTesting(
  2115. BuildTestHintsFetcherFactory(
  2116. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  2117. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2118. histogram_tester.ExpectUniqueSample(
  2119. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  2120. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL, 1);
  2121. histogram_tester.ExpectUniqueSample(
  2122. "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 1, 1);
  2123. }
  2124. {
  2125. base::HistogramTester histogram_tester;
  2126. hints_manager()->SetHintsFetcherFactoryForTesting(
  2127. BuildTestHintsFetcherFactory(
  2128. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  2129. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2130. histogram_tester.ExpectUniqueSample(
  2131. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  2132. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchAlreadyInProgress,
  2133. 1);
  2134. // Should not be recorded since we are not attempting a new fetch.
  2135. histogram_tester.ExpectTotalCount(
  2136. "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 0);
  2137. // Set hints fetch end.so we can figure out if hints fetch start was set.
  2138. navigation_data->set_hints_fetch_end(base::TimeTicks::Now());
  2139. EXPECT_TRUE(navigation_data->hints_fetch_latency().has_value());
  2140. EXPECT_EQ(navigation_data->hints_fetch_attempt_status(),
  2141. RaceNavigationFetchAttemptStatus::
  2142. kRaceNavigationFetchAlreadyInProgress);
  2143. }
  2144. }
  2145. TEST_F(HintsManagerFetchingTest,
  2146. PageNavigationHintsFetcherGetsCleanedUpOnceHintsAreStored) {
  2147. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2148. switches::kDisableCheckingUserPermissionsForTesting);
  2149. hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING});
  2150. InitializeWithDefaultConfig("1.0.0.0");
  2151. hints_manager()->SetHintsFetcherFactoryForTesting(
  2152. BuildTestHintsFetcherFactory(
  2153. {HintsFetcherEndState::kFetchSuccessWithNoHints}));
  2154. // Attempt to fetch a hint but initiate the next navigation right away to
  2155. // simulate being mid-fetch.
  2156. auto navigation_data =
  2157. CreateTestNavigationData(url_without_hints(), {proto::RESOURCE_LOADING});
  2158. {
  2159. base::HistogramTester histogram_tester;
  2160. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2161. histogram_tester.ExpectUniqueSample(
  2162. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  2163. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL, 1);
  2164. histogram_tester.ExpectUniqueSample(
  2165. "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 1, 1);
  2166. // Make sure hints are stored (i.e. fetcher is cleaned up).
  2167. RunUntilIdle();
  2168. }
  2169. {
  2170. base::HistogramTester histogram_tester;
  2171. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2172. histogram_tester.ExpectUniqueSample(
  2173. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  2174. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost, 1);
  2175. histogram_tester.ExpectUniqueSample(
  2176. "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 1, 1);
  2177. }
  2178. }
  2179. TEST_F(HintsManagerFetchingTest,
  2180. PageNavigationHintsFetcherCanFetchMultipleThingsConcurrently) {
  2181. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2182. switches::kDisableCheckingUserPermissionsForTesting);
  2183. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2184. InitializeWithDefaultConfig("1.0.0.0");
  2185. hints_manager()->SetHintsFetcherFactoryForTesting(
  2186. BuildTestHintsFetcherFactory(
  2187. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2188. auto navigation_data_with_hints = CreateTestNavigationData(
  2189. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2190. auto navigation_data_without_hints = CreateTestNavigationData(
  2191. GURL("https://doesntmatter.com/"), {proto::COMPRESS_PUBLIC_IMAGES});
  2192. auto navigation_data_without_hints2 = CreateTestNavigationData(
  2193. url_without_hints(), {proto::COMPRESS_PUBLIC_IMAGES});
  2194. // Attempt to fetch a hint but initiate the next navigations right away to
  2195. // simulate being mid-fetch.
  2196. base::HistogramTester histogram_tester;
  2197. CallOnNavigationStartOrRedirect(navigation_data_with_hints.get(),
  2198. base::DoNothing());
  2199. CallOnNavigationStartOrRedirect(navigation_data_without_hints.get(),
  2200. base::DoNothing());
  2201. CallOnNavigationStartOrRedirect(navigation_data_without_hints2.get(),
  2202. base::DoNothing());
  2203. // The third one is over the max and should evict another one.
  2204. histogram_tester.ExpectTotalCount(
  2205. "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 3);
  2206. histogram_tester.ExpectBucketCount(
  2207. "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 1, 1);
  2208. histogram_tester.ExpectBucketCount(
  2209. "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 2, 2);
  2210. }
  2211. TEST_F(HintsManagerFetchingTest,
  2212. CanApplyOptimizationNewAPIDecisionComesFromInFlightURLHint) {
  2213. base::HistogramTester histogram_tester;
  2214. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2215. switches::kDisableCheckingUserPermissionsForTesting);
  2216. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2217. InitializeWithDefaultConfig("1.0.0.0");
  2218. hints_manager()->SetHintsFetcherFactoryForTesting(
  2219. BuildTestHintsFetcherFactory(
  2220. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2221. auto navigation_data = CreateTestNavigationData(
  2222. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2223. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2224. hints_manager()->CanApplyOptimization(
  2225. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2226. base::BindOnce([](OptimizationGuideDecision decision,
  2227. const OptimizationMetadata& metadata) {
  2228. EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
  2229. }));
  2230. // Wait for the hint to be available and for the callback to execute.
  2231. RunUntilIdle();
  2232. // The new API should have called the async API in the background.
  2233. histogram_tester.ExpectUniqueSample(
  2234. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  2235. OptimizationTypeDecision::kAllowedByHint, 1);
  2236. }
  2237. TEST_F(HintsManagerFetchingTest,
  2238. CanApplyOptimizationNewAPIRequestFailsBeforeFetch) {
  2239. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2240. switches::kDisableCheckingUserPermissionsForTesting);
  2241. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2242. InitializeWithDefaultConfig("1.0.0.0");
  2243. // The first query should fail since no "navigation" has occurred.
  2244. hints_manager()->CanApplyOptimization(
  2245. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2246. base::BindOnce([](OptimizationGuideDecision decision,
  2247. const OptimizationMetadata& metadata) {
  2248. EXPECT_EQ(OptimizationGuideDecision::kUnknown, decision);
  2249. }));
  2250. // Make the hints available after the URL has been queried.
  2251. auto navigation_data = CreateTestNavigationData(
  2252. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2253. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2254. hints_manager()->SetHintsFetcherFactoryForTesting(
  2255. BuildTestHintsFetcherFactory(
  2256. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2257. // Wait for the hint to become available.
  2258. RunUntilIdle();
  2259. // Now make sure the hint is available with the same API.
  2260. hints_manager()->CanApplyOptimization(
  2261. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2262. base::BindOnce([](OptimizationGuideDecision decision,
  2263. const OptimizationMetadata& metadata) {
  2264. EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
  2265. }));
  2266. }
  2267. TEST_F(HintsManagerFetchingTest, CanApplyOptimizationNewAPICalledPostFetch) {
  2268. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2269. switches::kDisableCheckingUserPermissionsForTesting);
  2270. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2271. InitializeWithDefaultConfig("1.0.0.0");
  2272. hints_manager()->SetHintsFetcherFactoryForTesting(
  2273. BuildTestHintsFetcherFactory(
  2274. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2275. auto navigation_data = CreateTestNavigationData(
  2276. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2277. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2278. // Wait for the hint to become available.
  2279. RunUntilIdle();
  2280. hints_manager()->CanApplyOptimization(
  2281. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2282. base::BindOnce([](OptimizationGuideDecision decision,
  2283. const OptimizationMetadata& metadata) {
  2284. EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
  2285. }));
  2286. }
  2287. TEST_F(HintsManagerFetchingTest,
  2288. CanApplyOptimizationAsyncDecisionComesFromInFlightURLHint) {
  2289. base::HistogramTester histogram_tester;
  2290. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2291. switches::kDisableCheckingUserPermissionsForTesting);
  2292. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2293. InitializeWithDefaultConfig("1.0.0.0");
  2294. hints_manager()->SetHintsFetcherFactoryForTesting(
  2295. BuildTestHintsFetcherFactory(
  2296. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2297. auto navigation_data = CreateTestNavigationData(
  2298. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2299. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2300. hints_manager()->CanApplyOptimizationAsync(
  2301. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2302. base::BindOnce([](OptimizationGuideDecision decision,
  2303. const OptimizationMetadata& metadata) {
  2304. EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
  2305. EXPECT_TRUE(metadata.public_image_metadata().has_value());
  2306. }));
  2307. RunUntilIdle();
  2308. histogram_tester.ExpectUniqueSample(
  2309. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  2310. OptimizationTypeDecision::kAllowedByHint, 1);
  2311. }
  2312. TEST_F(HintsManagerFetchingTest,
  2313. CanApplyOptimizationAsyncMultipleCallbacksRegisteredForSameTypeAndURL) {
  2314. base::HistogramTester histogram_tester;
  2315. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2316. switches::kDisableCheckingUserPermissionsForTesting);
  2317. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2318. InitializeWithDefaultConfig("1.0.0.0");
  2319. hints_manager()->SetHintsFetcherFactoryForTesting(
  2320. BuildTestHintsFetcherFactory(
  2321. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2322. auto navigation_data = CreateTestNavigationData(
  2323. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2324. hints_manager()->CanApplyOptimizationAsync(
  2325. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2326. base::BindOnce([](OptimizationGuideDecision decision,
  2327. const OptimizationMetadata& metadata) {
  2328. EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
  2329. EXPECT_TRUE(metadata.public_image_metadata().has_value());
  2330. }));
  2331. hints_manager()->CanApplyOptimizationAsync(
  2332. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2333. base::BindOnce([](OptimizationGuideDecision decision,
  2334. const OptimizationMetadata& metadata) {
  2335. EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
  2336. EXPECT_TRUE(metadata.public_image_metadata().has_value());
  2337. }));
  2338. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2339. RunUntilIdle();
  2340. histogram_tester.ExpectUniqueSample(
  2341. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  2342. OptimizationTypeDecision::kAllowedByHint, 2);
  2343. }
  2344. TEST_F(
  2345. HintsManagerFetchingTest,
  2346. CanApplyOptimizationAsyncDecisionComesFromInFlightURLHintNotAllowlisted) {
  2347. base::HistogramTester histogram_tester;
  2348. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2349. switches::kDisableCheckingUserPermissionsForTesting);
  2350. hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING});
  2351. InitializeWithDefaultConfig("1.0.0.0");
  2352. hints_manager()->SetHintsFetcherFactoryForTesting(
  2353. BuildTestHintsFetcherFactory(
  2354. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2355. auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(),
  2356. {proto::RESOURCE_LOADING});
  2357. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2358. hints_manager()->CanApplyOptimizationAsync(
  2359. url_with_url_keyed_hint(), proto::RESOURCE_LOADING,
  2360. base::BindOnce([](OptimizationGuideDecision decision,
  2361. const OptimizationMetadata& metadata) {
  2362. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  2363. }));
  2364. RunUntilIdle();
  2365. histogram_tester.ExpectUniqueSample(
  2366. "OptimizationGuide.ApplyDecisionAsync.ResourceLoading",
  2367. OptimizationTypeDecision::kNotAllowedByHint, 1);
  2368. }
  2369. TEST_F(HintsManagerFetchingTest,
  2370. CanApplyOptimizationAsyncFetchFailsDoesNotStrandCallbacks) {
  2371. base::HistogramTester histogram_tester;
  2372. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2373. switches::kDisableCheckingUserPermissionsForTesting);
  2374. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2375. InitializeWithDefaultConfig("1.0.0.0");
  2376. hints_manager()->SetHintsFetcherFactoryForTesting(
  2377. BuildTestHintsFetcherFactory({HintsFetcherEndState::kFetchFailed}));
  2378. auto navigation_data = CreateTestNavigationData(
  2379. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2380. hints_manager()->CanApplyOptimizationAsync(
  2381. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2382. base::BindOnce([](OptimizationGuideDecision decision,
  2383. const OptimizationMetadata& metadata) {
  2384. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  2385. }));
  2386. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2387. RunUntilIdle();
  2388. histogram_tester.ExpectUniqueSample(
  2389. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  2390. OptimizationTypeDecision::kNotAllowedByHint, 1);
  2391. }
  2392. TEST_F(HintsManagerFetchingTest,
  2393. CanApplyOptimizationAsyncInfoAlreadyInPriorToCall) {
  2394. base::HistogramTester histogram_tester;
  2395. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2396. switches::kDisableCheckingUserPermissionsForTesting);
  2397. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2398. InitializeWithDefaultConfig("1.0.0.0");
  2399. hints_manager()->SetHintsFetcherFactoryForTesting(
  2400. BuildTestHintsFetcherFactory(
  2401. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2402. auto navigation_data = CreateTestNavigationData(
  2403. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2404. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2405. RunUntilIdle();
  2406. hints_manager()->CanApplyOptimizationAsync(
  2407. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2408. base::BindOnce([](OptimizationGuideDecision decision,
  2409. const OptimizationMetadata& metadata) {
  2410. EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
  2411. EXPECT_TRUE(metadata.public_image_metadata().has_value());
  2412. }));
  2413. RunUntilIdle();
  2414. histogram_tester.ExpectUniqueSample(
  2415. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  2416. OptimizationTypeDecision::kAllowedByHint, 1);
  2417. }
  2418. TEST_F(HintsManagerFetchingTest,
  2419. CanApplyOptimizationAsyncInfoAlreadyInPriorToCallAndNotAllowlisted) {
  2420. base::HistogramTester histogram_tester;
  2421. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2422. switches::kDisableCheckingUserPermissionsForTesting);
  2423. hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS});
  2424. InitializeWithDefaultConfig("1.0.0.0");
  2425. hints_manager()->SetHintsFetcherFactoryForTesting(
  2426. BuildTestHintsFetcherFactory(
  2427. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2428. auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(),
  2429. {proto::PERFORMANCE_HINTS});
  2430. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2431. RunUntilIdle();
  2432. hints_manager()->CanApplyOptimizationAsync(
  2433. url_with_url_keyed_hint(), proto::PERFORMANCE_HINTS,
  2434. base::BindOnce([](OptimizationGuideDecision decision,
  2435. const OptimizationMetadata& metadata) {
  2436. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  2437. }));
  2438. RunUntilIdle();
  2439. histogram_tester.ExpectUniqueSample(
  2440. "OptimizationGuide.ApplyDecisionAsync.PerformanceHints",
  2441. OptimizationTypeDecision::kNotAllowedByHint, 1);
  2442. }
  2443. TEST_F(HintsManagerFetchingTest,
  2444. CanApplyOptimizationAsyncHintComesInAndNotAllowlisted) {
  2445. base::HistogramTester histogram_tester;
  2446. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2447. switches::kDisableCheckingUserPermissionsForTesting);
  2448. hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS});
  2449. InitializeWithDefaultConfig("1.0.0.0");
  2450. hints_manager()->SetHintsFetcherFactoryForTesting(
  2451. BuildTestHintsFetcherFactory(
  2452. {HintsFetcherEndState::kFetchSuccessWithNoHints}));
  2453. auto navigation_data =
  2454. CreateTestNavigationData(url_without_hints(), {proto::PERFORMANCE_HINTS});
  2455. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2456. hints_manager()->CanApplyOptimizationAsync(
  2457. url_without_hints(), proto::PERFORMANCE_HINTS,
  2458. base::BindOnce([](OptimizationGuideDecision decision,
  2459. const OptimizationMetadata& metadata) {
  2460. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  2461. }));
  2462. RunUntilIdle();
  2463. histogram_tester.ExpectUniqueSample(
  2464. "OptimizationGuide.ApplyDecisionAsync.PerformanceHints",
  2465. OptimizationTypeDecision::kNoHintAvailable, 1);
  2466. }
  2467. TEST_F(HintsManagerFetchingTest,
  2468. CanApplyOptimizationAsyncDoesNotStrandCallbacksAtBeginningOfChain) {
  2469. base::HistogramTester histogram_tester;
  2470. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2471. switches::kDisableCheckingUserPermissionsForTesting);
  2472. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2473. InitializeWithDefaultConfig("1.0.0.0");
  2474. GURL url_that_redirected("https://urlthatredirected.com");
  2475. auto navigation_data_redirect = CreateTestNavigationData(
  2476. url_that_redirected, {proto::COMPRESS_PUBLIC_IMAGES});
  2477. hints_manager()->CanApplyOptimizationAsync(
  2478. url_that_redirected, proto::COMPRESS_PUBLIC_IMAGES,
  2479. base::BindOnce([](OptimizationGuideDecision decision,
  2480. const OptimizationMetadata& metadata) {
  2481. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  2482. }));
  2483. hints_manager()->OnNavigationFinish(
  2484. {url_that_redirected, GURL("https://otherurl.com/")});
  2485. RunUntilIdle();
  2486. histogram_tester.ExpectUniqueSample(
  2487. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  2488. OptimizationTypeDecision::kNoHintAvailable, 1);
  2489. }
  2490. TEST_F(HintsManagerFetchingTest,
  2491. CanApplyOptimizationAsyncDoesNotStrandCallbacksIfFetchNotPending) {
  2492. base::HistogramTester histogram_tester;
  2493. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2494. switches::kDisableCheckingUserPermissionsForTesting);
  2495. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2496. InitializeWithDefaultConfig("1.0.0.0");
  2497. hints_manager()->SetHintsFetcherFactoryForTesting(
  2498. BuildTestHintsFetcherFactory(
  2499. {HintsFetcherEndState::kFetchSuccessWithNoHints}));
  2500. auto navigation_data = CreateTestNavigationData(
  2501. url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES});
  2502. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2503. hints_manager()->CanApplyOptimizationAsync(
  2504. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2505. base::BindOnce([](OptimizationGuideDecision decision,
  2506. const OptimizationMetadata& metadata) {
  2507. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  2508. }));
  2509. hints_manager()->OnNavigationFinish({url_with_url_keyed_hint()});
  2510. RunUntilIdle();
  2511. histogram_tester.ExpectUniqueSample(
  2512. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  2513. OptimizationTypeDecision::kNotAllowedByHint, 1);
  2514. }
  2515. TEST_F(HintsManagerFetchingTest,
  2516. CanApplyOptimizationAsyncWithDecisionFromAllowlistReturnsRightAway) {
  2517. base::HistogramTester histogram_tester;
  2518. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  2519. proto::Configuration config;
  2520. BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  2521. kDefaultHostBloomFilterNumBits);
  2522. PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter);
  2523. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter,
  2524. kDefaultHostBloomFilterNumHashFunctions,
  2525. kDefaultHostBloomFilterNumBits,
  2526. /*is_allowlist=*/true, &config);
  2527. ProcessHints(config, "1.0.0.0");
  2528. auto navigation_data = CreateTestNavigationData(
  2529. GURL("https://notallowed.com/123"), {proto::LITE_PAGE_REDIRECT});
  2530. hints_manager()->CanApplyOptimizationAsync(
  2531. navigation_data->navigation_url(), proto::LITE_PAGE_REDIRECT,
  2532. base::BindOnce([](OptimizationGuideDecision decision,
  2533. const OptimizationMetadata& metadata) {
  2534. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  2535. }));
  2536. RunUntilIdle();
  2537. histogram_tester.ExpectUniqueSample(
  2538. "OptimizationGuide.ApplyDecisionAsync.LitePageRedirect",
  2539. OptimizationTypeDecision::kNotAllowedByOptimizationFilter, 1);
  2540. }
  2541. TEST_F(HintsManagerFetchingTest,
  2542. CanApplyOptimizationAsyncWithDecisionFromBlocklistReturnsRightAway) {
  2543. base::HistogramTester histogram_tester;
  2544. hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
  2545. proto::Configuration config;
  2546. BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions,
  2547. kDefaultHostBloomFilterNumBits);
  2548. PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter);
  2549. AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter,
  2550. kDefaultHostBloomFilterNumHashFunctions,
  2551. kDefaultHostBloomFilterNumBits,
  2552. /*is_allowlist=*/false, &config);
  2553. ProcessHints(config, "1.0.0.0");
  2554. auto navigation_data = CreateTestNavigationData(
  2555. GURL("https://m.host.com/123"), {proto::LITE_PAGE_REDIRECT});
  2556. hints_manager()->CanApplyOptimizationAsync(
  2557. navigation_data->navigation_url(), proto::LITE_PAGE_REDIRECT,
  2558. base::BindOnce([](OptimizationGuideDecision decision,
  2559. const OptimizationMetadata& metadata) {
  2560. EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
  2561. }));
  2562. RunUntilIdle();
  2563. histogram_tester.ExpectUniqueSample(
  2564. "OptimizationGuide.ApplyDecisionAsync.LitePageRedirect",
  2565. OptimizationTypeDecision::kNotAllowedByOptimizationFilter, 1);
  2566. }
  2567. TEST_F(HintsManagerFetchingTest,
  2568. OnNavigationFinishDoesNotPrematurelyInvokeRegisteredCallbacks) {
  2569. base::HistogramTester histogram_tester;
  2570. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2571. switches::kDisableCheckingUserPermissionsForTesting);
  2572. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2573. InitializeWithDefaultConfig("1.0.0.0");
  2574. hints_manager()->SetHintsFetcherFactoryForTesting(
  2575. BuildTestHintsFetcherFactory(
  2576. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2577. auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(),
  2578. {proto::LITE_PAGE_REDIRECT});
  2579. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2580. hints_manager()->CanApplyOptimizationAsync(
  2581. url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES,
  2582. base::BindOnce([](OptimizationGuideDecision decision,
  2583. const OptimizationMetadata& metadata) {
  2584. EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
  2585. EXPECT_TRUE(metadata.public_image_metadata().has_value());
  2586. }));
  2587. hints_manager()->OnNavigationFinish({url_with_url_keyed_hint()});
  2588. RunUntilIdle();
  2589. histogram_tester.ExpectUniqueSample(
  2590. "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages",
  2591. OptimizationTypeDecision::kAllowedByHint, 1);
  2592. }
  2593. TEST_F(HintsManagerFetchingTest,
  2594. OnNavigationFinishDoesNotCrashWithoutAnyCallbacksRegistered) {
  2595. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2596. switches::kDisableCheckingUserPermissionsForTesting);
  2597. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2598. InitializeWithDefaultConfig("1.0.0.0");
  2599. hints_manager()->OnNavigationFinish({url_with_url_keyed_hint()});
  2600. RunUntilIdle();
  2601. }
  2602. TEST_F(HintsManagerFetchingTest, NewOptTypeRegisteredClearsHintCache) {
  2603. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2604. switches::kDisableCheckingUserPermissionsForTesting);
  2605. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  2606. InitializeWithDefaultConfig("1.0.0.0");
  2607. GURL url("https://host.com/fetched_hint_host");
  2608. hints_manager()->SetHintsFetcherFactoryForTesting(
  2609. BuildTestHintsFetcherFactory(
  2610. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  2611. auto navigation_data =
  2612. CreateTestNavigationData(url, {proto::DEFER_ALL_SCRIPT});
  2613. // Attempt to fetch a hint but ensure nothing comes back.
  2614. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing());
  2615. RunUntilIdle();
  2616. OptimizationMetadata optimization_metadata;
  2617. OptimizationTypeDecision optimization_type_decision =
  2618. hints_manager()->CanApplyOptimization(navigation_data->navigation_url(),
  2619. proto::DEFER_ALL_SCRIPT,
  2620. &optimization_metadata);
  2621. EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByHint,
  2622. optimization_type_decision);
  2623. // Register a new type that is unlaunched - this should clear the Fetched
  2624. // hints.
  2625. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2626. RunUntilIdle();
  2627. base::RunLoop run_loop;
  2628. base::HistogramTester histogram_tester;
  2629. navigation_data = CreateTestNavigationData(url, {proto::DEFER_ALL_SCRIPT});
  2630. CallOnNavigationStartOrRedirect(navigation_data.get(),
  2631. run_loop.QuitClosure());
  2632. run_loop.Run();
  2633. optimization_type_decision = hints_manager()->CanApplyOptimization(
  2634. navigation_data->navigation_url(), proto::DEFER_ALL_SCRIPT,
  2635. &optimization_metadata);
  2636. // The previously fetched hints for the host should not be available after
  2637. // registering a new optimization type.
  2638. histogram_tester.ExpectUniqueSample(
  2639. "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus",
  2640. RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost, 1);
  2641. }
  2642. TEST_F(HintsManagerFetchingTest,
  2643. CanApplyOptimizationOnDemandDecisionMetadataComesFromFetch) {
  2644. base::HistogramTester histogram_tester;
  2645. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2646. InitializeWithDefaultConfig("1.0.0.0");
  2647. hints_manager()->SetHintsFetcherFactoryForTesting(
  2648. BuildTestHintsFetcherFactory(
  2649. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2650. std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
  2651. hints_manager()->CanApplyOptimizationOnDemand(
  2652. {url_with_url_keyed_hint()}, {proto::COMPRESS_PUBLIC_IMAGES},
  2653. proto::RequestContext::CONTEXT_BOOKMARKS,
  2654. base::BindRepeating(
  2655. [](base::RunLoop* run_loop, const GURL& url,
  2656. const base::flat_map<proto::OptimizationType,
  2657. OptimizationGuideDecisionWithMetadata>&
  2658. decisions) {
  2659. ASSERT_EQ(decisions.size(), 1u);
  2660. auto it = decisions.find(proto::COMPRESS_PUBLIC_IMAGES);
  2661. ASSERT_TRUE(it != decisions.end());
  2662. EXPECT_EQ(OptimizationGuideDecision::kTrue, it->second.decision);
  2663. EXPECT_TRUE(
  2664. it->second.metadata.public_image_metadata().has_value());
  2665. run_loop->Quit();
  2666. },
  2667. run_loop.get()));
  2668. run_loop->Run();
  2669. histogram_tester.ExpectUniqueSample(
  2670. "OptimizationGuide.HintsManager.ConcurrentBatchUpdateFetches", 1, 1);
  2671. }
  2672. TEST_F(HintsManagerFetchingTest, BatchUpdateCalledMoreThanMaxConcurrent) {
  2673. base::HistogramTester histogram_tester;
  2674. hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES});
  2675. InitializeWithDefaultConfig("1.0.0.0");
  2676. hints_manager()->SetHintsFetcherFactoryForTesting(
  2677. BuildTestHintsFetcherFactory(
  2678. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2679. // Call this over the max count.
  2680. hints_manager()->CanApplyOptimizationOnDemand(
  2681. {url_with_url_keyed_hint()}, {proto::COMPRESS_PUBLIC_IMAGES},
  2682. proto::RequestContext::CONTEXT_BOOKMARKS,
  2683. base::DoNothingAs<void(
  2684. const GURL&,
  2685. const base::flat_map<proto::OptimizationType,
  2686. OptimizationGuideDecisionWithMetadata>&)>());
  2687. hints_manager()->CanApplyOptimizationOnDemand(
  2688. {url_with_url_keyed_hint()}, {proto::COMPRESS_PUBLIC_IMAGES},
  2689. proto::RequestContext::CONTEXT_BOOKMARKS,
  2690. base::DoNothingAs<void(
  2691. const GURL&,
  2692. const base::flat_map<proto::OptimizationType,
  2693. OptimizationGuideDecisionWithMetadata>&)>());
  2694. hints_manager()->CanApplyOptimizationOnDemand(
  2695. {url_with_url_keyed_hint()}, {proto::COMPRESS_PUBLIC_IMAGES},
  2696. proto::RequestContext::CONTEXT_BOOKMARKS,
  2697. base::DoNothingAs<void(
  2698. const GURL&,
  2699. const base::flat_map<proto::OptimizationType,
  2700. OptimizationGuideDecisionWithMetadata>&)>());
  2701. // The third one is over the max and should evict another one.
  2702. histogram_tester.ExpectTotalCount(
  2703. "OptimizationGuide.HintsManager.ConcurrentBatchUpdateFetches", 3);
  2704. histogram_tester.ExpectBucketCount(
  2705. "OptimizationGuide.HintsManager.ConcurrentBatchUpdateFetches", 1, 1);
  2706. histogram_tester.ExpectBucketCount(
  2707. "OptimizationGuide.HintsManager.ConcurrentBatchUpdateFetches", 2, 2);
  2708. }
  2709. TEST_F(
  2710. HintsManagerFetchingTest,
  2711. CanApplyOptimizationOnDemandDecisionMultipleTypesBothHostAndURLKeyedMixedFetch) {
  2712. base::HistogramTester histogram_tester;
  2713. hints_manager()->RegisterOptimizationTypes(
  2714. {proto::NOSCRIPT, proto::COMPRESS_PUBLIC_IMAGES});
  2715. InitializeWithDefaultConfig("1.0.0.0");
  2716. hints_manager()->SetHintsFetcherFactoryForTesting(
  2717. BuildTestHintsFetcherFactory(
  2718. {HintsFetcherEndState::kFetchSuccessWithURLHints}));
  2719. std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
  2720. hints_manager()->CanApplyOptimizationOnDemand(
  2721. {url_with_url_keyed_hint()},
  2722. {proto::NOSCRIPT, proto::COMPRESS_PUBLIC_IMAGES},
  2723. proto::RequestContext::CONTEXT_BOOKMARKS,
  2724. base::BindRepeating(
  2725. [](base::RunLoop* run_loop, const GURL& url,
  2726. const base::flat_map<proto::OptimizationType,
  2727. OptimizationGuideDecisionWithMetadata>&
  2728. decisions) {
  2729. ASSERT_EQ(decisions.size(), 2u);
  2730. auto it = decisions.find(proto::COMPRESS_PUBLIC_IMAGES);
  2731. ASSERT_TRUE(it != decisions.end());
  2732. EXPECT_EQ(OptimizationGuideDecision::kTrue, it->second.decision);
  2733. EXPECT_TRUE(
  2734. it->second.metadata.public_image_metadata().has_value());
  2735. it = decisions.find(proto::NOSCRIPT);
  2736. ASSERT_TRUE(it != decisions.end());
  2737. EXPECT_EQ(OptimizationGuideDecision::kTrue, it->second.decision);
  2738. run_loop->Quit();
  2739. },
  2740. run_loop.get()));
  2741. run_loop->Run();
  2742. }
  2743. TEST_F(HintsManagerFetchingTest,
  2744. CanApplyOptimizationOnDemandDecisionFailedFetchDoesNotStrandCallback) {
  2745. base::HistogramTester histogram_tester;
  2746. hints_manager()->RegisterOptimizationTypes(
  2747. {proto::NOSCRIPT, proto::COMPRESS_PUBLIC_IMAGES});
  2748. InitializeWithDefaultConfig("1.0.0.0");
  2749. hints_manager()->SetHintsFetcherFactoryForTesting(
  2750. BuildTestHintsFetcherFactory({HintsFetcherEndState::kFetchFailed}));
  2751. std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
  2752. hints_manager()->CanApplyOptimizationOnDemand(
  2753. {url_with_url_keyed_hint()},
  2754. {proto::NOSCRIPT, proto::COMPRESS_PUBLIC_IMAGES},
  2755. proto::RequestContext::CONTEXT_BOOKMARKS,
  2756. base::BindRepeating(
  2757. [](base::RunLoop* run_loop, const GURL& url,
  2758. const base::flat_map<proto::OptimizationType,
  2759. OptimizationGuideDecisionWithMetadata>&
  2760. decisions) {
  2761. ASSERT_EQ(decisions.size(), 2u);
  2762. auto it = decisions.find(proto::COMPRESS_PUBLIC_IMAGES);
  2763. ASSERT_TRUE(it != decisions.end());
  2764. EXPECT_EQ(OptimizationGuideDecision::kFalse, it->second.decision);
  2765. // Should still populate with what's on device.
  2766. it = decisions.find(proto::NOSCRIPT);
  2767. ASSERT_TRUE(it != decisions.end());
  2768. EXPECT_EQ(OptimizationGuideDecision::kTrue, it->second.decision);
  2769. run_loop->Quit();
  2770. },
  2771. run_loop.get()));
  2772. run_loop->Run();
  2773. }
  2774. class HintsManagerFetchingNoBatchUpdateTest : public HintsManagerTest {
  2775. public:
  2776. HintsManagerFetchingNoBatchUpdateTest() {
  2777. scoped_list_.InitAndEnableFeatureWithParameters(
  2778. features::kRemoteOptimizationGuideFetching,
  2779. {{"batch_update_hints_for_top_hosts", "false"}});
  2780. }
  2781. private:
  2782. base::test::ScopedFeatureList scoped_list_;
  2783. };
  2784. TEST_F(HintsManagerFetchingNoBatchUpdateTest,
  2785. BatchUpdateHintsFetchNotScheduledIfNotAllowed) {
  2786. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  2787. switches::kDisableCheckingUserPermissionsForTesting);
  2788. std::unique_ptr<FakeTopHostProvider> top_host_provider =
  2789. std::make_unique<FakeTopHostProvider>(
  2790. std::vector<std::string>({"example1.com", "example2.com"}));
  2791. // Force hints fetch scheduling.
  2792. CreateHintsManager(top_host_provider.get());
  2793. hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT});
  2794. hints_manager()->SetHintsFetcherFactoryForTesting(
  2795. BuildTestHintsFetcherFactory(
  2796. {HintsFetcherEndState::kFetchSuccessWithHostHints}));
  2797. InitializeWithDefaultConfig("1.0.0");
  2798. // Force timer to expire and schedule a hints fetch.
  2799. MoveClockForwardBy(base::Seconds(kUpdateFetchHintsTimeSecs));
  2800. // Hints fetcher should not even be created.
  2801. EXPECT_FALSE(active_tabs_batch_update_hints_fetcher());
  2802. }
  2803. class HintsManagerComponentSkipProcessingTest : public HintsManagerTest {
  2804. public:
  2805. HintsManagerComponentSkipProcessingTest() {
  2806. scoped_feature_list_.InitAndEnableFeatureWithParameters(
  2807. features::kOptimizationHintsComponent,
  2808. {{"check_failed_component_version_pref", "false"}});
  2809. }
  2810. private:
  2811. base::test::ScopedFeatureList scoped_feature_list_;
  2812. };
  2813. TEST_F(HintsManagerComponentSkipProcessingTest, ProcessHintsWithExistingPref) {
  2814. // Write hints processing pref for version 2.0.0.
  2815. pref_service()->SetString(prefs::kPendingHintsProcessingVersion, "2.0.0");
  2816. CreateHintsManager(/*top_host_provider=*/nullptr);
  2817. // Verify config still processed even though pref is existing.
  2818. {
  2819. base::HistogramTester histogram_tester;
  2820. InitializeWithDefaultConfig("2.0.0");
  2821. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  2822. ProcessHintsComponentResult::kSuccess,
  2823. 1);
  2824. // If it processed correctly, it should clear the pref.
  2825. EXPECT_TRUE(pref_service()
  2826. ->GetString(prefs::kPendingHintsProcessingVersion)
  2827. .empty());
  2828. }
  2829. // Now verify config is processed for different version and pref cleared.
  2830. {
  2831. base::HistogramTester histogram_tester;
  2832. InitializeWithDefaultConfig("3.0.0");
  2833. EXPECT_TRUE(pref_service()
  2834. ->GetString(prefs::kPendingHintsProcessingVersion)
  2835. .empty());
  2836. histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult",
  2837. ProcessHintsComponentResult::kSuccess,
  2838. 1);
  2839. }
  2840. }
  2841. } // namespace optimization_guide