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
content / browser / attribution_reporting / attribution_manager_impl.cc [blame]
// Copyright 2020 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/attribution_reporting/attribution_manager_impl.h"
#include <stddef.h>
#include <cmath>
#include <functional>
#include <optional>
#include <set>
#include <utility>
#include <vector>
#include "base/barrier_closure.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/functional/overloaded.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ref.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/observer_list.h"
#include "base/ranges/algorithm.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/task/updateable_sequenced_task_runner.h"
#include "base/threading/sequence_bound.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "components/attribution_reporting/aggregatable_filtering_id_max_bytes.h"
#include "components/attribution_reporting/constants.h"
#include "components/attribution_reporting/os_registration.h"
#include "components/attribution_reporting/registration.mojom.h"
#include "components/attribution_reporting/source_registration.h"
#include "components/attribution_reporting/suitable_origin.h"
#include "components/attribution_reporting/trigger_registration.h"
#include "content/browser/aggregation_service/aggregation_service.h"
#include "content/browser/aggregation_service/aggregation_service_impl.h"
#include "content/browser/aggregation_service/report_scheduler_timer.h"
#include "content/browser/attribution_reporting/aggregatable_attribution_utils.h"
#include "content/browser/attribution_reporting/aggregatable_debug_report.h"
#include "content/browser/attribution_reporting/attribution_data_host_manager.h"
#include "content/browser/attribution_reporting/attribution_data_host_manager_impl.h"
#include "content/browser/attribution_reporting/attribution_debug_report.h"
#include "content/browser/attribution_reporting/attribution_features.h"
#include "content/browser/attribution_reporting/attribution_info.h"
#include "content/browser/attribution_reporting/attribution_observer.h"
#include "content/browser/attribution_reporting/attribution_os_level_manager.h"
#include "content/browser/attribution_reporting/attribution_report.h"
#include "content/browser/attribution_reporting/attribution_report_network_sender.h"
#include "content/browser/attribution_reporting/attribution_report_sender.h"
#include "content/browser/attribution_reporting/attribution_reporting.mojom.h"
#include "content/browser/attribution_reporting/attribution_resolver.h"
#include "content/browser/attribution_reporting/attribution_resolver_delegate.h"
#include "content/browser/attribution_reporting/attribution_resolver_delegate_impl.h"
#include "content/browser/attribution_reporting/attribution_resolver_impl.h"
#include "content/browser/attribution_reporting/attribution_trigger.h"
#include "content/browser/attribution_reporting/create_report_result.h"
#include "content/browser/attribution_reporting/os_registration.h"
#include "content/browser/attribution_reporting/send_result.h"
#include "content/browser/attribution_reporting/storable_source.h"
#include "content/browser/attribution_reporting/store_source_result.h"
#include "content/browser/attribution_reporting/stored_source.h"
#include "content/browser/storage_partition_impl.h"
#include "content/public/browser/attribution_data_model.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browsing_data_filter_builder.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "net/base/schemeful_site.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/network_change_manager.mojom-forward.h"
#include "storage/browser/quota/special_storage_policy.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "url/gurl.h"
#include "url/origin.h"
#if BUILDFLAG(IS_ANDROID)
#include "content/browser/attribution_reporting/attribution_os_level_manager_android.h"
#endif
namespace content {
namespace {
using ScopedUseInMemoryStorageForTesting =
::content::AttributionManagerImpl::ScopedUseInMemoryStorageForTesting;
using ::attribution_reporting::OsRegistrationItem;
using ::attribution_reporting::mojom::OsRegistrationResult;
using ::attribution_reporting::mojom::RegistrationType;
constexpr size_t kMaxPendingEvents = 1000u;
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
//
// LINT.IfChange(ConversionReportSendOutcome)
enum class ConversionReportSendOutcome {
kSent = 0,
kFailed = 1,
kDropped = 2,
kFailedToAssemble = 3,
kMaxValue = kFailedToAssemble,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/attribution_reporting/enums.xml:ConversionReportSendOutcome)
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
//
// LINT.IfChange(ConversionReportSendRetryCount)
enum class ConversionReportSendRetryCount {
kNone = 0,
kOnce = 1,
kTwice = 2,
kFailed = 3,
kMaxValue = kFailed,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/attribution_reporting/enums.xml:ConversionReportSendRetryCount)
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
//
// LINT.IfChange(ConversionReportSendRetryCountThirdRetryEnabled)
enum class ConversionReportSendRetryCountThirdRetryEnabled {
kNone = 0,
kOnce = 1,
kTwice = 2,
kThrice = 3,
kFailed = 4,
kMaxValue = kFailed,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/attribution_reporting/enums.xml:ConversionReportSendRetryCountThirdRetryEnabled)
const base::TimeDelta kPrivacySandboxAttestationsTimeout = base::Minutes(5);
} // namespace
// This class consolidates logic regarding when to schedule the browser to send
// attribution reports. It talks directly to the `AttributionResolver` to help
// make these decisions.
//
// While the class does not make large changes to the underlying database, it
// is responsible for notifying the `AttributionResolver` when the browser comes
// back online, which mutates report times for some scheduled reports.
class AttributionManagerImpl::ReportScheduler
: public ReportSchedulerTimer::Delegate {
public:
explicit ReportScheduler(base::WeakPtr<AttributionManagerImpl> manager)
: manager_(manager) {}
~ReportScheduler() override = default;
ReportScheduler(const ReportScheduler&) = delete;
ReportScheduler& operator=(const ReportScheduler&) = delete;
ReportScheduler(ReportScheduler&&) = delete;
ReportScheduler& operator=(ReportScheduler&&) = delete;
private:
// ReportSchedulerTimer::Delegate:
void GetNextReportTime(
base::OnceCallback<void(std::optional<base::Time>)> callback,
base::Time now) override {
if (!manager_) {
std::move(callback).Run(std::nullopt);
return;
}
manager_->attribution_resolver_
.AsyncCall(&AttributionResolver::GetNextReportTime)
.WithArgs(now)
.Then(std::move(callback));
}
void OnReportingTimeReached(base::Time now,
base::Time timer_desired_run_time) override {
if (manager_) {
manager_->GetReportsToSend();
}
}
void AdjustOfflineReportTimes(
base::OnceCallback<void(std::optional<base::Time>)> maybe_set_timer_cb)
override {
if (!manager_) {
std::move(maybe_set_timer_cb).Run(std::nullopt);
return;
}
// Add delay to all reports that should have been sent while the browser was
// offline so they are not temporally joinable. We do this in storage to
// avoid pulling an unbounded number of reports into memory, only to
// immediately issue async storage calls to modify their report times.
manager_->attribution_resolver_
.AsyncCall(&AttributionResolver::AdjustOfflineReportTimes)
.Then(std::move(maybe_set_timer_cb));
}
base::WeakPtr<AttributionManagerImpl> manager_;
};
namespace {
bool IsStorageKeySessionOnly(
scoped_refptr<storage::SpecialStoragePolicy> storage_policy,
const blink::StorageKey& storage_key) {
// TODO(johnidel): This conversion is unfortunate but necessary. Storage
// partition clear data logic uses storage key keyed deletion, while the
// storage policy uses GURLs. Ideally these would be coalesced.
const GURL& url = storage_key.origin().GetURL();
if (storage_policy->IsStorageProtected(url)) {
return false;
}
if (storage_policy->IsStorageSessionOnly(url)) {
return true;
}
return false;
}
void RecordStoreSourceStatus(const StoreSourceResult& result) {
base::UmaHistogramEnumeration("Conversions.SourceStoredStatus8",
result.status());
}
void RecordCreateReportStatus(const CreateReportResult& result) {
base::UmaHistogramEnumeration("Conversions.CreateReportStatus9",
result.event_level_status());
base::UmaHistogramEnumeration(
"Conversions.AggregatableReport.CreateReportStatus4",
result.aggregatable_status());
}
void RecordReportRetriesEventLevel(int retry_attempts,
bool third_retry_enabled) {
if (third_retry_enabled) {
// `retry_attempts` <= 3, represents the number of retries before success.
// `retry_attempts` == 4, represents failure after three retries.
DCHECK_LE(retry_attempts, 4);
base::UmaHistogramEnumeration(
"Conversions.EventLevelReport.ReportRetriesTillSuccessOrFailure_"
"ThirdRetryEnabled",
static_cast<ConversionReportSendRetryCountThirdRetryEnabled>(
retry_attempts));
} else {
// `retry_attempts` <= 2, represents the number of retries before success.
// `retry_attempts` == 3, represents failure after two retries.
DCHECK_LE(retry_attempts, 3);
base::UmaHistogramEnumeration(
"Conversions.EventLevelReport.ReportRetriesTillSuccessOrFailure",
static_cast<ConversionReportSendRetryCount>(retry_attempts));
}
}
void RecordReportRetriesAggregatable(int retry_attempts,
bool third_retry_enabled) {
if (third_retry_enabled) {
// `retry_attempts` <= 3, represents the number of retries before success.
// `retry_attempts` == 4, represents failure after three retries.
DCHECK_LE(retry_attempts, 4);
base::UmaHistogramEnumeration(
"Conversions.AggregatableReport.ReportRetriesTillSuccessOrFailure_"
"ThirdRetryEnabled",
static_cast<ConversionReportSendRetryCountThirdRetryEnabled>(
retry_attempts));
} else {
// `retry_attempts` <= 2, represents the number of retries before success.
// `retry_attempts` == 3, represents failure after two retries.
DCHECK_LE(retry_attempts, 3);
base::UmaHistogramEnumeration(
"Conversions.AggregatableReport.ReportRetriesTillSuccessOrFailure",
static_cast<ConversionReportSendRetryCount>(retry_attempts));
}
}
ConversionReportSendOutcome ConvertToConversionReportSendOutcome(
SendResult::Status status) {
switch (status) {
case SendResult::Status::kSent:
return ConversionReportSendOutcome::kSent;
case SendResult::Status::kTransientFailure:
case SendResult::Status::kFailure:
return ConversionReportSendOutcome::kFailed;
case SendResult::Status::kDropped:
return ConversionReportSendOutcome::kDropped;
case SendResult::Status::kAssemblyFailure:
case SendResult::Status::kTransientAssemblyFailure:
return ConversionReportSendOutcome::kFailedToAssemble;
}
}
void RecordNetworkConnectionTypeOnFailure(
AttributionReport::Type report_type,
network::mojom::ConnectionType connection_type) {
switch (report_type) {
case AttributionReport::Type::kEventLevel:
base::UmaHistogramEnumeration(
"Conversions.EventLevelReport.NetworkConnectionTypeOnFailure",
connection_type);
break;
case AttributionReport::Type::kAggregatableAttribution:
base::UmaHistogramEnumeration(
"Conversions.AggregatableReport.NetworkConnectionTypeOnFailure",
connection_type);
break;
case AttributionReport::Type::kNullAggregatable:
break;
}
}
void RecordAssembleAggregatableReportStatus(
AssembleAggregatableReportStatus status) {
base::UmaHistogramEnumeration(
"Conversions.AggregatableReport.AssembleReportStatus", status);
}
void LogAggregatableReportHistogramCustomTimes(const char* suffix,
bool has_trigger_context_id,
base::TimeDelta sample,
base::TimeDelta min,
base::TimeDelta max,
size_t buckets) {
base::UmaHistogramCustomTimes(
base::StrCat({"Conversions.AggregatableReport.", suffix}), sample, min,
max, buckets);
if (has_trigger_context_id) {
base::UmaHistogramCustomTimes(
base::StrCat({"Conversions.AggregatableReport.ContextID.", suffix}),
sample, min, max, buckets);
} else {
base::UmaHistogramCustomTimes(
base::StrCat({"Conversions.AggregatableReport.NoContextID.", suffix}),
sample, min, max, buckets);
}
}
// Called when |report| is to be sent over network for event-level reports or
// to be assembled for aggregatable reports, for logging metrics.
void LogMetricsOnReportSend(const AttributionReport& report, base::Time now) {
absl::visit(
base::Overloaded{
[&](const AttributionReport::EventLevelData&) {
// Use a large time range to capture users that might not open the
// browser for a long time while a conversion report is pending.
// Revisit this range if it is non-ideal for real world data.
const AttributionInfo& attribution_info = report.attribution_info();
base::TimeDelta time_since_original_report_time =
now - report.initial_report_time();
base::UmaHistogramCustomTimes("Conversions.ExtraReportDelay2",
time_since_original_report_time,
base::Seconds(1), base::Days(24),
/*buckets=*/100);
base::TimeDelta time_from_conversion_to_report_send =
report.report_time() - attribution_info.time;
UMA_HISTOGRAM_COUNTS_1000(
"Conversions.TimeFromConversionToReportSend",
time_from_conversion_to_report_send.InHours());
UMA_HISTOGRAM_CUSTOM_TIMES("Conversions.SchedulerReportDelay",
now - report.report_time(),
base::Seconds(1), base::Days(1), 50);
},
[&](const AttributionReport::AggregatableAttributionData& data) {
base::TimeDelta time_from_conversion_to_report_assembly =
report.report_time() - report.attribution_info().time;
UMA_HISTOGRAM_CUSTOM_TIMES(
"Conversions.AggregatableReport."
"TimeFromTriggerToReportAssembly2",
time_from_conversion_to_report_assembly, base::Minutes(1),
base::Days(24), 50);
LogAggregatableReportHistogramCustomTimes(
"ExtraReportDelay",
data.common_data.aggregatable_trigger_config
.trigger_context_id()
.has_value(),
now - report.initial_report_time(), base::Seconds(1),
base::Days(24), 50);
UMA_HISTOGRAM_CUSTOM_TIMES(
"Conversions.AggregatableReport.SchedulerReportDelay",
now - report.report_time(), base::Seconds(1), base::Days(1),
50);
},
[](const AttributionReport::NullAggregatableData&) {},
},
report.data());
}
// Called when |report| is sent, failed or dropped, for logging metrics.
void LogMetricsOnReportCompleted(const AttributionReport& report,
SendResult::Status status) {
switch (report.GetReportType()) {
case AttributionReport::Type::kEventLevel:
base::UmaHistogramEnumeration(
"Conversions.ReportSendOutcome3",
ConvertToConversionReportSendOutcome(status));
break;
case AttributionReport::Type::kAggregatableAttribution:
base::UmaHistogramEnumeration(
"Conversions.AggregatableReport.ReportSendOutcome2",
ConvertToConversionReportSendOutcome(status));
break;
case AttributionReport::Type::kNullAggregatable:
break;
}
}
// Called when `report` is sent successfully.
void LogMetricsOnReportSent(const AttributionReport& report,
bool third_retry_enabled) {
base::Time now = base::Time::Now();
base::TimeDelta time_from_conversion_to_report_sent =
now - report.attribution_info().time;
base::TimeDelta time_since_original_report_time =
now - report.initial_report_time();
switch (report.GetReportType()) {
case AttributionReport::Type::kEventLevel:
UMA_HISTOGRAM_CUSTOM_TIMES(
"Conversions.ExtraReportDelayForSuccessfulSend",
time_since_original_report_time, base::Seconds(1), base::Days(24),
/*bucket_count=*/100);
UMA_HISTOGRAM_COUNTS_1000(
"Conversions.TimeFromTriggerToReportSentSuccessfully",
time_from_conversion_to_report_sent.InHours());
RecordReportRetriesEventLevel(report.failed_send_attempts(),
third_retry_enabled);
break;
case AttributionReport::Type::kAggregatableAttribution:
UMA_HISTOGRAM_CUSTOM_TIMES(
"Conversions.AggregatableReport."
"TimeFromTriggerToReportSentSuccessfully",
time_from_conversion_to_report_sent, base::Minutes(1), base::Days(24),
50);
UMA_HISTOGRAM_CUSTOM_TIMES(
"Conversions.AggregatableReport.ExtraReportDelayForSuccessfulSend",
time_since_original_report_time, base::Seconds(1), base::Days(24),
/*bucket_count=*/50);
RecordReportRetriesAggregatable(report.failed_send_attempts(),
third_retry_enabled);
break;
case AttributionReport::Type::kNullAggregatable:
break;
}
}
bool HasNonDefaultFilteringId(const AttributionTrigger& trigger) {
return base::ranges::any_of(
trigger.registration().aggregatable_values, [](const auto& value) {
return base::ranges::any_of(value.values(), [](const auto& val) {
return val.second.filtering_id() !=
attribution_reporting::kDefaultFilteringId;
});
});
}
void RecordAggregatableFilteringIdUsage(const AttributionTrigger& trigger) {
base::UmaHistogramBoolean("Conversions.NonDefaultAggregatableFilteringId",
HasNonDefaultFilteringId(trigger));
base::UmaHistogramExactLinear(
"Conversions.AggregatableFilteringIdMaxBytesValue",
trigger.registration()
.aggregatable_trigger_config.aggregatable_filtering_id_max_bytes()
.value(),
/*exclusive_max=8+1=*/9);
}
std::unique_ptr<AttributionResolverDelegate> MakeResolverDelegate(
bool debug_mode) {
if (debug_mode) {
return std::make_unique<AttributionResolverDelegateImpl>(
AttributionNoiseMode::kNone, AttributionDelayMode::kNone);
}
return std::make_unique<AttributionResolverDelegateImpl>(
AttributionNoiseMode::kDefault, AttributionDelayMode::kDefault);
}
bool IsOperationAllowed(
StoragePartitionImpl& storage_partition,
ContentBrowserClient::AttributionReportingOperation operation,
content::RenderFrameHost* rfh,
const url::Origin* source_origin,
const url::Origin* destination_origin,
const url::Origin* reporting_origin,
bool* can_bypass = nullptr) {
return GetContentClient()->browser()->IsAttributionReportingOperationAllowed(
storage_partition.browser_context(), operation, rfh, source_origin,
destination_origin, reporting_origin, can_bypass);
}
std::unique_ptr<AttributionOsLevelManager> CreateOsLevelManager() {
#if BUILDFLAG(IS_ANDROID)
if (base::FeatureList::IsEnabled(
network::features::kAttributionReportingCrossAppWeb)) {
return std::make_unique<AttributionOsLevelManagerAndroid>();
}
#endif
return std::make_unique<NoOpAttributionOsLevelManager>();
}
// Returns new report time if any.
std::optional<base::Time> HandleTransientFailureOnSendReport(
const AttributionReport& report,
bool third_retry_enabled) {
int retry_attempts = report.failed_send_attempts() + 1;
if (std::optional<base::TimeDelta> delay =
GetFailedReportDelay(retry_attempts, third_retry_enabled)) {
return base::Time::Now() + *delay;
} else {
switch (report.GetReportType()) {
case AttributionReport::Type::kEventLevel:
RecordReportRetriesEventLevel(retry_attempts, third_retry_enabled);
break;
case AttributionReport::Type::kAggregatableAttribution:
RecordReportRetriesAggregatable(retry_attempts, third_retry_enabled);
break;
case AttributionReport::Type::kNullAggregatable:
break;
}
return std::nullopt;
}
}
bool g_run_in_memory = false;
} // namespace
struct AttributionManagerImpl::SourceOrTriggerRFH {
absl::variant<StorableSource, AttributionTrigger> source_or_trigger;
GlobalRenderFrameHostId rfh_id;
};
std::optional<base::TimeDelta> GetFailedReportDelay(int failed_send_attempts,
bool third_retry_enabled) {
DCHECK_GT(failed_send_attempts, 0);
switch (failed_send_attempts) {
case 1:
return base::Minutes(5);
case 2:
return base::Minutes(15);
case 3:
return third_retry_enabled ? std::make_optional(base::Days(1))
: std::nullopt;
default:
return std::nullopt;
}
}
ScopedUseInMemoryStorageForTesting::ScopedUseInMemoryStorageForTesting()
: previous_(g_run_in_memory) {
g_run_in_memory = true;
}
ScopedUseInMemoryStorageForTesting::~ScopedUseInMemoryStorageForTesting() {
g_run_in_memory = previous_;
}
bool AttributionManagerImpl::IsReportAllowed(
const AttributionReport& report) const {
return IsOperationAllowed(
*storage_partition_,
ContentBrowserClient::AttributionReportingOperation::kReport,
/*rfh=*/nullptr, &*report.GetSourceOrigin(),
&*report.attribution_info().context_origin, &*report.reporting_origin());
}
// static
std::unique_ptr<AttributionManagerImpl>
AttributionManagerImpl::CreateForTesting(
const base::FilePath& user_data_directory,
size_t max_pending_events,
scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy,
std::unique_ptr<AttributionResolverDelegate> resolver_delegate,
std::unique_ptr<AttributionReportSender> report_sender,
std::unique_ptr<AttributionOsLevelManager> os_level_manager,
StoragePartitionImpl* storage_partition,
scoped_refptr<base::UpdateableSequencedTaskRunner> resolver_task_runner) {
return base::WrapUnique(new AttributionManagerImpl(
storage_partition, user_data_directory, max_pending_events,
std::move(special_storage_policy), std::move(resolver_delegate),
std::move(report_sender), std::move(os_level_manager),
std::move(resolver_task_runner),
/*debug_mode=*/false));
}
AttributionManagerImpl::AttributionManagerImpl(
StoragePartitionImpl* storage_partition,
const base::FilePath& user_data_directory,
scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy)
: AttributionManagerImpl(
storage_partition,
user_data_directory,
// TODO(crbug.com/40267739): consider reducing this number when
// os registrations will include multiple items.
kMaxPendingEvents,
std::move(special_storage_policy),
/*resolver_delegate=*/nullptr,
std::make_unique<AttributionReportNetworkSender>(
storage_partition->GetURLLoaderFactoryForBrowserProcess()),
CreateOsLevelManager(),
// This uses BLOCK_SHUTDOWN as some data deletion operations may be
// running when the browser is closed, and we want to ensure all data
// is deleted correctly. Additionally, we use MUST_USE_FOREGROUND to
// avoid priority inversions if a task is already running when the
// priority is increased.
base::ThreadPool::CreateUpdateableSequencedTaskRunner(
base::TaskTraits(base::TaskPriority::BEST_EFFORT,
base::MayBlock(),
base::TaskShutdownBehavior::BLOCK_SHUTDOWN,
base::ThreadPolicy::MUST_USE_FOREGROUND)),
/*debug_mode=*/
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAttributionReportingDebugMode)) {}
AttributionManagerImpl::AttributionManagerImpl(
StoragePartitionImpl* storage_partition,
const base::FilePath& user_data_directory,
size_t max_pending_events,
scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy,
std::unique_ptr<AttributionResolverDelegate> resolver_delegate,
std::unique_ptr<AttributionReportSender> report_sender,
std::unique_ptr<AttributionOsLevelManager> os_level_manager,
scoped_refptr<base::UpdateableSequencedTaskRunner> resolver_task_runner,
bool debug_mode)
: storage_partition_(
raw_ref<StoragePartitionImpl>::from_ptr(storage_partition)),
max_pending_events_(max_pending_events),
resolver_task_runner_(std::move(resolver_task_runner)),
attribution_resolver_(base::SequenceBound<AttributionResolverImpl>(
resolver_task_runner_,
g_run_in_memory ? base::FilePath() : user_data_directory,
resolver_delegate ? std::move(resolver_delegate)
: MakeResolverDelegate(debug_mode))),
data_host_manager_(
std::make_unique<AttributionDataHostManagerImpl>(this)),
special_storage_policy_(std::move(special_storage_policy)),
report_sender_(std::move(report_sender)),
os_level_manager_(std::move(os_level_manager)),
debug_mode_(debug_mode),
third_retry_enabled_(base::FeatureList::IsEnabled(
kAttributionReportDeliveryThirdRetryAttempt)) {
DCHECK_GT(max_pending_events_, 0u);
DCHECK(resolver_task_runner_);
DCHECK(report_sender_);
DCHECK(os_level_manager_);
if (GetContentClient()->browser()->AddPrivacySandboxAttestationsObserver(
this)) {
OnAttestationsLoaded();
} else {
privacy_sandbox_attestations_timer_.Start(
FROM_HERE, kPrivacySandboxAttestationsTimeout,
base::BindOnce(&AttributionManagerImpl::OnAttestationsLoaded,
weak_factory_.GetWeakPtr()));
}
}
AttributionManagerImpl::~AttributionManagerImpl() {
GetContentClient()->browser()->RemovePrivacySandboxAttestationsObserver(this);
// Browser contexts are not required to have a special storage policy.
if (!special_storage_policy_ ||
!special_storage_policy_->HasSessionOnlyOrigins()) {
return;
}
// Delete stored data for all session only origins given by
// |special_storage_policy|.
StoragePartition::StorageKeyMatcherFunction
session_only_storage_key_predicate = base::BindRepeating(
&IsStorageKeySessionOnly, std::move(special_storage_policy_));
ClearData(base::Time::Min(), base::Time::Max(),
std::move(session_only_storage_key_predicate),
/*filter_builder=*/nullptr,
/*delete_rate_limit_data=*/true, /*done=*/base::DoNothing());
}
void AttributionManagerImpl::AddObserver(AttributionObserver* observer) {
observers_.AddObserver(observer);
observer->OnDebugModeChanged(debug_mode_);
}
void AttributionManagerImpl::RemoveObserver(AttributionObserver* observer) {
observers_.RemoveObserver(observer);
}
AttributionDataHostManager* AttributionManagerImpl::GetDataHostManager() {
DCHECK(data_host_manager_);
return data_host_manager_.get();
}
void AttributionManagerImpl::HandleSource(
StorableSource source,
GlobalRenderFrameHostId render_frame_id) {
MaybeEnqueueEvent(std::move(source), render_frame_id);
}
void AttributionManagerImpl::OnSourceStored(
std::optional<uint64_t> cleared_debug_key,
StoreSourceResult result) {
CHECK(IsReady());
RecordStoreSourceStatus(result);
base::Time now = base::Time::Now();
for (auto& observer : observers_) {
observer.OnSourceHandled(result.source(), now, cleared_debug_key,
result.status());
}
if (const auto* success =
absl::get_if<StoreSourceResult::Success>(&result.result())) {
scheduler_timer_->MaybeSet(success->min_fake_report_time);
if (success->min_fake_report_time.has_value()) {
NotifyReportsChanged();
}
}
NotifySourcesChanged();
MaybeSendVerboseDebugReport(result);
MaybeSendAggregatableDebugReport(result);
}
void AttributionManagerImpl::HandleTrigger(
AttributionTrigger trigger,
GlobalRenderFrameHostId render_frame_id) {
RecordAggregatableFilteringIdUsage(trigger);
MaybeEnqueueEvent(std::move(trigger), render_frame_id);
}
void AttributionManagerImpl::StoreTrigger(AttributionTrigger trigger,
bool cookie_based_debug_allowed) {
std::optional<uint64_t> cleared_debug_key;
if (!cookie_based_debug_allowed) {
cleared_debug_key =
std::exchange(trigger.registration().debug_key, std::nullopt);
}
attribution_resolver_
.AsyncCall(&AttributionResolver::MaybeCreateAndStoreReport)
.WithArgs(std::move(trigger))
.Then(base::BindOnce(&AttributionManagerImpl::OnReportStored,
weak_factory_.GetWeakPtr(), cleared_debug_key,
cookie_based_debug_allowed));
}
template <typename T>
void AttributionManagerImpl::MaybeEnqueueEvent(
T&& event,
GlobalRenderFrameHostId render_frame_id) {
if (IsReady()) {
DCHECK(pending_events_.empty());
ProcessEvent(std::move(event), render_frame_id);
return;
}
const size_t size_before_push = pending_events_.size();
// Avoid unbounded memory growth with adversarial input.
bool allowed = size_before_push < max_pending_events_;
base::UmaHistogramBoolean("Conversions.EnqueueEventAllowed", allowed);
if (!allowed) {
return;
}
pending_events_.emplace_back(std::move(event), render_frame_id);
}
namespace {
enum class BrowserPolicy {
kProhibited,
kAllowedWithDebug,
kAllowedWithoutDebug,
};
BrowserPolicy GetBrowserPolicy(
StoragePartitionImpl& storage_partition,
ContentBrowserClient::AttributionReportingOperation registration_operation,
ContentBrowserClient::AttributionReportingOperation debug_operation,
GlobalRenderFrameHostId rfh_id,
const url::Origin* source_origin,
const url::Origin* destination_origin,
const url::Origin& reporting_origin,
bool check_debug) {
if (!IsOperationAllowed(storage_partition, registration_operation,
RenderFrameHost::FromID(rfh_id), source_origin,
destination_origin, &reporting_origin)) {
return BrowserPolicy::kProhibited;
}
if (check_debug) {
// TODO(crbug.com/40941634): Clean up `can_bypass` after the cookie
// deprecation experiment.
bool can_bypass = false;
if (IsOperationAllowed(storage_partition, debug_operation,
/*rfh=*/nullptr, source_origin, destination_origin,
&reporting_origin, &can_bypass) ||
can_bypass) {
return BrowserPolicy::kAllowedWithDebug;
}
}
return BrowserPolicy::kAllowedWithoutDebug;
}
} // namespace
void AttributionManagerImpl::ProcessEvent(StorableSource source,
GlobalRenderFrameHostId rfh_id) {
BrowserPolicy browser_policy = GetBrowserPolicy(
*storage_partition_,
ContentBrowserClient::AttributionReportingOperation::kSource,
ContentBrowserClient::AttributionReportingOperation::
kSourceTransitionalDebugReporting,
rfh_id, &*source.common_info().source_origin(),
/*destination_origin=*/nullptr, source.common_info().reporting_origin(),
/*check_debug=*/true);
switch (browser_policy) {
case BrowserPolicy::kProhibited:
OnSourceStored(
/*cleared_debug_key=*/std::nullopt,
StoreSourceResult(std::move(source),
/*is_noised=*/false,
/*source_time=*/base::Time::Now(),
/*destination_limit=*/std::nullopt,
StoreSourceResult::ProhibitedByBrowserPolicy()));
break;
case BrowserPolicy::kAllowedWithDebug:
source.set_cookie_based_debug_allowed(/*value=*/true);
StoreSource(std::move(source));
break;
case BrowserPolicy::kAllowedWithoutDebug:
source.set_cookie_based_debug_allowed(/*value=*/false);
StoreSource(std::move(source));
break;
}
}
void AttributionManagerImpl::ProcessEvent(AttributionTrigger trigger,
GlobalRenderFrameHostId rfh_id) {
const attribution_reporting::TriggerRegistration& registration =
trigger.registration();
BrowserPolicy browser_policy = GetBrowserPolicy(
*storage_partition_,
ContentBrowserClient::AttributionReportingOperation::kTrigger,
ContentBrowserClient::AttributionReportingOperation::
kTriggerTransitionalDebugReporting,
rfh_id,
/*source_origin=*/nullptr, &*trigger.destination_origin(),
trigger.reporting_origin(),
/*check_debug=*/registration.debug_key.has_value() ||
registration.debug_reporting);
switch (browser_policy) {
case BrowserPolicy::kProhibited:
OnReportStored(
/*cleared_debug_key=*/std::nullopt,
/*cookie_based_debug_allowed=*/false,
CreateReportResult(
/*trigger_time=*/base::Time::Now(), std::move(trigger),
/*event_level_result=*/
CreateReportResult::ProhibitedByBrowserPolicy(),
/*aggregatable_result=*/
CreateReportResult::ProhibitedByBrowserPolicy(),
/*source=*/std::nullopt,
/*min_null_aggregatable_report_time=*/std::nullopt));
break;
case BrowserPolicy::kAllowedWithDebug:
StoreTrigger(std::move(trigger), /*cookie_based_debug_allowed=*/true);
break;
case BrowserPolicy::kAllowedWithoutDebug:
StoreTrigger(std::move(trigger), /*cookie_based_debug_allowed=*/false);
break;
}
}
void AttributionManagerImpl::StoreSource(StorableSource source) {
std::optional<uint64_t> cleared_debug_key;
if (!source.common_info().cookie_based_debug_allowed()) {
cleared_debug_key =
std::exchange(source.registration().debug_key, std::nullopt);
}
attribution_resolver_.AsyncCall(&AttributionResolver::StoreSource)
.WithArgs(std::move(source))
.Then(base::BindOnce(&AttributionManagerImpl::OnSourceStored,
weak_factory_.GetWeakPtr(), cleared_debug_key));
}
void AttributionManagerImpl::OnReportStored(
std::optional<uint64_t> cleared_debug_key,
bool cookie_based_debug_allowed,
CreateReportResult result) {
CHECK(IsReady());
RecordCreateReportStatus(result);
std::optional<base::Time> min_new_report_time;
if (auto* report = result.new_event_level_report()) {
min_new_report_time = report->report_time();
MaybeSendDebugReport(std::move(*report));
}
if (auto* report = result.new_aggregatable_report()) {
min_new_report_time = AttributionReport::MinReportTime(
min_new_report_time, report->report_time());
MaybeSendDebugReport(std::move(*report));
}
min_new_report_time = AttributionReport::MinReportTime(
min_new_report_time, result.min_null_aggregatable_report_time());
scheduler_timer_->MaybeSet(min_new_report_time);
bool notify_reports_changed = false;
if (result.event_level_status() !=
AttributionTrigger::EventLevelResult::kInternalError ||
result.aggregatable_status() ==
AttributionTrigger::AggregatableResult::kSuccess) {
// Sources are changed here because storing an event-level report or
// aggregatable report can cause sources to reach event-level attribution
// limit or become associated with a dedup key.
NotifySourcesChanged();
notify_reports_changed = true;
}
if (notify_reports_changed ||
result.min_null_aggregatable_report_time().has_value()) {
NotifyReportsChanged();
}
for (auto& observer : observers_) {
observer.OnTriggerHandled(cleared_debug_key, result);
}
MaybeSendVerboseDebugReport(cookie_based_debug_allowed, result);
MaybeSendAggregatableDebugReport(result);
}
void AttributionManagerImpl::MaybeSendDebugReport(AttributionReport&& report) {
if (!report.CanDebuggingBeEnabled() || !IsReportAllowed(report)) {
return;
}
// We don't delete from storage for debug reports.
PrepareToSendReport(std::move(report), /*is_debug_report=*/true,
base::BindOnce(&AttributionManagerImpl::NotifyReportSent,
weak_factory_.GetWeakPtr(),
/*is_debug_report=*/true));
}
void AttributionManagerImpl::GetActiveSourcesForWebUI(
base::OnceCallback<void(std::vector<StoredSource>)> callback) {
OnUserVisibleTaskStarted();
const int kMaxSources = 1000;
attribution_resolver_.AsyncCall(&AttributionResolver::GetActiveSources)
.WithArgs(kMaxSources)
.Then(std::move(callback).Then(
base::BindOnce(&AttributionManagerImpl::OnUserVisibleTaskComplete,
weak_factory_.GetWeakPtr())));
}
void AttributionManagerImpl::GetPendingReportsForInternalUse(
int limit,
base::OnceCallback<void(std::vector<AttributionReport>)> callback) {
OnUserVisibleTaskStarted();
attribution_resolver_.AsyncCall(&AttributionResolver::GetAttributionReports)
.WithArgs(/*max_report_time=*/base::Time::Max(), limit)
.Then(std::move(callback).Then(
base::BindOnce(&AttributionManagerImpl::OnUserVisibleTaskComplete,
weak_factory_.GetWeakPtr())));
}
void AttributionManagerImpl::SendReportForWebUI(AttributionReport::Id id,
base::OnceClosure done) {
DCHECK(done);
// TODO(linnan): Consider returning an error to the web UI.
if (!IsReady()) {
std::move(done).Run();
return;
}
OnUserVisibleTaskStarted();
done = std::move(done).Then(
base::BindOnce(&AttributionManagerImpl::OnUserVisibleTaskComplete,
weak_factory_.GetWeakPtr()));
attribution_resolver_.AsyncCall(&AttributionResolver::GetReport)
.WithArgs(id)
.Then(base::BindOnce(&AttributionManagerImpl::OnGetReportToSendFromWebUI,
weak_factory_.GetWeakPtr(), std::move(done)));
}
void AttributionManagerImpl::ClearData(
base::Time delete_begin,
base::Time delete_end,
StoragePartition::StorageKeyMatcherFunction filter,
BrowsingDataFilterBuilder* filter_builder,
bool delete_rate_limit_data,
base::OnceClosure done) {
auto barrier = base::BarrierClosure(2, std::move(done));
done = barrier;
if (filter_builder) {
os_level_manager_->ClearData(
delete_begin, delete_end, filter_builder->GetOrigins(),
filter_builder->GetRegisterableDomains(), filter_builder->GetMode(),
delete_rate_limit_data, std::move(barrier));
} else {
// When there is not filter_builder, we clear all the data.
os_level_manager_->ClearData(delete_begin, delete_end, /*origins=*/{},
/*domains=*/{},
// By preserving data only from an empty list,
// we are effectively clearing all the data.
BrowsingDataFilterBuilder::Mode::kPreserve,
delete_rate_limit_data, std::move(barrier));
}
// Rate-limit data is only deleted when initiated by a user, not a site via
// the Clear-Site-Data header.
if (delete_rate_limit_data) {
OnUserVisibleTaskStarted();
}
attribution_resolver_.AsyncCall(&AttributionResolver::ClearData)
.WithArgs(delete_begin, delete_end, std::move(filter),
delete_rate_limit_data)
.Then(std::move(done).Then(
base::BindOnce(&AttributionManagerImpl::OnClearDataComplete,
weak_factory_.GetWeakPtr(),
/*was_user_visible=*/delete_rate_limit_data)));
}
void AttributionManagerImpl::OnUserVisibleTaskStarted() {
// When a user-visible task is queued or running, we use a higher priority.
++num_pending_user_visible_tasks_;
resolver_task_runner_->UpdatePriority(base::TaskPriority::USER_VISIBLE);
}
void AttributionManagerImpl::OnUserVisibleTaskComplete() {
DCHECK_GT(num_pending_user_visible_tasks_, 0);
--num_pending_user_visible_tasks_;
// No more user-visible tasks, so we can reset the priority.
if (num_pending_user_visible_tasks_ == 0) {
resolver_task_runner_->UpdatePriority(base::TaskPriority::BEST_EFFORT);
}
}
void AttributionManagerImpl::OnClearDataComplete(bool was_user_visible) {
if (was_user_visible) {
OnUserVisibleTaskComplete();
}
NotifySourcesChanged();
NotifyReportsChanged();
}
void AttributionManagerImpl::GetAllDataKeys(
base::OnceCallback<void(std::set<DataKey>)> callback) {
OnUserVisibleTaskStarted();
attribution_resolver_.AsyncCall(&AttributionResolver::GetAllDataKeys)
.Then(std::move(callback).Then(
base::BindOnce(&AttributionManagerImpl::OnUserVisibleTaskComplete,
weak_factory_.GetWeakPtr())));
}
void AttributionManagerImpl::RemoveAttributionDataByDataKey(
const DataKey& data_key,
base::OnceClosure callback) {
auto barrier = base::BarrierClosure(2, std::move(callback));
callback = barrier;
os_level_manager_->ClearData(
/*delete_begin=*/base::Time::Min(), /*delete_end=*/base::Time::Max(),
/*origins=*/{data_key.reporting_origin()},
/*domains=*/{}, BrowsingDataFilterBuilder::Mode::kDelete,
/*delete_rate_limit_data=*/true, std::move(barrier));
OnUserVisibleTaskStarted();
attribution_resolver_.AsyncCall(&AttributionResolver::DeleteByDataKey)
.WithArgs(data_key)
.Then(std::move(callback).Then(base::BindOnce(
&AttributionManagerImpl::OnClearDataComplete,
weak_factory_.GetWeakPtr(), /*was_user_visible=*/true)));
}
void AttributionManagerImpl::GetReportsToSend() {
// We only get the next report time strictly after now, because if we are
// sending a report now but haven't finished doing so and it is still present
// in storage, storage will return the report time for the same report.
// Deduplication via `reports_being_sent_` will ensure that the report isn't
// sent twice, but it will result in wasted processing.
//
// TODO(apaseltiner): Consider limiting the number of reports being sent at
// once, to avoid pulling an arbitrary number of reports into memory.
attribution_resolver_.AsyncCall(&AttributionResolver::GetAttributionReports)
.WithArgs(/*max_report_time=*/base::Time::Now(), /*limit=*/-1)
.Then(base::BindOnce(&AttributionManagerImpl::SendReports,
weak_factory_.GetWeakPtr()));
}
void AttributionManagerImpl::OnGetReportToSendFromWebUI(
base::OnceClosure done,
std::optional<AttributionReport> report) {
DCHECK(done);
if (!report.has_value()) {
std::move(done).Run();
return;
}
const base::Time now = base::Time::Now();
report->set_report_time(now);
SendReport(std::move(done), now, *std::move(report));
}
void AttributionManagerImpl::SendReports(
std::vector<AttributionReport> reports) {
const base::Time now = base::Time::Now();
for (auto& report : reports) {
SendReport(base::NullCallback(), now, std::move(report));
}
}
// If `web_ui_callback` is null, assumes that `report` is being sent at its
// intended time, and logs metrics for it. Otherwise, does not log metrics.
void AttributionManagerImpl::SendReport(base::OnceClosure web_ui_callback,
const base::Time now,
AttributionReport report) {
DCHECK_LE(report.report_time(), now);
bool inserted = reports_being_sent_.emplace(report.id()).second;
if (!inserted) {
if (web_ui_callback) {
std::move(web_ui_callback).Run();
}
return;
}
if (!IsReportAllowed(report)) {
// If measurement is disallowed, just drop the report on the floor. We
// need to make sure we forward that the report was "sent" to ensure it is
// deleted from storage, etc. This simulates sending the report through a
// null channel.
OnReportSent(std::move(web_ui_callback), std::move(report),
SendResult(SendResult::Dropped()));
return;
}
if (!web_ui_callback) {
LogMetricsOnReportSend(report, now);
}
PrepareToSendReport(
std::move(report), /*is_debug_report=*/false,
base::BindOnce(&AttributionManagerImpl::OnReportSent,
weak_factory_.GetWeakPtr(), std::move(web_ui_callback)));
}
void AttributionManagerImpl::MarkReportCompleted(
AttributionReport::Id report_id) {
size_t num_removed = reports_being_sent_.erase(report_id);
DCHECK_EQ(num_removed, 1u);
}
void AttributionManagerImpl::PrepareToSendReport(AttributionReport report,
bool is_debug_report,
ReportSentCallback callback) {
switch (report.GetReportType()) {
case AttributionReport::Type::kEventLevel:
SendReport(std::move(report), is_debug_report, std::move(callback));
break;
case AttributionReport::Type::kAggregatableAttribution:
case AttributionReport::Type::kNullAggregatable:
AssembleAggregatableReport(std::move(report), is_debug_report,
std::move(callback));
break;
}
}
void AttributionManagerImpl::SendReport(AttributionReport report,
bool is_debug_report,
ReportSentCallback callback) {
report_sender_->SendReport(
std::move(report), is_debug_report,
base::BindOnce(
[](ReportSentCallback callback, const AttributionReport& report,
SendResult::Sent sent) {
std::move(callback).Run(report, SendResult(std::move(sent)));
},
std::move(callback)));
}
void AttributionManagerImpl::OnReportSent(base::OnceClosure done,
const AttributionReport& report,
SendResult info) {
CHECK(IsReady());
// If there was a transient failure, and another attempt is allowed,
// update the report's DB state to reflect that. Otherwise, delete the report
// from storage.
std::optional<base::Time> new_report_time =
absl::visit(base::Overloaded{
[&](SendResult::Sent sent) -> std::optional<base::Time> {
switch (sent.result) {
case SendResult::Sent::Result::kSent:
LogMetricsOnReportSent(report,
third_retry_enabled_);
return std::nullopt;
case SendResult::Sent::Result::kTransientFailure:
RecordNetworkConnectionTypeOnFailure(
report.GetReportType(),
scheduler_timer_->connection_type());
return HandleTransientFailureOnSendReport(
report, third_retry_enabled_);
case SendResult::Sent::Result::kFailure:
RecordNetworkConnectionTypeOnFailure(
report.GetReportType(),
scheduler_timer_->connection_type());
return std::nullopt;
}
},
[](SendResult::Dropped) -> std::optional<base::Time> {
return std::nullopt;
},
[&](SendResult::AssemblyFailure failure)
-> std::optional<base::Time> {
// TODO(linnan): Retry on transient assembly failure
// isn't privacy sensitive, therefore we could consider
// subjecting these failures to a different limit.
return failure.transient
? HandleTransientFailureOnSendReport(
report, third_retry_enabled_)
: std::nullopt;
},
},
info.result);
base::OnceCallback then = base::BindOnce(
[](base::OnceClosure done, base::WeakPtr<AttributionManagerImpl> manager,
AttributionReport::Id report_id,
std::optional<base::Time> new_report_time, bool success) {
if (done) {
std::move(done).Run();
}
if (manager && success) {
manager->MarkReportCompleted(report_id);
manager->scheduler_timer_->MaybeSet(new_report_time);
manager->NotifyReportsChanged();
}
},
std::move(done), weak_factory_.GetWeakPtr(), report.id(),
new_report_time);
if (new_report_time) {
attribution_resolver_
.AsyncCall(&AttributionResolver::UpdateReportForSendFailure)
.WithArgs(report.id(), *new_report_time)
.Then(std::move(then));
// TODO(apaseltiner): Consider surfacing retry attempts in internals UI.
return;
}
NotifyReportSent(/*is_debug_report=*/false, report, info);
attribution_resolver_.AsyncCall(&AttributionResolver::DeleteReport)
.WithArgs(report.id())
.Then(std::move(then));
LogMetricsOnReportCompleted(report, info.status());
}
void AttributionManagerImpl::NotifyReportSent(bool is_debug_report,
const AttributionReport& report,
SendResult info) {
for (auto& observer : observers_) {
observer.OnReportSent(report, /*is_debug_report=*/is_debug_report, info);
}
}
void AttributionManagerImpl::NotifyDebugReportSent(
const AttributionDebugReport& report,
const int status) {
// Use the same time for all observers.
const base::Time time = base::Time::Now();
for (auto& observer : observers_) {
observer.OnDebugReportSent(report, status, time);
}
}
void AttributionManagerImpl::AssembleAggregatableReport(
AttributionReport report,
bool is_debug_report,
ReportSentCallback callback) {
AggregationService* aggregation_service =
storage_partition_->GetAggregationService();
if (!aggregation_service) {
RecordAssembleAggregatableReportStatus(
AssembleAggregatableReportStatus::kAggregationServiceUnavailable);
std::move(callback).Run(
std::move(report),
SendResult(SendResult::AssemblyFailure(/*transient=*/false)));
return;
}
std::optional<AggregatableReportRequest> request =
CreateAggregatableReportRequest(report);
if (!request.has_value()) {
RecordAssembleAggregatableReportStatus(
AssembleAggregatableReportStatus::kCreateRequestFailed);
std::move(callback).Run(
std::move(report),
SendResult(SendResult::AssemblyFailure(/*transient=*/false)));
return;
}
aggregation_service->AssembleReport(
*std::move(request),
base::BindOnce(&AttributionManagerImpl::OnAggregatableReportAssembled,
weak_factory_.GetWeakPtr(), std::move(report),
is_debug_report, std::move(callback)));
}
void AttributionManagerImpl::OnAggregatableReportAssembled(
AttributionReport report,
bool is_debug_report,
ReportSentCallback callback,
AggregatableReportRequest,
std::optional<AggregatableReport> assembled_report,
AggregationService::AssemblyStatus) {
if (!assembled_report.has_value()) {
RecordAssembleAggregatableReportStatus(
AssembleAggregatableReportStatus::kAssembleReportFailed);
std::move(callback).Run(
std::move(report),
SendResult(SendResult::AssemblyFailure(/*transient=*/true)));
return;
}
absl::visit(
base::Overloaded{
[](const AttributionReport::EventLevelData&) { NOTREACHED(); },
[&](AttributionReport::AggregatableAttributionData& data) {
data.common_data.assembled_report = std::move(assembled_report);
},
[&](AttributionReport::NullAggregatableData& data) {
data.common_data.assembled_report = std::move(assembled_report);
},
},
report.data());
RecordAssembleAggregatableReportStatus(
AssembleAggregatableReportStatus::kSuccess);
SendReport(std::move(report), is_debug_report, std::move(callback));
}
void AttributionManagerImpl::NotifySourcesChanged() {
for (auto& observer : observers_) {
observer.OnSourcesChanged();
}
}
void AttributionManagerImpl::NotifyReportsChanged() {
for (auto& observer : observers_) {
observer.OnReportsChanged();
}
}
void AttributionManagerImpl::MaybeSendAggregatableDebugReport(
const StoreSourceResult& result) {
const auto is_operation_allowed = [&]() {
return IsOperationAllowed(
*storage_partition_,
ContentBrowserClient::AttributionReportingOperation::
kSourceAggregatableDebugReport,
/*rfh=*/nullptr, &*result.source().common_info().source_origin(),
/*destination_origin=*/nullptr,
&*result.source().common_info().reporting_origin());
};
if (std::optional<AggregatableDebugReport> debug_report =
AggregatableDebugReport::Create(is_operation_allowed, result)) {
std::optional<StoredSource::Id> source_id;
if (const auto* success =
absl::get_if<StoreSourceResult::Success>(&result.result())) {
source_id.emplace(success->source_id);
}
attribution_resolver_
.AsyncCall(&AttributionResolver::ProcessAggregatableDebugReport)
.WithArgs(*std::move(debug_report),
result.source()
.registration()
.aggregatable_debug_reporting_config.budget(),
source_id)
.Then(base::BindOnce(
&AttributionManagerImpl::OnAggregatableDebugReportProcessed,
weak_factory_.GetWeakPtr()));
}
}
void AttributionManagerImpl::MaybeSendAggregatableDebugReport(
const CreateReportResult& result) {
const auto is_operation_allowed = [&]() {
return IsOperationAllowed(
*storage_partition_,
ContentBrowserClient::AttributionReportingOperation::
kTriggerAggregatableDebugReport,
/*rfh=*/nullptr,
/*source_origin=*/nullptr, &*result.trigger().destination_origin(),
&*result.trigger().reporting_origin());
};
if (std::optional<AggregatableDebugReport> debug_report =
AggregatableDebugReport::Create(is_operation_allowed, result)) {
std::optional<StoredSource::Id> source_id;
if (const std::optional<StoredSource>& source = result.source();
source.has_value()) {
source_id.emplace(source->source_id());
}
attribution_resolver_
.AsyncCall(&AttributionResolver::ProcessAggregatableDebugReport)
.WithArgs(*std::move(debug_report),
/*remaining_budget=*/std::nullopt, source_id)
.Then(base::BindOnce(
&AttributionManagerImpl::OnAggregatableDebugReportProcessed,
weak_factory_.GetWeakPtr()));
}
}
void AttributionManagerImpl::OnAggregatableDebugReportProcessed(
ProcessAggregatableDebugReportResult result) {
AggregationService* aggregation_service =
storage_partition_->GetAggregationService();
if (!aggregation_service) {
NotifyAggregatableDebugReportSent(
result.report, /*report_body=*/base::Value::Dict(), result.result,
SendAggregatableDebugReportResult(
SendAggregatableDebugReportResult::AssemblyFailed()));
return;
}
std::optional<AggregatableReportRequest> request =
result.report.CreateAggregatableReportRequest();
if (!request.has_value()) {
NotifyAggregatableDebugReportSent(
result.report, /*report_body=*/base::Value::Dict(), result.result,
SendAggregatableDebugReportResult(
SendAggregatableDebugReportResult::AssemblyFailed()));
return;
}
aggregation_service->AssembleReport(
*std::move(request),
base::BindOnce(
&AttributionManagerImpl::OnAggregatableDebugReportAssembled,
weak_factory_.GetWeakPtr(), std::move(result)));
}
void AttributionManagerImpl::OnAggregatableDebugReportAssembled(
ProcessAggregatableDebugReportResult result,
AggregatableReportRequest,
std::optional<AggregatableReport> assembled_report,
AggregationService::AssemblyStatus) {
if (!assembled_report.has_value()) {
NotifyAggregatableDebugReportSent(
result.report, /*report_body=*/base::Value::Dict(), result.result,
SendAggregatableDebugReportResult(
SendAggregatableDebugReportResult::AssemblyFailed()));
return;
}
report_sender_->SendReport(
std::move(result.report), assembled_report->GetAsJson(),
base::BindOnce(
[](base::WeakPtr<AttributionManagerImpl> manager,
attribution_reporting::mojom::ProcessAggregatableDebugReportResult
process_result,
const AggregatableDebugReport& report, base::ValueView report_body,
int status) {
if (!manager) {
return;
}
manager->NotifyAggregatableDebugReportSent(
report, report_body, process_result,
SendAggregatableDebugReportResult(
SendAggregatableDebugReportResult::Sent(status)));
},
weak_factory_.GetWeakPtr(), result.result));
}
void AttributionManagerImpl::NotifyAggregatableDebugReportSent(
const AggregatableDebugReport& report,
base::ValueView report_body,
attribution_reporting::mojom::ProcessAggregatableDebugReportResult
process_result,
SendAggregatableDebugReportResult send_result) {
for (auto& observer : observers_) {
observer.OnAggregatableDebugReportSent(report, report_body, process_result,
send_result);
}
}
void AttributionManagerImpl::MaybeSendVerboseDebugReport(
const StoreSourceResult& result) {
const auto is_operation_allowed = [&]() {
return IsOperationAllowed(
*storage_partition_,
ContentBrowserClient::AttributionReportingOperation::
kSourceVerboseDebugReport,
/*rfh=*/nullptr, &*result.source().common_info().source_origin(),
/*destination_origin=*/nullptr,
&*result.source().common_info().reporting_origin());
};
if (std::optional<AttributionDebugReport> debug_report =
AttributionDebugReport::Create(is_operation_allowed, result)) {
report_sender_->SendReport(
*std::move(debug_report),
base::BindOnce(&AttributionManagerImpl::NotifyDebugReportSent,
weak_factory_.GetWeakPtr()));
}
}
void AttributionManagerImpl::MaybeSendVerboseDebugReport(
bool cookie_based_debug_allowed,
const CreateReportResult& result) {
const auto is_operation_allowed = [&]() {
return IsOperationAllowed(
*storage_partition_,
ContentBrowserClient::AttributionReportingOperation::
kTriggerVerboseDebugReport,
/*rfh=*/nullptr,
/*source_origin=*/nullptr, &*result.trigger().destination_origin(),
&*result.trigger().reporting_origin());
};
if (std::optional<AttributionDebugReport> debug_report =
AttributionDebugReport::Create(is_operation_allowed,
cookie_based_debug_allowed, result)) {
report_sender_->SendReport(
*std::move(debug_report),
base::BindOnce(&AttributionManagerImpl::NotifyDebugReportSent,
weak_factory_.GetWeakPtr()));
}
}
void AttributionManagerImpl::HandleOsRegistration(OsRegistration registration) {
if (IsReady()) {
DCHECK(pending_os_events_.empty());
ProcessOsEvent(std::move(registration));
return;
}
const size_t size_before_push = pending_os_events_.size();
// Avoid unbounded memory growth with adversarial input.
bool allowed = size_before_push < max_pending_events_;
base::UmaHistogramBoolean("Conversions.EnqueueOsEventAllowed", allowed);
if (!allowed) {
NotifyTotalOsRegistrationFailure(registration,
OsRegistrationResult::kExcessiveQueueSize);
return;
}
pending_os_events_.push_back(std::move(registration));
}
void AttributionManagerImpl::ProcessOsEvent(OsRegistration event) {
ContentBrowserClient::AttributionReportingOperation registration_operation;
ContentBrowserClient::AttributionReportingOperation debug_operation;
const url::Origin* source_origin;
const url::Origin* destination_origin;
switch (event.GetType()) {
case RegistrationType::kSource:
registration_operation =
ContentBrowserClient::AttributionReportingOperation::kOsSource;
debug_operation = ContentBrowserClient::AttributionReportingOperation::
kOsSourceTransitionalDebugReporting;
source_origin = &event.top_level_origin;
destination_origin = nullptr;
break;
case RegistrationType::kTrigger:
registration_operation =
ContentBrowserClient::AttributionReportingOperation::kOsTrigger;
debug_operation = ContentBrowserClient::AttributionReportingOperation::
kOsTriggerTransitionalDebugReporting;
source_origin = nullptr;
destination_origin = &event.top_level_origin;
break;
}
std::vector<bool> debug_allowed;
std::erase_if(event.registration_items, [&, now = base::Time::Now()](
const OsRegistrationItem& item) {
const auto registration_origin = url::Origin::Create(item.url);
if (registration_origin.opaque()) {
NotifyOsRegistration(now, item, event.top_level_origin,
/*is_debug_key_allowed=*/false, event.GetType(),
OsRegistrationResult::kInvalidRegistrationUrl);
return true;
}
BrowserPolicy browser_policy =
GetBrowserPolicy(*storage_partition_, registration_operation,
debug_operation, event.render_frame_id, source_origin,
destination_origin, registration_origin,
/*check_debug=*/true);
switch (browser_policy) {
case BrowserPolicy::kProhibited:
NotifyOsRegistration(now, item, event.top_level_origin,
/*is_debug_key_allowed=*/false, event.GetType(),
OsRegistrationResult::kProhibitedByBrowserPolicy);
return true;
case BrowserPolicy::kAllowedWithDebug:
debug_allowed.push_back(true);
return false;
case BrowserPolicy::kAllowedWithoutDebug:
debug_allowed.push_back(false);
return false;
}
NOTREACHED_NORETURN();
});
if (event.registration_items.empty()) {
return;
}
os_level_manager_->Register(
std::move(event), debug_allowed,
base::BindOnce(&AttributionManagerImpl::OnOsRegistration,
weak_factory_.GetWeakPtr(), debug_allowed));
}
void AttributionManagerImpl::NotifyTotalOsRegistrationFailure(
const OsRegistration& registration,
OsRegistrationResult result) {
const base::Time now = base::Time::Now();
for (const OsRegistrationItem& item : registration.registration_items) {
NotifyOsRegistration(now, item, registration.top_level_origin,
/*is_debug_key_allowed=*/false, registration.GetType(),
result);
}
}
void AttributionManagerImpl::NotifyOsRegistration(
base::Time time,
const OsRegistrationItem& registration,
const url::Origin& top_level_origin,
bool is_debug_key_allowed,
attribution_reporting::mojom::RegistrationType type,
attribution_reporting::mojom::OsRegistrationResult result) {
for (auto& observer : observers_) {
observer.OnOsRegistration(time, registration, top_level_origin, type,
is_debug_key_allowed, result);
}
switch (type) {
case attribution_reporting::mojom::RegistrationType::kSource:
base::UmaHistogramEnumeration("Conversions.OsRegistrationResult.Source",
result);
break;
case attribution_reporting::mojom::RegistrationType::kTrigger:
base::UmaHistogramEnumeration("Conversions.OsRegistrationResult.Trigger",
result);
break;
}
}
void AttributionManagerImpl::OnOsRegistration(
const std::vector<bool>& is_debug_key_allowed,
const OsRegistration& registration,
const std::vector<bool>& success) {
const size_t num_items = registration.registration_items.size();
CHECK_EQ(num_items, is_debug_key_allowed.size());
CHECK_EQ(num_items, success.size());
MaybeSendVerboseDebugReports(registration);
const base::Time now = base::Time::Now();
for (size_t i = 0; i < num_items; ++i) {
auto result = success[i] ? OsRegistrationResult::kPassedToOs
: OsRegistrationResult::kRejectedByOs;
NotifyOsRegistration(now, registration.registration_items[i],
registration.top_level_origin, is_debug_key_allowed[i],
registration.GetType(), result);
}
}
void AttributionManagerImpl::SetDebugMode(std::optional<bool> enabled,
base::OnceClosure done) {
bool debug_mode =
enabled.value_or(base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAttributionReportingDebugMode));
attribution_resolver_.AsyncCall(&AttributionResolver::SetDelegate)
.WithArgs(MakeResolverDelegate(debug_mode))
.Then(std::move(done).Then(base::BindOnce(
[](base::WeakPtr<AttributionManagerImpl> manager,
const bool debug_mode) {
if (manager) {
manager->debug_mode_ = debug_mode;
for (auto& observer : manager->observers_) {
observer.OnDebugModeChanged(debug_mode);
}
}
},
weak_factory_.GetWeakPtr(), debug_mode)));
}
void AttributionManagerImpl::MaybeSendVerboseDebugReports(
const OsRegistration& registration) {
ContentBrowserClient::AttributionReportingOperation operation;
const url::Origin* source_origin;
const url::Origin* destination_origin;
switch (registration.GetType()) {
case RegistrationType::kSource:
operation = ContentBrowserClient::AttributionReportingOperation::
kOsSourceVerboseDebugReport;
source_origin = ®istration.top_level_origin;
destination_origin = nullptr;
break;
case RegistrationType::kTrigger:
operation = ContentBrowserClient::AttributionReportingOperation::
kOsTriggerVerboseDebugReport;
source_origin = nullptr;
destination_origin = ®istration.top_level_origin;
break;
}
const auto is_operation_allowed =
[&](const url::Origin& registration_origin) {
return IsOperationAllowed(*storage_partition_, operation,
/*rfh=*/nullptr, source_origin,
destination_origin,
/*reporting_origin=*/®istration_origin);
};
for (size_t i = 0; i < registration.registration_items.size(); ++i) {
if (std::optional<AttributionDebugReport> debug_report =
AttributionDebugReport::Create(registration, /*item_index=*/i,
is_operation_allowed)) {
report_sender_->SendReport(
*std::move(debug_report),
base::BindOnce(&AttributionManagerImpl::NotifyDebugReportSent,
weak_factory_.GetWeakPtr()));
}
}
}
void AttributionManagerImpl::OnAttestationsLoaded() {
if (IsReady()) {
return;
}
base::UmaHistogramCustomTimes("Conversions.DelayOnAttestationsLoaded",
time_since_construction_.Elapsed(),
base::Milliseconds(1), base::Minutes(5),
/*buckets=*/50);
static_assert(kMaxPendingEvents == 1000u);
if (!pending_events_.empty()) {
base::UmaHistogramCounts1000(
"Conversions.NumEventsQueuedOnAttestationsLoaded",
pending_events_.size());
}
if (!pending_os_events_.empty()) {
base::UmaHistogramCounts1000(
"Conversions.NumOsEventsQueuedOnAttestationsLoaded",
pending_os_events_.size());
}
scheduler_timer_ = std::make_unique<ReportSchedulerTimer>(
std::make_unique<ReportScheduler>(weak_factory_.GetWeakPtr()));
for (SourceOrTriggerRFH& event : pending_events_) {
absl::visit([this, rfh_id = event.rfh_id](
auto& event) { ProcessEvent(std::move(event), rfh_id); },
event.source_or_trigger);
}
pending_events_.clear();
for (OsRegistration& event : pending_os_events_) {
ProcessOsEvent(std::move(event));
}
pending_os_events_.clear();
}
bool AttributionManagerImpl::IsReady() const {
return !!scheduler_timer_;
}
void AttributionManagerImpl::ReportRegistrationHeaderError(
attribution_reporting::SuitableOrigin reporting_origin,
const attribution_reporting::RegistrationHeaderError& error,
const attribution_reporting::SuitableOrigin& context_origin,
bool is_within_fenced_frame,
GlobalRenderFrameHostId render_frame_id) {
const auto is_operation_allowed = [&](const url::Origin& reporting_origin) {
return GetContentClient()
->browser()
->IsAttributionReportingAllowedForContext(
storage_partition_->browser_context(),
RenderFrameHost::FromID(render_frame_id), *context_origin,
reporting_origin);
};
if (std::optional<AttributionDebugReport> debug_report =
AttributionDebugReport::Create(std::move(reporting_origin), error,
context_origin, is_within_fenced_frame,
is_operation_allowed)) {
report_sender_->SendReport(
*std::move(debug_report),
base::BindOnce(&AttributionManagerImpl::NotifyDebugReportSent,
weak_factory_.GetWeakPtr()));
}
}
} // namespace content