1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
content / browser / interest_group / auction_process_manager_unittest.cc [blame]
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/interest_group/auction_process_manager.h"
#include <cstddef>
#include <list>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include "base/check.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/scoped_refptr.h"
#include "base/notreached.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/run_until.h"
#include "base/test/scoped_command_line.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "content/browser/interest_group/interest_group_features.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/service_worker/service_worker_process_manager.h"
#include "content/common/features.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/site_isolation_mode.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
#include "content/services/auction_worklet/public/mojom/auction_shared_storage_host.mojom.h"
#include "content/services/auction_worklet/public/mojom/auction_worklet_service.mojom-forward.h"
#include "content/services/auction_worklet/public/mojom/auction_worklet_service.mojom.h"
#include "content/services/auction_worklet/public/mojom/bidder_worklet.mojom.h"
#include "content/services/auction_worklet/public/mojom/seller_worklet.mojom.h"
#include "content/services/auction_worklet/public/mojom/trusted_signals_cache.mojom.h"
#include "content/test/test_content_browser_client.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace content {
namespace {
using RequestWorkletServiceOutcome =
AuctionProcessManager::RequestWorkletServiceOutcome;
// Alias constants to improve readability.
const size_t kMaxSellerProcesses = AuctionProcessManager::kMaxSellerProcesses;
const size_t kMaxBidderProcesses = AuctionProcessManager::kMaxBidderProcesses;
class TestAuctionProcessManager
: public AuctionProcessManager,
public auction_worklet::mojom::AuctionWorkletService {
public:
TestAuctionProcessManager() = default;
TestAuctionProcessManager(const TestAuctionProcessManager&) = delete;
const TestAuctionProcessManager& operator=(const TestAuctionProcessManager&) =
delete;
~TestAuctionProcessManager() override = default;
void SetTrustedSignalsCache(
mojo::PendingRemote<auction_worklet::mojom::TrustedSignalsCache>
trusted_signals_cache) override {}
void LoadBidderWorklet(
mojo::PendingReceiver<auction_worklet::mojom::BidderWorklet>
bidder_worklet_receiver,
std::vector<
mojo::PendingRemote<auction_worklet::mojom::AuctionSharedStorageHost>>
shared_storage_hosts,
bool pause_for_debugger_on_start,
mojo::PendingRemote<network::mojom::URLLoaderFactory>
pending_url_loader_factory,
mojo::PendingRemote<auction_worklet::mojom::AuctionNetworkEventsHandler>
auction_network_events_handler,
const GURL& script_source_url,
const std::optional<GURL>& bidding_wasm_helper_url,
const std::optional<GURL>& trusted_bidding_signals_url,
const std::string& trusted_bidding_signals_slot_size_param,
const url::Origin& top_window_origin,
auction_worklet::mojom::AuctionWorkletPermissionsPolicyStatePtr
permissions_policy_state,
std::optional<uint16_t> experiment_id,
auction_worklet::mojom::TrustedSignalsPublicKeyPtr public_key) override {
NOTREACHED_IN_MIGRATION();
}
void LoadSellerWorklet(
mojo::PendingReceiver<auction_worklet::mojom::SellerWorklet>
seller_worklet,
std::vector<
mojo::PendingRemote<auction_worklet::mojom::AuctionSharedStorageHost>>
shared_storage_hosts,
bool should_pause_on_start,
mojo::PendingRemote<network::mojom::URLLoaderFactory> url_loader_factory,
mojo::PendingRemote<auction_worklet::mojom::AuctionNetworkEventsHandler>
auction_network_events_handler,
const GURL& script_source_url,
const std::optional<GURL>& trusted_scoring_signals_url,
const url::Origin& top_window_origin,
auction_worklet::mojom::AuctionWorkletPermissionsPolicyStatePtr
permissions_policy_state,
std::optional<uint16_t> experiment_id,
auction_worklet::mojom::TrustedSignalsPublicKeyPtr public_key) override {
NOTREACHED_IN_MIGRATION();
}
void ClosePipes() {
receiver_set_.Clear();
// No wait to flush a closed pipe from the end that was closed. Run until
// the other side has noticed the pipe was closed instead.
base::RunLoop().RunUntilIdle();
}
private:
scoped_refptr<WorkletProcess> LaunchProcess(
WorkletType worklet_type,
const url::Origin& origin,
scoped_refptr<SiteInstance> site_instance,
const std::string& display_name,
bool is_idle) override {
mojo::PendingRemote<auction_worklet::mojom::AuctionWorkletService> service;
receiver_set_.Add(this, service.InitWithNewPipeAndPassReceiver());
RenderProcessHost* host = site_instance->GetProcess();
return base::MakeRefCounted<WorkletProcess>(
this, site_instance, /*render_process_host=*/host, std::move(service),
worklet_type, origin, /*uses_shared_process=*/false,
/*is_idle=*/is_idle, /*is_bound_to_origin=*/true);
}
scoped_refptr<SiteInstance> MaybeComputeSiteInstance(
SiteInstance* frame_site_instance,
const url::Origin& worklet_origin) override {
return frame_site_instance->GetRelatedSiteInstance(worklet_origin.GetURL());
}
bool TryUseSharedProcess(ProcessHandle* process_handle) override {
return false;
}
mojo::ReceiverSet<auction_worklet::mojom::AuctionWorkletService>
receiver_set_;
};
class DedicatedStyleTestAuctionProcessManager
: public TestAuctionProcessManager {
public:
DedicatedStyleTestAuctionProcessManager() = default;
DedicatedStyleTestAuctionProcessManager(
const DedicatedStyleTestAuctionProcessManager&) = delete;
DedicatedStyleTestAuctionProcessManager& operator=(
const DedicatedStyleTestAuctionProcessManager&) = delete;
~DedicatedStyleTestAuctionProcessManager() override = default;
// Get the index that this process was created (e.g. if it was
// the first created process, return 0).
// This will fail if this handle's process was not created by this
// DedicatedStyleTestAuctionProcessManager.
// Do not call this function after any process in the test has been
// destroyed.
size_t ProcessCreationOrder(const ProcessHandle* handle) {
for (size_t i = 0u; i < launched_processes_.size(); ++i) {
if (handle->worklet_process_for_testing() == launched_processes_[i]) {
return i;
}
}
CHECK(false);
return 0;
}
private:
scoped_refptr<WorkletProcess> LaunchProcess(
WorkletType worklet_type,
const url::Origin& origin,
scoped_refptr<SiteInstance> site_instance,
const std::string& display_name,
bool is_idle) override {
mojo::PendingRemote<auction_worklet::mojom::AuctionWorkletService> service;
receiver_set_.Add(this, service.InitWithNewPipeAndPassReceiver());
// Start all idle processes unbound and all non-idle processes bound.
scoped_refptr<WorkletProcess> process =
base::MakeRefCounted<WorkletProcess>(
this, /*site_instance=*/nullptr, /*render_process_host=*/nullptr,
std::move(service), worklet_type, origin,
/*uses_shared_process=*/false, /*is_idle=*/is_idle,
/*is_bound_to_origin=*/!is_idle);
launched_processes_.push_back(process.get());
return process;
}
scoped_refptr<SiteInstance> MaybeComputeSiteInstance(
SiteInstance* frame_site_instance,
const url::Origin& worklet_origin) override {
return nullptr;
}
mojo::ReceiverSet<auction_worklet::mojom::AuctionWorkletService>
receiver_set_;
std::vector<WorkletProcess*> launched_processes_;
};
class AuctionProcessManagerTestBase
: public testing::TestWithParam<AuctionProcessManager::WorkletType> {
protected:
void MaybeStartAnticipatoryProcess(
const url::Origin& origin,
AuctionProcessManager::WorkletType worklet_type) {
GetAuctionProcessManager().MaybeStartAnticipatoryProcess(
origin, GetSiteInstance(), worklet_type);
}
std::string RequestWorkletServiceOutcomeUmaName(
AuctionProcessManager::WorkletType worklet_type) {
return base::StrCat(
{"Ads.InterestGroup.Auction.",
worklet_type == AuctionProcessManager::WorkletType::kSeller ? "Seller."
: "Buyer.",
"RequestWorkletServiceOutcome"});
}
void RequestWorkletService(
AuctionProcessManager::ProcessHandle* process_handle,
const url::Origin& origin,
AuctionProcessManager::WorkletType worklet_type,
bool expect_success,
RequestWorkletServiceOutcome expected_outcome) {
base::HistogramTester histogram_tester;
bool success = GetAuctionProcessManager().RequestWorkletService(
worklet_type, origin, GetSiteInstance(), process_handle,
base::DoNothing());
EXPECT_EQ(expect_success, success);
histogram_tester.ExpectUniqueSample(
RequestWorkletServiceOutcomeUmaName(worklet_type), expected_outcome,
1u);
}
// Returns the maximum number of processes of type GetParam().
size_t GetMaxProcesses() const {
switch (GetParam()) {
case AuctionProcessManager::WorkletType::kSeller:
return kMaxSellerProcesses;
case AuctionProcessManager::WorkletType::kBidder:
return kMaxBidderProcesses;
}
}
AuctionProcessManager::WorkletType GetParamInverse() const {
switch (GetParam()) {
case AuctionProcessManager::WorkletType::kSeller:
return AuctionProcessManager::WorkletType::kBidder;
case AuctionProcessManager::WorkletType::kBidder:
return AuctionProcessManager::WorkletType::kSeller;
}
}
// Returns the number of pending requests of GetParam() type.
size_t GetPendingRequestsOfParamType() {
switch (GetParam()) {
case AuctionProcessManager::WorkletType::kSeller:
return GetAuctionProcessManager().GetPendingSellerRequestsForTesting();
case AuctionProcessManager::WorkletType::kBidder:
return GetAuctionProcessManager().GetPendingBidderRequestsForTesting();
}
}
size_t GetActiveProcesses(AuctionProcessManager::WorkletType type) {
switch (type) {
case AuctionProcessManager::WorkletType::kSeller:
return GetAuctionProcessManager().GetSellerProcessCountForTesting();
case AuctionProcessManager::WorkletType::kBidder:
return GetAuctionProcessManager().GetBidderProcessCountForTesting();
}
}
// Returns the number of active processes of GetParam() type.
size_t GetActiveProcessesOfParamType() {
return GetActiveProcesses(GetParam());
}
void CheckOnlyIdleProcessesWithCount(size_t expected_idle_process_count) {
EXPECT_EQ(GetAuctionProcessManager().GetIdleProcessCountForTesting(),
expected_idle_process_count);
EXPECT_EQ(GetAuctionProcessManager().GetBidderProcessCountForTesting(), 0u);
EXPECT_EQ(GetAuctionProcessManager().GetSellerProcessCountForTesting(), 0u);
}
virtual AuctionProcessManager& GetAuctionProcessManager() = 0;
virtual SiteInstance* GetSiteInstance() = 0;
const url::Origin kOriginA = url::Origin::Create(GURL("https://a.test"));
const url::Origin kOriginB = url::Origin::Create(GURL("https://b.test"));
const url::Origin kOriginC = url::Origin::Create(GURL("https://c.test"));
BrowserTaskEnvironment task_environment_{
content::BrowserTaskEnvironment::TimeSource::MOCK_TIME};
};
class AuctionProcessManagerTest : public AuctionProcessManagerTestBase {
protected:
AuctionProcessManagerTest()
: site_instance_(SiteInstance::Create(&test_browser_context_)) {}
void SetUp() override {
RenderProcessHostImpl::set_render_process_host_factory_for_testing(
&rph_factory_);
SiteIsolationPolicy::DisableFlagCachingForTesting();
}
void TearDown() override {
RenderProcessHostImpl::set_render_process_host_factory_for_testing(nullptr);
}
AuctionProcessManager& GetAuctionProcessManager() override {
return auction_process_manager_;
}
SiteInstance* GetSiteInstance() override { return site_instance_.get(); }
// Request a worklet service and expect the request to complete synchronously.
// There's no async version, since async calls are only triggered by deleting
// another handle.
std::unique_ptr<AuctionProcessManager::ProcessHandle>
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType worklet_type,
const url::Origin& origin) {
auto process_handle =
std::make_unique<AuctionProcessManager::ProcessHandle>();
EXPECT_TRUE(auction_process_manager_.RequestWorkletService(
worklet_type, origin, site_instance_, process_handle.get(),
NeverInvokedClosure()));
EXPECT_TRUE(process_handle->GetService());
return process_handle;
}
// Requests a process of type GetParam().
std::unique_ptr<AuctionProcessManager::ProcessHandle> GetServiceExpectSuccess(
const url::Origin& origin) {
return GetServiceOfTypeExpectSuccess(GetParam(), origin);
}
base::OnceClosure NeverInvokedClosure() {
return base::BindOnce(
[]() { ADD_FAILURE() << "This should not be called"; });
}
TestBrowserContext test_browser_context_;
MockRenderProcessHostFactory rph_factory_;
scoped_refptr<SiteInstance> site_instance_;
TestAuctionProcessManager auction_process_manager_;
};
class DedicatedStyleAuctionProcessManagerTest
: public AuctionProcessManagerTestBase {
protected:
DedicatedStyleAuctionProcessManagerTest() {
feature_list_.InitAndEnableFeatureWithParameters(
features::kFledgeStartAnticipatoryProcesses,
{{"AnticipatoryProcessHoldTime", "10s"}});
}
SiteInstance* GetSiteInstance() override { return nullptr; }
AuctionProcessManager& GetAuctionProcessManager() override {
return auction_process_manager_;
}
DedicatedStyleTestAuctionProcessManager auction_process_manager_;
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
All,
AuctionProcessManagerTest,
testing::Values(AuctionProcessManager::WorkletType::kSeller,
AuctionProcessManager::WorkletType::kBidder));
INSTANTIATE_TEST_SUITE_P(
All,
DedicatedStyleAuctionProcessManagerTest,
testing::Values(AuctionProcessManager::WorkletType::kSeller,
AuctionProcessManager::WorkletType::kBidder));
TEST_P(AuctionProcessManagerTest, Basic) {
auto worklet = GetServiceExpectSuccess(kOriginA);
EXPECT_TRUE(worklet->GetService());
EXPECT_EQ(1u, GetActiveProcessesOfParamType());
EXPECT_EQ(0u, GetActiveProcesses(GetParamInverse()));
EXPECT_EQ(0u, auction_process_manager_.GetIdleProcessCountForTesting());
}
// Make sure requests for different origins don't share processes, nor do
// sellers and bidders.
//
// This test doesn't use the parameterization, but using TEST_F() for a single
// test would require another test fixture, and so would add more complexity
// than it's worth, for only a single unit test.
TEST_P(AuctionProcessManagerTest, MultipleRequestsForDifferentProcesses) {
auto worlket_a = GetServiceOfTypeExpectSuccess(GetParam(), kOriginA);
auto worklet_b = GetServiceOfTypeExpectSuccess(GetParam(), kOriginB);
auto worklet_of_other_type_a =
GetServiceOfTypeExpectSuccess(GetParamInverse(), kOriginA);
auto worklet_of_other_type_b =
GetServiceOfTypeExpectSuccess(GetParamInverse(), kOriginB);
EXPECT_EQ(2u,
GetActiveProcesses(AuctionProcessManager::WorkletType::kBidder));
EXPECT_EQ(2u,
GetActiveProcesses(AuctionProcessManager::WorkletType::kSeller));
EXPECT_EQ(0u, auction_process_manager_.GetIdleProcessCountForTesting());
EXPECT_NE(worlket_a->GetService(), worklet_b->GetService());
EXPECT_NE(worlket_a->GetService(), worklet_of_other_type_a->GetService());
EXPECT_NE(worlket_a->GetService(), worklet_of_other_type_b->GetService());
EXPECT_NE(worklet_b->GetService(), worklet_of_other_type_a->GetService());
EXPECT_NE(worklet_b->GetService(), worklet_of_other_type_b->GetService());
EXPECT_NE(worklet_of_other_type_a->GetService(),
worklet_of_other_type_b->GetService());
}
TEST_P(AuctionProcessManagerTest, MultipleRequestsForSameProcess) {
// Request 3 processes of the same type for the same origin. All requests
// should get the same process.
auto process_a1 = GetServiceExpectSuccess(kOriginA);
EXPECT_TRUE(process_a1->GetService());
auto process_a2 = GetServiceExpectSuccess(kOriginA);
EXPECT_EQ(process_a1->GetService(), process_a2->GetService());
EXPECT_EQ(1u, GetActiveProcessesOfParamType());
auto process_a3 = GetServiceExpectSuccess(kOriginA);
EXPECT_EQ(process_a1->GetService(), process_a3->GetService());
EXPECT_EQ(1u, GetActiveProcessesOfParamType());
// Request process of the other type with the same origin. It should get a
// different process.
std::unique_ptr<AuctionProcessManager::ProcessHandle> other_process_a1 =
GetServiceOfTypeExpectSuccess(GetParamInverse(), kOriginA);
EXPECT_EQ(1u, GetActiveProcessesOfParamType());
EXPECT_EQ(1u, GetActiveProcesses(GetParamInverse()));
EXPECT_NE(process_a1->GetService(), other_process_a1->GetService());
}
// Test requesting and releasing worklet processes, exceeding the limit. This
// test does not cover the case of multiple requests sharing the same process,
// which is covered by the next test.
TEST_P(AuctionProcessManagerTest, LimitExceeded) {
// The list of operations below assumes at least 3 processes are allowed at
// once.
CHECK_GE(GetMaxProcesses(), 3u);
// Operations applied to the process manager. All requests use unique origins,
// so no need to specify that.
struct Operation {
enum class Op {
// Request the specified number of handle. If there are less than
// GetMaxProcesses() handles already, expects a process to be immediately
// assigned. All requests use different origins from every other request.
kRequestHandles,
// Destroy a handle with the given index. If the index is less than
// GetMaxProcesses(), then expect a ProcessHandle to have its callback
// invoked, if there are more than GetMaxProcesses() already.
kDestroyHandle,
// Same as destroy handle, but additionally destroys the next handle that
// would have been assigned the next available process slot, and makes
// sure the handle after that one gets a process instead.
kDestroyHandleAndNextInQueue,
};
Op op;
// Number of handles to request for kRequestHandles operations.
std::optional<size_t> num_handles;
// Used for kDestroyHandle and kDestroyHandleAndNextInQueue operations.
std::optional<size_t> index;
// The number of total handles expected after this operation. This can be
// inferred by sum of requested handles requests less handles destroyed
// handles, but having it explcitly in the struct makes sure the test cases
// are testing what they're expected to.
size_t expected_total_handles;
// If `num_handles` is set, this represents whether each request caused us
// to hit the limit for the number of processes.
std::vector<bool> hit_limit_after_requesting_handles = {};
};
const Operation kOperationList[] = {
{Operation::Op::kRequestHandles,
/*num_handles=*/GetMaxProcesses(),
/*index=*/std::nullopt,
/*expected_total_handles=*/
GetMaxProcesses(), /*hit_limit_after_requesting_handles=*/
{false, false, false}},
// Check destroying intermediate, last, and first handle when there are no
// queued requests. Keep exactly GetMaxProcesses() requests, to ensure
// there are in fact first, last, and intermediate requests (as long as
// GetMaxProcesses() is at least 3).
{Operation::Op::kDestroyHandle, /*num_handles=*/std::nullopt,
/*index=*/1u, /*expected_total_handles=*/GetMaxProcesses() - 1},
{Operation::Op::kRequestHandles,
/*num_handles=*/1,
/*index=*/std::nullopt,
/*expected_total_handles=*/
GetMaxProcesses(), /*hit_limit_after_requesting_handles=*/
{false}},
{Operation::Op::kDestroyHandle, /*num_handles=*/std::nullopt,
/*index=*/0u, /*expected_total_handles=*/GetMaxProcesses() - 1},
{Operation::Op::kRequestHandles,
/*num_handles=*/1,
/*index=*/std::nullopt,
/*expected_total_handles=*/
GetMaxProcesses(), /*hit_limit_after_requesting_handles=*/
{false}},
{Operation::Op::kDestroyHandle, /*num_handles=*/std::nullopt,
/*index=*/GetMaxProcesses() - 1,
/*expected_total_handles=*/GetMaxProcesses() - 1},
{Operation::Op::kRequestHandles,
/*num_handles=*/1,
/*index=*/std::nullopt,
/*expected_total_handles=*/
GetMaxProcesses(), /*hit_limit_after_requesting_handles=*/
{false}},
// Queue 3 more requests, but delete the last and first of them, to test
// deleting queued requests.
{Operation::Op::kRequestHandles,
/*num_handles=*/3,
/*index=*/std::nullopt,
/*expected_total_handles=*/GetMaxProcesses() +
3, /*hit_limit_after_requesting_handles=*/
{true, true, true}},
{Operation::Op::kDestroyHandle, /*num_handles=*/std::nullopt,
/*index=*/GetMaxProcesses(),
/*expected_total_handles=*/GetMaxProcesses() + 2},
{Operation::Op::kDestroyHandle, /*num_handles=*/std::nullopt,
/*index=*/GetMaxProcesses() + 1,
/*expected_total_handles=*/GetMaxProcesses() + 1},
// Request 4 more processes.
{Operation::Op::kRequestHandles,
/*num_handles=*/4,
/*index=*/std::nullopt,
/*expected_total_handles=*/GetMaxProcesses() +
5, /*hit_limit_after_requesting_handles=*/
{true, true, true, true}},
// Destroy the first handle and the first pending in the queue immediately
// afterwards. The next pending request should get a process.
{Operation::Op::kDestroyHandleAndNextInQueue,
/*num_handles=*/std::nullopt, /*index=*/0u,
/*expected_total_handles=*/GetMaxProcesses() + 3},
// Destroy three more requests that have been asssigned processes, being
// sure to destroy the first, last, and some request request with nether,
// amongst requests with assigned processes.
{Operation::Op::kDestroyHandle, /*num_handles=*/std::nullopt,
/*index=*/GetMaxProcesses() - 1,
/*expected_total_handles=*/GetMaxProcesses() + 2},
{Operation::Op::kDestroyHandle, /*num_handles=*/std::nullopt,
/*index=*/0u, /*expected_total_handles=*/GetMaxProcesses() + 1},
{Operation::Op::kDestroyHandle, /*num_handles=*/std::nullopt,
/*index=*/1u, /*expected_total_handles=*/GetMaxProcesses()},
};
struct ProcessHandleData {
std::unique_ptr<AuctionProcessManager::ProcessHandle> process_handle =
std::make_unique<AuctionProcessManager::ProcessHandle>();
std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
};
std::vector<ProcessHandleData> data;
// Used to create distinct origins for each handle
int num_origins = 0;
for (const auto& operation : kOperationList) {
switch (operation.op) {
case Operation::Op::kRequestHandles:
for (size_t i = 0; i < *operation.num_handles; ++i) {
size_t original_size = data.size();
data.emplace_back(ProcessHandleData());
url::Origin distinct_origin = url::Origin::Create(
GURL(base::StringPrintf("https://%i.test", ++num_origins)));
base::HistogramTester histogram_tester;
ASSERT_EQ(original_size < GetMaxProcesses(),
auction_process_manager_.RequestWorkletService(
GetParam(), distinct_origin, site_instance_,
data.back().process_handle.get(),
data.back().run_loop->QuitClosure()));
RequestWorkletServiceOutcome expected_result =
operation.hit_limit_after_requesting_handles[i]
? RequestWorkletServiceOutcome::kHitProcessLimit
: RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess;
histogram_tester.ExpectUniqueSample(
base::StrCat(
{"Ads.InterestGroup.Auction.",
GetParam() == AuctionProcessManager::WorkletType::kSeller
? "Seller."
: "Buyer.",
"RequestWorkletServiceOutcome"}),
expected_result,
/*expected_bucket_count=*/1);
}
break;
case Operation::Op::kDestroyHandle: {
size_t original_size = data.size();
ASSERT_GT(data.size(), *operation.index);
data.erase(data.begin() + *operation.index);
// If destroying one of the first GetMaxProcesses() handles, and
// there were more than GetMaxProcesses() handles before, the
// first of the handles waiting on a process should get a process.
if (*operation.index < GetMaxProcesses() &&
original_size > GetMaxProcesses()) {
data[GetMaxProcesses() - 1].run_loop->Run();
EXPECT_TRUE(data[GetMaxProcesses() - 1].process_handle->GetService());
}
break;
}
case Operation::Op::kDestroyHandleAndNextInQueue: {
ASSERT_GT(data.size(), *operation.index);
ASSERT_GT(data.size(), GetMaxProcesses() + 1);
data.erase(data.begin() + *operation.index);
data.erase(data.begin() + GetMaxProcesses());
data[GetMaxProcesses() - 1].run_loop->Run();
EXPECT_TRUE(data[GetMaxProcesses() - 1].process_handle->GetService());
break;
}
}
EXPECT_EQ(operation.expected_total_handles, data.size());
// The first GetMaxProcesses() ProcessHandles should all have
// assigned processes, which should all be distinct.
for (size_t i = 0; i < data.size() && i < GetMaxProcesses(); ++i) {
EXPECT_TRUE(data[i].process_handle->GetService());
for (size_t j = 0; j < i; ++j) {
EXPECT_NE(data[i].process_handle->GetService(),
data[j].process_handle->GetService());
}
}
// Make sure all pending tasks have been run.
base::RunLoop().RunUntilIdle();
// All other requests should not have been assigned processes yet.
for (size_t i = GetMaxProcesses(); i < data.size(); ++i) {
EXPECT_FALSE(data[i].run_loop->AnyQuitCalled());
EXPECT_FALSE(data[i].process_handle->GetService());
}
}
}
// Check the process sharing logic - specifically, that requests share processes
// when origins match, and that handles that share a process only count once
// towrads the process limit the process limit.
TEST_P(AuctionProcessManagerTest, ProcessSharing) {
// This test assumes GetMaxProcesses() is greater than 1.
DCHECK_GT(GetMaxProcesses(), 1u);
// Make 2*GetMaxProcesses() requests for each of GetMaxProcesses() different
// origins. All requests should succeed immediately.
std::vector<std::list<std::unique_ptr<AuctionProcessManager::ProcessHandle>>>
processes(GetMaxProcesses());
for (size_t origin_index = 0; origin_index < GetMaxProcesses();
++origin_index) {
url::Origin origin = url::Origin::Create(
GURL(base::StringPrintf("https://%zu.test", origin_index)));
base::HistogramTester histogram_tester;
for (size_t i = 0; i < 2 * GetMaxProcesses(); ++i) {
processes[origin_index].emplace_back(GetServiceExpectSuccess(origin));
// All requests for the same origin share a process.
EXPECT_EQ(processes[origin_index].back()->GetService(),
processes[origin_index].front()->GetService());
EXPECT_EQ(origin_index + 1, GetActiveProcessesOfParamType());
}
histogram_tester.ExpectBucketCount(
base::StrCat({"Ads.InterestGroup.Auction.",
GetParam() == AuctionProcessManager::WorkletType::kSeller
? "Seller."
: "Buyer.",
"RequestWorkletServiceOutcome"}),
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess, 1);
histogram_tester.ExpectBucketCount(
base::StrCat({"Ads.InterestGroup.Auction.",
GetParam() == AuctionProcessManager::WorkletType::kSeller
? "Seller."
: "Buyer.",
"RequestWorkletServiceOutcome"}),
RequestWorkletServiceOutcome::kUsedExistingDedicatedProcess,
2 * GetMaxProcesses() - 1);
// Each origin should have a different process.
for (size_t origin_index2 = 0; origin_index2 < origin_index;
++origin_index2) {
EXPECT_NE(processes[origin_index].front()->GetService(),
processes[origin_index2].front()->GetService());
}
}
// Make two process requests for kOriginA and one one for kOriginB, which
// should all be blocked due to the process limit being reached.
base::RunLoop run_loop_delayed_a1;
auto process_delayed_a1 =
std::make_unique<AuctionProcessManager::ProcessHandle>();
ASSERT_FALSE(auction_process_manager_.RequestWorkletService(
GetParam(), kOriginA, site_instance_, process_delayed_a1.get(),
run_loop_delayed_a1.QuitClosure()));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(run_loop_delayed_a1.AnyQuitCalled());
EXPECT_FALSE(process_delayed_a1->GetService());
EXPECT_EQ(GetMaxProcesses(), GetActiveProcessesOfParamType());
base::RunLoop run_loop_delayed_a2;
auto process_delayed_a2 =
std::make_unique<AuctionProcessManager::ProcessHandle>();
ASSERT_FALSE(auction_process_manager_.RequestWorkletService(
GetParam(), kOriginA, site_instance_, process_delayed_a2.get(),
run_loop_delayed_a2.QuitClosure()));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(run_loop_delayed_a2.AnyQuitCalled());
EXPECT_FALSE(process_delayed_a2->GetService());
EXPECT_EQ(GetMaxProcesses(), GetActiveProcessesOfParamType());
base::RunLoop run_loop_delayed_b;
auto process_delayed_b =
std::make_unique<AuctionProcessManager::ProcessHandle>();
ASSERT_FALSE(auction_process_manager_.RequestWorkletService(
GetParam(), kOriginB, site_instance_, process_delayed_b.get(),
run_loop_delayed_b.QuitClosure()));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(run_loop_delayed_b.AnyQuitCalled());
EXPECT_FALSE(process_delayed_b->GetService());
EXPECT_EQ(GetMaxProcesses(), GetActiveProcessesOfParamType());
// Release processes for first origin one at a time, until only one is left.
// The pending requests for kOriginA and kOriginB should remain stalled.
while (processes[0].size() > 1u) {
processes[0].pop_front();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(run_loop_delayed_a1.AnyQuitCalled());
EXPECT_FALSE(process_delayed_a1->GetService());
EXPECT_FALSE(run_loop_delayed_a2.AnyQuitCalled());
EXPECT_FALSE(process_delayed_a2->GetService());
EXPECT_FALSE(run_loop_delayed_b.AnyQuitCalled());
EXPECT_FALSE(process_delayed_b->GetService());
EXPECT_EQ(GetMaxProcesses(), GetActiveProcessesOfParamType());
}
// Remove the final process for the first origin. It should queue a callback
// to resume the kOriginA requests (prioritized alphabetically), but nothing
// should happen until the callbacks are invoked.
processes[0].pop_front();
EXPECT_FALSE(run_loop_delayed_a1.AnyQuitCalled());
EXPECT_FALSE(process_delayed_a1->GetService());
EXPECT_FALSE(run_loop_delayed_a2.AnyQuitCalled());
EXPECT_FALSE(process_delayed_a2->GetService());
EXPECT_FALSE(run_loop_delayed_b.AnyQuitCalled());
EXPECT_FALSE(process_delayed_b->GetService());
// The two kOriginA callbacks should be invoked when the message loop next
// spins. The two kOriginA requests should now have been assigned the same
// service, while the kOriginB request is still pending.
run_loop_delayed_a1.Run();
run_loop_delayed_a2.Run();
EXPECT_TRUE(process_delayed_a1->GetService());
EXPECT_TRUE(process_delayed_a2->GetService());
EXPECT_EQ(process_delayed_a1->GetService(), process_delayed_a2->GetService());
EXPECT_FALSE(run_loop_delayed_b.AnyQuitCalled());
EXPECT_FALSE(process_delayed_b->GetService());
EXPECT_EQ(GetMaxProcesses(), GetActiveProcessesOfParamType());
// Freeing one of the two kOriginA processes should have no effect.
process_delayed_a2.reset();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(run_loop_delayed_b.AnyQuitCalled());
EXPECT_FALSE(process_delayed_b->GetService());
// Freeing the other one should queue a task to give the kOriginB requests a
// process.
process_delayed_a1.reset();
EXPECT_FALSE(run_loop_delayed_b.AnyQuitCalled());
EXPECT_FALSE(process_delayed_b->GetService());
run_loop_delayed_b.Run();
EXPECT_TRUE(process_delayed_b->GetService());
EXPECT_EQ(GetMaxProcesses(), GetActiveProcessesOfParamType());
}
TEST_P(AuctionProcessManagerTest, DestroyHandlesWithPendingRequests) {
// Make GetMaxProcesses() requests for worklets with different origins.
std::list<std::unique_ptr<AuctionProcessManager::ProcessHandle>> processes;
for (size_t i = 0; i < GetMaxProcesses(); ++i) {
url::Origin origin =
url::Origin::Create(GURL(base::StringPrintf("https://%zu.test", i)));
processes.emplace_back(GetServiceExpectSuccess(origin));
}
// Make a pending request.
auto pending_process1 =
std::make_unique<AuctionProcessManager::ProcessHandle>();
ASSERT_FALSE(auction_process_manager_.RequestWorkletService(
GetParam(), kOriginA, site_instance_, pending_process1.get(),
NeverInvokedClosure()));
EXPECT_EQ(1u, GetPendingRequestsOfParamType());
// Destroy the pending request. Its callback should not be invoked.
pending_process1.reset();
EXPECT_EQ(0u, GetPendingRequestsOfParamType());
base::RunLoop().RunUntilIdle();
// Make two more pending process requests.
auto pending_process2 =
std::make_unique<AuctionProcessManager::ProcessHandle>();
ASSERT_FALSE(auction_process_manager_.RequestWorkletService(
GetParam(), kOriginA, site_instance_, pending_process2.get(),
NeverInvokedClosure()));
auto pending_process3 =
std::make_unique<AuctionProcessManager::ProcessHandle>();
base::RunLoop pending_process3_run_loop;
ASSERT_FALSE(auction_process_manager_.RequestWorkletService(
GetParam(), kOriginB, site_instance_, pending_process3.get(),
pending_process3_run_loop.QuitClosure()));
EXPECT_EQ(2u, GetPendingRequestsOfParamType());
// Delete a process. This should result in a posted task to give
// `pending_process2` a process.
processes.pop_front();
EXPECT_EQ(1u, GetPendingRequestsOfParamType());
// Destroy `pending_process2` before it gets passed a process.
pending_process2.reset();
// `pending_process3` should get a process instead.
pending_process3_run_loop.Run();
EXPECT_TRUE(pending_process3->GetService());
EXPECT_EQ(0u, auction_process_manager_.GetPendingSellerRequestsForTesting());
}
// Check that process crash is handled properly, by creating a new process.
TEST_P(AuctionProcessManagerTest, ProcessCrash) {
auto process = GetServiceExpectSuccess(kOriginA);
auction_worklet::mojom::AuctionWorkletService* service =
process->GetService();
EXPECT_TRUE(service);
EXPECT_EQ(1u, GetActiveProcessesOfParamType());
// Close pipes. No new pipe should be created.
auction_process_manager_.ClosePipes();
EXPECT_EQ(0u, GetActiveProcessesOfParamType());
// Requesting a new process will create a new pipe.
auto process2 = GetServiceExpectSuccess(kOriginA);
auction_worklet::mojom::AuctionWorkletService* service2 =
process2->GetService();
EXPECT_TRUE(service2);
EXPECT_NE(service, service2);
EXPECT_NE(process, process2);
EXPECT_EQ(1u, GetActiveProcessesOfParamType());
}
TEST_P(AuctionProcessManagerTest, DisconnectBeforeDelete) {
// Exercise the codepath where the mojo pipe to a service is broken when
// a handle to its process is still alive, to make sure this is handled
// correctly (rather than hitting a DCHECK on incorrect refcounting).
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a1 =
GetServiceExpectSuccess(kOriginA);
auction_process_manager_.ClosePipes();
task_environment_.RunUntilIdle();
handle_a1.reset();
task_environment_.RunUntilIdle();
}
TEST_P(AuctionProcessManagerTest, ProcessDeleteBeforeHandle) {
// Exercise the codepath where a RenderProcessHostDestroyed is received, to
// make sure it doesn't crash.
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a1 =
GetServiceExpectSuccess(kOriginA);
for (std::unique_ptr<MockRenderProcessHost>& proc :
*rph_factory_.GetProcesses()) {
proc.reset();
}
task_environment_.RunUntilIdle();
handle_a1.reset();
task_environment_.RunUntilIdle();
}
TEST_F(AuctionProcessManagerTest, PidLookup) {
auto handle = GetServiceOfTypeExpectSuccess(
AuctionProcessManager::WorkletType::kSeller, kOriginA);
base::ProcessId expected_pid = base::Process::Current().Pid();
// Request PID twice. Should happen asynchronously, but only use one RPC.
base::RunLoop run_loop0, run_loop1;
bool got_pid0 = false, got_pid1 = false;
std::optional<base::ProcessId> pid0 =
handle->GetPid(base::BindLambdaForTesting(
[&run_loop0, &got_pid0, expected_pid](base::ProcessId pid) {
EXPECT_EQ(expected_pid, pid);
got_pid0 = true;
run_loop0.Quit();
}));
EXPECT_FALSE(pid0.has_value());
std::optional<base::ProcessId> pid1 =
handle->GetPid(base::BindLambdaForTesting(
[&run_loop1, &got_pid1, expected_pid](base::ProcessId pid) {
EXPECT_EQ(expected_pid, pid);
got_pid1 = true;
run_loop1.Quit();
}));
EXPECT_FALSE(pid1.has_value());
for (std::unique_ptr<MockRenderProcessHost>& proc :
*rph_factory_.GetProcesses()) {
proc->SimulateReady();
}
run_loop0.Run();
EXPECT_TRUE(got_pid0);
run_loop1.Run();
EXPECT_TRUE(got_pid1);
// Next attempt should be synchronous.
std::optional<base::ProcessId> pid2 =
handle->GetPid(base::BindOnce([](base::ProcessId pid) {
ADD_FAILURE() << "Should not get to callback in pid2 case";
}));
ASSERT_TRUE(pid2.has_value());
EXPECT_EQ(expected_pid, pid2.value());
}
TEST_F(AuctionProcessManagerTest, PidLookupAlreadyRunning) {
// "Launch" the appropriate process before we even ask for it, and mark its
// launch as completed. |frame_site_instance| will help keep it alive.
scoped_refptr<SiteInstance> frame_site_instance =
site_instance_->GetRelatedSiteInstance(kOriginA.GetURL());
frame_site_instance->GetProcess()->Init();
for (std::unique_ptr<MockRenderProcessHost>& proc :
*rph_factory_.GetProcesses()) {
proc->SimulateReady();
}
auto handle = GetServiceOfTypeExpectSuccess(
AuctionProcessManager::WorkletType::kSeller, kOriginA);
base::ProcessId expected_pid = base::Process::Current().Pid();
// Request PID twice. Should happen asynchronously, but only use one RPC.
std::optional<base::ProcessId> pid0 =
handle->GetPid(base::BindOnce([](base::ProcessId pid) {
ADD_FAILURE() << "Should not get to callback in pid0 case";
}));
ASSERT_TRUE(pid0.has_value());
EXPECT_EQ(expected_pid, pid0.value());
std::optional<base::ProcessId> pid1 =
handle->GetPid(base::BindOnce([](base::ProcessId pid) {
ADD_FAILURE() << "Should not get to callback in pid1 case";
}));
ASSERT_TRUE(pid1.has_value());
EXPECT_EQ(expected_pid, pid1.value());
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
DoesNotStartAnticipatoryProcessIfFeatureDisabled) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndDisableFeature(
features::kFledgeStartAnticipatoryProcesses);
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(0);
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
ProcessLimitIsRespected_AnticipatoryProcessesOnly) {
// Create the maximum possible # of anticipatory processes.
for (size_t i = 0; i < GetMaxProcesses(); ++i) {
url::Origin origin =
url::Origin::Create(GURL(base::StringPrintf("https://%i.test", i)));
MaybeStartAnticipatoryProcess(origin, GetParam());
CheckOnlyIdleProcessesWithCount(1 + i);
}
// We can't make more.
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(GetMaxProcesses());
}
// Make sure the process limit is respected when we have a combination of
// anticipatory and active processes. Make sure we can make processes of
// the other type (active and idle) even if we've hit the limit of one type.
TEST_P(DedicatedStyleAuctionProcessManagerTest,
ProcessLimitIsRespected_ActiveAndAnticipatoryProcesses) {
// Alternate creating anticipatory and active processes. Each active processes
// will consume 1 anticipatory process. After the for loop, we end up with 1
// anticipatory process and GetMaxProcesses() - 1 active processes.
MaybeStartAnticipatoryProcess(
url::Origin::Create(GURL("https://worklet.test")), GetParam());
CheckOnlyIdleProcessesWithCount(1);
std::vector<std::unique_ptr<AuctionProcessManager::ProcessHandle>> handles;
for (size_t i = 0; i < GetMaxProcesses() - 1; ++i) {
url::Origin origin =
url::Origin::Create(GURL(base::StringPrintf("https://%i.test", i)));
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(handles.back().get(), origin, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
EXPECT_EQ(GetActiveProcessesOfParamType(), handles.size());
origin = url::Origin::Create(
GURL(base::StringPrintf("https://%i_anticipatory.test", i)));
MaybeStartAnticipatoryProcess(origin, GetParam());
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
EXPECT_EQ(GetActiveProcessesOfParamType(), handles.size());
}
// Can't make more anticipatory processes of this type.
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
EXPECT_EQ(GetActiveProcessesOfParamType(), GetMaxProcesses() - 1);
// Can make an anticipatory process of the other type.
MaybeStartAnticipatoryProcess(kOriginB, GetParamInverse());
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 2u);
EXPECT_EQ(GetActiveProcessesOfParamType(), GetMaxProcesses() - 1);
// We should still be able to create another worklet with the
// anticipatory process we made of this type.
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(handles.back().get(), kOriginA, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
EXPECT_EQ(GetActiveProcessesOfParamType(), GetMaxProcesses());
// Can't make more processes of this type.
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(handles.back().get(), kOriginB, GetParam(),
/*expect_success=*/false,
RequestWorkletServiceOutcome::kHitProcessLimit);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
EXPECT_EQ(GetActiveProcessesOfParamType(), GetMaxProcesses());
// Can make a process of the other type.
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(handles.back().get(), kOriginC, GetParamInverse(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
EXPECT_EQ(GetActiveProcessesOfParamType(), GetMaxProcesses());
handles.clear();
EXPECT_EQ(GetActiveProcessesOfParamType(), 0u);
// Now we should no longer be at the process limit. We can make more
// processes.
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(
handles.back().get(), url::Origin::Create(GURL("https://worklet2.test")),
GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
MaybeStartAnticipatoryProcess(
url::Origin::Create(GURL("https://worklet3.test")), GetParam());
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
DoNotStartMultipleProcessesSameOriginAndType) {
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
CanStartProcessesWithSameOriginIfOneIsSellerAndOneIsBuyer) {
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
MaybeStartAnticipatoryProcess(kOriginA, GetParamInverse());
CheckOnlyIdleProcessesWithCount(2);
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
DoNotStartProcessWithSameOriginAndTypeAsExistingProcess) {
AuctionProcessManager::ProcessHandle process_handle;
RequestWorkletService(
&process_handle, kOriginA, GetParam(), /*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
ProcessCanBeAssignedToHandleOfSameOrDifferentOriginAndType) {
for (const auto& origin_to_assign : {kOriginA, kOriginB}) {
SCOPED_TRACE(origin_to_assign);
for (AuctionProcessManager::WorkletType worklet_type_to_assign :
{GetParam(), GetParamInverse()}) {
SCOPED_TRACE(static_cast<int>(worklet_type_to_assign));
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
AuctionProcessManager::ProcessHandle handle;
RequestWorkletService(&handle, origin_to_assign, worklet_type_to_assign,
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
// The `process_handle` gets deleted between iterations of the for loop
// so we'll only have 1 active process at this point.
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
EXPECT_EQ(GetActiveProcesses(worklet_type_to_assign), 1u);
}
}
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
AssignsIdleProcessOfSameTypeOnlyAfterReachingLimit) {
// Make an anticipatory process of the other type. This will not be
// convertible to a process of our type after we hit the limit.
MaybeStartAnticipatoryProcess(kOriginA, GetParamInverse());
CheckOnlyIdleProcessesWithCount(1);
for (size_t i = 0; i < GetMaxProcesses(); ++i) {
url::Origin origin =
url::Origin::Create(GURL(base::StringPrintf("https://%i.test", i)));
MaybeStartAnticipatoryProcess(origin, GetParam());
CheckOnlyIdleProcessesWithCount(2 + i);
}
// Try assigning these to different origins.
std::vector<std::unique_ptr<AuctionProcessManager::ProcessHandle>> handles;
for (size_t i = 0; i < GetMaxProcesses(); ++i) {
url::Origin origin =
url::Origin::Create(GURL(base::StringPrintf("https://%i_2.test", i)));
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(handles.back().get(), origin, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
// We should assign the oldest anticipatory process of the same type because
// we've hit the process limit -- we'd prefer to assign a newer anticipatory
// process than to use the older process & have to remove one of our
// anticipatory processes. All anticipatory processes were of type
// GetParam() except the first one.
EXPECT_EQ(
auction_process_manager_.ProcessCreationOrder(handles.back().get()),
i + 1u);
EXPECT_EQ(GetActiveProcessesOfParamType(), i + 1u);
}
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
ProcessesCanBeAssignedInDifferentOrderFromHowTheyWereMade) {
std::vector<url::Origin> origins{kOriginA, kOriginB, kOriginC};
for (url::Origin origin : origins) {
MaybeStartAnticipatoryProcess(origin, GetParam());
}
CheckOnlyIdleProcessesWithCount(3);
std::vector<std::unique_ptr<AuctionProcessManager::ProcessHandle>> handles;
for (size_t i = 0; i < 3; i++) {
url::Origin origin = origins[2 - i];
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle =
std::make_unique<AuctionProcessManager::ProcessHandle>();
RequestWorkletService(handle.get(), origin, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
// We assigned the oldest available idle process.
EXPECT_EQ(auction_process_manager_.ProcessCreationOrder(handle.get()), i);
EXPECT_EQ(GetActiveProcessesOfParamType(), i + 1u);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 2 - i);
handles.push_back(std::move(handle));
}
}
// Make sure we're not creating duplicate processes for
// an origin, even if we've assigned one of our anticipatory
// processes to a worklet.
TEST_P(DedicatedStyleAuctionProcessManagerTest,
DoesNotRecreateAnticipatoryProcessForOriginAfterAssigned) {
url::Origin origins[] = {kOriginA, kOriginB, kOriginC};
for (const url::Origin& origin_to_request_service : origins) {
CheckOnlyIdleProcessesWithCount(0);
for (const url::Origin& origin_for_anticipatory_process : origins) {
MaybeStartAnticipatoryProcess(origin_for_anticipatory_process,
GetParam());
}
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 3u);
AuctionProcessManager::ProcessHandle handle;
RequestWorkletService(&handle, origin_to_request_service, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 2u);
for (const url::Origin& origin_for_anticipatory_process : origins) {
MaybeStartAnticipatoryProcess(origin_for_anticipatory_process,
GetParam());
}
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 2u);
// Reset the number of processes for the next loop by letting the idle
// processes expire. The active process will go out of scope.
task_environment_.FastForwardBy(
features::kFledgeStartAnticipatoryProcessExpirationTime.Get());
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
}
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
RemovesProcessAfterExpirationTime) {
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
task_environment_.FastForwardBy(
features::kFledgeStartAnticipatoryProcessExpirationTime.Get() -
base::Milliseconds(1));
CheckOnlyIdleProcessesWithCount(1);
task_environment_.FastForwardBy(base::Milliseconds(1));
CheckOnlyIdleProcessesWithCount(0);
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
CorrectProcessGetsDeletedAfterExpiration) {
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
task_environment_.FastForwardBy(base::Milliseconds(1));
MaybeStartAnticipatoryProcess(kOriginB, GetParam());
CheckOnlyIdleProcessesWithCount(2);
// One processes should be deleted after the first
// features::kFledgeStartAnticipatoryProcessExpirationTime
// passes.
task_environment_.FastForwardBy(
features::kFledgeStartAnticipatoryProcessExpirationTime.Get() -
base::Milliseconds(2));
CheckOnlyIdleProcessesWithCount(2);
task_environment_.FastForwardBy(base::Milliseconds(1));
CheckOnlyIdleProcessesWithCount(1);
// Should not add a new idle process of kOriginB. We shouldn't
// have deleted that process.
MaybeStartAnticipatoryProcess(kOriginB, GetParam());
CheckOnlyIdleProcessesWithCount(1);
// Should add a new idle process of kOriginA.
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(2);
}
TEST_P(DedicatedStyleAuctionProcessManagerTest,
DoesNotRemoveActiveProcessAfterExpirationTime) {
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
AuctionProcessManager::ProcessHandle handle;
RequestWorkletService(&handle, kOriginA, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
task_environment_.FastForwardBy(
features::kFledgeStartAnticipatoryProcessExpirationTime.Get());
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
}
class PartialSiteIsolationContentBrowserClient
: public TestContentBrowserClient {
public:
bool ShouldEnableStrictSiteIsolation() override { return false; }
bool ShouldDisableSiteIsolation(
SiteIsolationMode site_isolation_mode) override {
switch (site_isolation_mode) {
case SiteIsolationMode::kStrictSiteIsolation:
return true;
case SiteIsolationMode::kPartialSiteIsolation:
return false;
}
}
};
// A base class for AuctionProcessManager tests that sets up the basic test
// environment. Since this class creates SiteInstances and (implicitly)
// BrowsingInstances, it's important that it knows whether to use
// kOriginKeyedProcessesByDefault at the time it's constructed.
class InRendererAuctionProcessManagerTestBase
: public AuctionProcessManagerTestBase {
public:
explicit InRendererAuctionProcessManagerTestBase(
bool disable_origin_keyed_processes_by_default) {
// Note: if we're going to disable kOriginKeyedProcessesByDefault, it's
// important to do it here before we create any SiteInstances, since that
// will create BrowsingInstances, and each BrowsingInstance will create
// a default isolation state based on kOriginKeyedProcessesByDefault.
std::vector<base::test::FeatureRef> disabled_features;
if (disable_origin_keyed_processes_by_default) {
disabled_features.push_back(features::kOriginKeyedProcessesByDefault);
}
feature_list_.InitWithFeaturesAndParameters(
/*enabled_features=*/
{{features::kFledgeStartAnticipatoryProcesses,
{{"AnticipatoryProcessHoldTime", "3s"}}}},
/*disabled_features=*/
disabled_features);
SiteInstance::StartIsolatingSite(
&test_browser_context_, kIsolatedOrigin.GetURL(),
ChildProcessSecurityPolicy::IsolatedOriginSource::TEST);
// Created these after StartIsolatingSite so they are affected by it.
site_instance1_ = SiteInstance::Create(&test_browser_context_);
site_instance2_ = SiteInstance::Create(&test_browser_context_);
}
void SetUp() override {
RenderProcessHostImpl::set_render_process_host_factory_for_testing(
&rph_factory_);
SiteIsolationPolicy::DisableFlagCachingForTesting();
}
void TearDown() override {
RenderProcessHostImpl::set_render_process_host_factory_for_testing(nullptr);
}
AuctionProcessManager& GetAuctionProcessManager() override {
return auction_process_manager_;
}
SiteInstance* GetSiteInstance() override { return site_instance1_.get(); }
std::unique_ptr<AuctionProcessManager::ProcessHandle>
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType worklet_type,
scoped_refptr<SiteInstance> site_instance,
const url::Origin& origin) {
auto process_handle =
std::make_unique<AuctionProcessManager::ProcessHandle>();
EXPECT_TRUE(auction_process_manager_.RequestWorkletService(
worklet_type, origin, site_instance, process_handle.get(),
NeverInvokedClosure()));
EXPECT_TRUE(process_handle->GetService());
return process_handle;
}
base::OnceClosure NeverInvokedClosure() {
return base::BindOnce(
[]() { ADD_FAILURE() << "This should not be called"; });
}
TestBrowserContext test_browser_context_;
MockRenderProcessHostFactory rph_factory_;
// Make sure `scoped_command_line_` gets destructed after the
// `auction_process_manager_`. Otherwise idle worklet processes
// may try to read it after destruction.
base::test::ScopedCommandLine scoped_command_line_;
// `site_instance1_` and `site_instance2_` are in different browsing
// instances.
scoped_refptr<SiteInstance> site_instance1_, site_instance2_;
InRendererAuctionProcessManager auction_process_manager_;
const url::Origin kIsolatedOrigin =
url::Origin::Create(GURL("https://bank.test"));
private:
base::test::ScopedFeatureList feature_list_;
};
// A test class for AuctionProcessManager tests that require desktop-like
// behavior, i.e. site-per-process is enabled, and
// kOriginKeyedProcessesByDefault and process sharing for non-default
// SiteInstances is allowed.
class InRendererAuctionProcessManagerTest
: public InRendererAuctionProcessManagerTestBase {
public:
InRendererAuctionProcessManagerTest()
: InRendererAuctionProcessManagerTestBase(
/*disable_origin_keyed_processes_by_default=*/false) {}
void SetUp() override {
InRendererAuctionProcessManagerTestBase::SetUp();
scoped_command_line_.GetProcessCommandLine()->AppendSwitch(
switches::kSitePerProcess);
}
};
INSTANTIATE_TEST_SUITE_P(
All,
InRendererAuctionProcessManagerTest,
testing::Values(AuctionProcessManager::WorkletType::kSeller,
AuctionProcessManager::WorkletType::kBidder));
// A test class for AuctionProcessManager tests that require Android-like
// behavior, i.e. site-per-process is disabled, kOriginKeyedProcessesByDefault
// is disabled, and process sharing is set for default SiteInstances only.
class InRendererAuctionProcessManagerTest_NoOriginKeyedProcessesByDefault
: public InRendererAuctionProcessManagerTestBase {
public:
InRendererAuctionProcessManagerTest_NoOriginKeyedProcessesByDefault()
: InRendererAuctionProcessManagerTestBase(
/*disable_origin_keyed_processes_by_default=*/true) {
feature_list.InitWithFeatures(
/*enabled_features=*/{features::
kProcessSharingWithDefaultSiteInstances},
/*disabled_features=*/{
features::kProcessSharingWithStrictSiteInstances});
}
void SetUp() override {
InRendererAuctionProcessManagerTestBase::SetUp();
original_browser_client_ =
content::SetBrowserClientForTesting(&browser_client_);
scoped_command_line_.GetProcessCommandLine()->RemoveSwitch(
switches::kSitePerProcess);
}
void TearDown() override {
content::SetBrowserClientForTesting(original_browser_client_);
InRendererAuctionProcessManagerTestBase::TearDown();
}
private:
base::test::ScopedFeatureList feature_list;
PartialSiteIsolationContentBrowserClient browser_client_;
raw_ptr<ContentBrowserClient> original_browser_client_;
};
TEST_F(InRendererAuctionProcessManagerTest_NoOriginKeyedProcessesByDefault,
AndroidLike) {
base::HistogramTester histogram_tester;
// Launch some services in different origins and browsing instances.
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a1 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kOriginA);
int id_a1 = handle_a1->GetRenderProcessHostForTesting()->GetID();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a2 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance2_, kOriginA);
int id_a2 = handle_a2->GetRenderProcessHostForTesting()->GetID();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_b1 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kOriginB);
int id_b1 = handle_b1->GetRenderProcessHostForTesting()->GetID();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_b2 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance2_, kOriginB);
int id_b2 = handle_b2->GetRenderProcessHostForTesting()->GetID();
// Non-site-isolation requiring origins can share processes, but not across
// different browsing instances.
EXPECT_NE(id_a1, id_a2);
EXPECT_EQ(id_a1, id_b1);
EXPECT_NE(id_a1, id_b2);
EXPECT_NE(id_a2, id_b1);
EXPECT_EQ(id_a2, id_b2);
EXPECT_NE(id_b1, id_b2);
histogram_tester.ExpectUniqueSample(
"Ads.InterestGroup.Auction.Seller.RequestWorkletServiceOutcome",
RequestWorkletServiceOutcome::kUsedSharedProcess, 4);
// Site-isolation requiring origins are distinct from non-isolated ones, but
// can share across browsing instances.
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_i1 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kIsolatedOrigin);
int id_i1 = handle_i1->GetRenderProcessHostForTesting()->GetID();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_i2 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance2_, kIsolatedOrigin);
int id_i2 = handle_i2->GetRenderProcessHostForTesting()->GetID();
EXPECT_EQ(id_i1, id_i2);
EXPECT_NE(id_i1, id_a1);
EXPECT_NE(id_i1, id_a2);
EXPECT_NE(id_i1, id_b1);
EXPECT_NE(id_i1, id_b2);
histogram_tester.ExpectBucketCount(
"Ads.InterestGroup.Auction.Seller.RequestWorkletServiceOutcome",
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess, 1);
histogram_tester.ExpectBucketCount(
"Ads.InterestGroup.Auction.Seller.RequestWorkletServiceOutcome",
RequestWorkletServiceOutcome::kUsedExistingDedicatedProcess, 1);
}
// Test that anticipatory processes are not created for origins that can use the
// shared renderer process.
TEST_F(InRendererAuctionProcessManagerTest_NoOriginKeyedProcessesByDefault,
MaybeStartAnticipatoryProcess_DoesNotStartIfSharedProcessPossible) {
MaybeStartAnticipatoryProcess(kOriginA,
AuctionProcessManager::WorkletType::kBidder);
CheckOnlyIdleProcessesWithCount(0);
}
// Test that anticipatory processes can be created for isolated origins.
TEST_F(InRendererAuctionProcessManagerTest_NoOriginKeyedProcessesByDefault,
MaybeStartAnticipatoryProcess_StartsProcessForIsolatedOrigin) {
MaybeStartAnticipatoryProcess(kIsolatedOrigin,
AuctionProcessManager::WorkletType::kBidder);
CheckOnlyIdleProcessesWithCount(1);
// Don't use this process for an origin that can use a shared process.
AuctionProcessManager::ProcessHandle handle1, handle2;
RequestWorkletService(&handle1, kOriginA,
AuctionProcessManager::WorkletType::kBidder,
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedSharedProcess);
CheckOnlyIdleProcessesWithCount(1);
// Can use this process for the same isolated origin.
RequestWorkletService(
&handle2, kIsolatedOrigin, AuctionProcessManager::WorkletType::kBidder,
/*expect_success=*/true, RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
EXPECT_EQ(GetActiveProcesses(AuctionProcessManager::WorkletType::kBidder),
1u);
}
TEST_F(InRendererAuctionProcessManagerTest, DesktopLike) {
base::HistogramTester histogram_tester;
// Launch some services in different origins and browsing instances.
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a1 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kOriginA);
int id_a1 = handle_a1->GetRenderProcessHostForTesting()->GetID();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a2 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance2_, kOriginA);
int id_a2 = handle_a2->GetRenderProcessHostForTesting()->GetID();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_b1 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kOriginB);
int id_b1 = handle_b1->GetRenderProcessHostForTesting()->GetID();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_b2 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance2_, kOriginB);
int id_b2 = handle_b2->GetRenderProcessHostForTesting()->GetID();
// Since we are site-per-process, things should be grouped by origin.
EXPECT_EQ(id_a1, id_a2);
EXPECT_NE(id_a1, id_b1);
EXPECT_NE(id_a1, id_b2);
EXPECT_NE(id_a2, id_b1);
EXPECT_NE(id_a2, id_b2);
EXPECT_EQ(id_b1, id_b2);
histogram_tester.ExpectBucketCount(
"Ads.InterestGroup.Auction.Seller.RequestWorkletServiceOutcome",
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess, 2);
histogram_tester.ExpectBucketCount(
"Ads.InterestGroup.Auction.Seller.RequestWorkletServiceOutcome",
RequestWorkletServiceOutcome::kUsedExistingDedicatedProcess, 2);
// Stuff that's also isolated by explicit requests gets the same treatment.
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_i1 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kIsolatedOrigin);
int id_i1 = handle_i1->GetRenderProcessHostForTesting()->GetID();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_i2 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance2_, kIsolatedOrigin);
int id_i2 = handle_i2->GetRenderProcessHostForTesting()->GetID();
EXPECT_EQ(id_i1, id_i2);
EXPECT_NE(id_i1, id_a1);
EXPECT_NE(id_i1, id_a2);
EXPECT_NE(id_i1, id_b1);
EXPECT_NE(id_i1, id_b2);
histogram_tester.ExpectBucketCount(
"Ads.InterestGroup.Auction.Seller.RequestWorkletServiceOutcome",
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess, 3);
histogram_tester.ExpectBucketCount(
"Ads.InterestGroup.Auction.Seller.RequestWorkletServiceOutcome",
RequestWorkletServiceOutcome::kUsedExistingDedicatedProcess, 3);
}
TEST_P(
InRendererAuctionProcessManagerTest,
MaybeStartAnticipatoryProcess_UsesIdleProcessOnlyForMatchingOriginAndType) {
CheckOnlyIdleProcessesWithCount(0);
// We only start one process when we try to create one for the same
// origin/type twice.
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(1);
// We don't consume this process when we request a process for a different
// origin or type.
AuctionProcessManager::ProcessHandle handle1, handle2, handle3, handle4;
RequestWorkletService(
&handle1, kOriginB, GetParam(), /*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
RequestWorkletService(
&handle2, kOriginA, GetParamInverse(), /*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
RequestWorkletService(
&handle3, kOriginB, GetParamInverse(), /*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
EXPECT_EQ(GetActiveProcesses(GetParamInverse()), 2u);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
// We do consume the process when we request the same type and origin.
RequestWorkletService(&handle4, kOriginA, GetParam(), /*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
EXPECT_EQ(GetActiveProcessesOfParamType(), 2u);
}
TEST_P(InRendererAuctionProcessManagerTest,
MaybeStartAnticipatoryProcess_CorrectProcessGetsAssigned) {
std::vector<std::tuple<url::Origin, AuctionProcessManager::WorkletType>>
origins_and_types;
for (url::Origin origin : {kOriginA, kOriginB, kOriginC}) {
for (AuctionProcessManager::WorkletType type :
{GetParam(), GetParamInverse()}) {
origins_and_types.emplace_back(origin, type);
}
}
for (const auto& [origin_to_assign, type_to_assign] : origins_and_types) {
// Start the processes.
for (const auto& [origin_to_start, type_to_start] : origins_and_types) {
MaybeStartAnticipatoryProcess(origin_to_start, type_to_start);
}
CheckOnlyIdleProcessesWithCount(origins_and_types.size());
// Assign one of them.
{
AuctionProcessManager::ProcessHandle handle;
RequestWorkletService(&handle, origin_to_assign, type_to_assign,
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(),
origins_and_types.size() - 1);
EXPECT_EQ(GetActiveProcesses(type_to_assign), 1u);
}
// We should be able to start a new process again
// because it's gone out of scope.
EXPECT_EQ(GetActiveProcesses(type_to_assign), 0u);
MaybeStartAnticipatoryProcess(origin_to_assign, type_to_assign);
CheckOnlyIdleProcessesWithCount(origins_and_types.size());
// Trying to start the processes again should be redundant and
// should not increase our process count.
for (const auto& [origin_to_start, type_to_start] : origins_and_types) {
MaybeStartAnticipatoryProcess(origin_to_start, type_to_start);
}
CheckOnlyIdleProcessesWithCount(origins_and_types.size());
// Reset the number of processes for the next loop by letting the idle
// processes expire. The active process has already gone out of scope.
task_environment_.FastForwardBy(
features::kFledgeStartAnticipatoryProcessExpirationTime.Get());
CheckOnlyIdleProcessesWithCount(0);
}
}
TEST_P(InRendererAuctionProcessManagerTest,
MaybeStartAnticipatoryProcess_RespectsLimitWithIdleProcessesOnly) {
for (size_t i = 0; i < GetMaxProcesses(); ++i) {
url::Origin origin =
url::Origin::Create(GURL(base::StringPrintf("https://%i.test", i)));
MaybeStartAnticipatoryProcess(origin, GetParam());
CheckOnlyIdleProcessesWithCount(i + 1);
}
// Can't make another one.
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
CheckOnlyIdleProcessesWithCount(GetMaxProcesses());
// Can make an anticipatory process of the other type.
MaybeStartAnticipatoryProcess(kOriginA, GetParamInverse());
CheckOnlyIdleProcessesWithCount(GetMaxProcesses() + 1);
// Can start an active process of the other type.
AuctionProcessManager::ProcessHandle handle0, handle1, handle2;
RequestWorkletService(
&handle0, kOriginB, GetParamInverse(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(),
GetMaxProcesses() + 1);
EXPECT_EQ(GetActiveProcesses(GetParamInverse()), 1u);
// We can make a new process even if the origin doesn't match a
// previously created process of the same type. It will create a new process
// and evict one of our idle processes.
RequestWorkletService(
&handle1, kOriginA, GetParam(), /*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(),
GetMaxProcesses());
EXPECT_EQ(GetActiveProcessesOfParamType(), 1u);
// We can use one of the idle processes to make a new process if the origin
// and type match. We should still have a process on behalf of 1.test because
// the oldest one will get cleared (0.test).
RequestWorkletService(
&handle2,
url::Origin::Create(GURL(base::StringPrintf("https://%i.test", 1))),
GetParam(), /*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(),
GetMaxProcesses() - 1);
EXPECT_EQ(GetActiveProcessesOfParamType(), 2u);
// We should be able to make up to the limit # of processes (we've already
// created 2).
std::vector<std::unique_ptr<AuctionProcessManager::ProcessHandle>> handles;
for (size_t i = 0; i < GetMaxProcesses() - 2; ++i) {
url::Origin origin =
url::Origin::Create(GURL(base::StringPrintf("https://%i_2.test", i)));
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(
handles.back().get(), origin, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
}
// An idle process of the other type should still exist.
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 1u);
EXPECT_EQ(GetActiveProcessesOfParamType(), GetMaxProcesses());
// Now we will hit the process limit when we request a new process.
AuctionProcessManager::ProcessHandle hit_limit_handle;
RequestWorkletService(&hit_limit_handle, kOriginB, GetParam(),
/*expect_success=*/false,
RequestWorkletServiceOutcome::kHitProcessLimit);
// The idle process of the other type should not have been cleared.
// We should be able to use it.
AuctionProcessManager::ProcessHandle other_type_handle;
RequestWorkletService(&other_type_handle, kOriginA, GetParamInverse(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 0u);
EXPECT_EQ(GetActiveProcessesOfParamType(), GetMaxProcesses());
EXPECT_EQ(GetActiveProcesses(GetParamInverse()), 2u);
}
TEST_P(InRendererAuctionProcessManagerTest,
MaybeStartAnticipatoryProcess_RespectsLimitWithActiveAndIdleProcesses) {
// Alternate making idle and active processes.
std::vector<std::unique_ptr<AuctionProcessManager::ProcessHandle>> handles;
for (size_t i = 0; i < GetMaxProcesses(); ++i) {
url::Origin origin =
url::Origin::Create(GURL(base::StringPrintf("https://%i.test", i)));
if (i % 2 == 0) {
MaybeStartAnticipatoryProcess(origin, GetParam());
} else {
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(
handles.back().get(), origin, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
}
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(),
i + 1 - handles.size());
EXPECT_EQ(GetActiveProcessesOfParamType(), handles.size());
}
// Can't make another anticipatory process.
MaybeStartAnticipatoryProcess(kOriginA, GetParam());
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(),
GetMaxProcesses() - handles.size());
EXPECT_EQ(GetActiveProcessesOfParamType(), handles.size());
// We can evict one of the anticipatory processes to make a new active
// process.
handles.emplace_back(
std::make_unique<AuctionProcessManager::ProcessHandle>());
RequestWorkletService(
handles.back().get(), kOriginA, GetParam(), /*expect_success=*/true,
RequestWorkletServiceOutcome::kCreatedNewDedicatedProcess);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(),
GetMaxProcesses() - handles.size());
EXPECT_EQ(GetActiveProcessesOfParamType(), handles.size());
}
TEST_P(
InRendererAuctionProcessManagerTest,
MaybeStartAnticipatoryProcess_ProcessesCanBeAssignedInDifferentOrderFromHowTheyWereMade) {
std::vector<url::Origin> origins{kOriginA, kOriginB, kOriginC};
for (url::Origin origin : origins) {
MaybeStartAnticipatoryProcess(origin, GetParam());
}
CheckOnlyIdleProcessesWithCount(3);
std::vector<std::unique_ptr<AuctionProcessManager::ProcessHandle>> handles;
for (size_t i = 0; i < 3; i++) {
url::Origin origin = origins[2 - i];
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle =
std::make_unique<AuctionProcessManager::ProcessHandle>();
RequestWorkletService(handle.get(), origin, GetParam(),
/*expect_success=*/true,
RequestWorkletServiceOutcome::kUsedIdleProcess);
EXPECT_EQ(GetActiveProcessesOfParamType(), i + 1u);
EXPECT_EQ(auction_process_manager_.GetIdleProcessCountForTesting(), 2 - i);
handles.push_back(std::move(handle));
}
}
TEST_F(InRendererAuctionProcessManagerTest_NoOriginKeyedProcessesByDefault,
PolicyChange) {
// Launch site in default instance.
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a1 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kOriginA);
EXPECT_FALSE(
handle_a1->site_instance_for_testing()->RequiresDedicatedProcess());
RenderProcessHost* shared_process =
handle_a1->GetRenderProcessHostForTesting();
// Change policy so that A can no longer use shared instances.
SiteInstance::StartIsolatingSite(
&test_browser_context_, kOriginA.GetURL(),
ChildProcessSecurityPolicy::IsolatedOriginSource::TEST);
site_instance1_ = SiteInstance::Create(&test_browser_context_);
// Launch another A-origin worklet, this should get a different process.
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a2 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kOriginA);
EXPECT_TRUE(
handle_a2->site_instance_for_testing()->RequiresDedicatedProcess());
EXPECT_NE(handle_a2->GetRenderProcessHostForTesting(), shared_process);
// Destroy shared process and try to get another A one --- should reuse the
// same non-shared process.
handle_a1.reset();
std::unique_ptr<AuctionProcessManager::ProcessHandle> handle_a3 =
GetServiceOfTypeExpectSuccess(AuctionProcessManager::WorkletType::kSeller,
site_instance1_, kOriginA);
EXPECT_TRUE(
handle_a3->site_instance_for_testing()->RequiresDedicatedProcess());
EXPECT_EQ(handle_a2->GetRenderProcessHostForTesting(),
handle_a3->GetRenderProcessHostForTesting());
// Checking GetRenderProcessHostForTesting isn't enough since SiteInstance
// can share it, too.
EXPECT_EQ(handle_a2->worklet_process_for_testing(),
handle_a3->worklet_process_for_testing());
}
} // namespace
} // namespace content