1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/rappor/sample.h"
10 #include "base/logging.h"
11 #include "components/metrics/metrics_hashes.h"
12 #include "components/rappor/bloom_filter.h"
13 #include "components/rappor/byte_vector_utils.h"
14 #include "components/rappor/proto/rappor_metric.pb.h"
15 #include "components/rappor/reports.h"
19 Sample::Sample(int32_t cohort_seed
, const RapporParameters
& parameters
)
20 : parameters_(parameters
),
21 bloom_offset_((cohort_seed
% parameters_
.num_cohorts
) *
22 parameters_
.bloom_filter_hash_function_count
) {
23 // Must use bloom filter size that fits in uint64.
24 DCHECK_LE(parameters_
.bloom_filter_size_bytes
, 8);
30 void Sample::SetStringField(const std::string
& field_name
,
31 const std::string
& value
) {
32 DVLOG(2) << "Recording sample \"" << value
33 << "\" for sample metric field \"" << field_name
<< "\"";
34 DCHECK_EQ(0u, sizes_
[field_name
]);
35 fields_
[field_name
] = internal::GetBloomBits(
36 parameters_
.bloom_filter_size_bytes
,
37 parameters_
.bloom_filter_hash_function_count
,
40 sizes_
[field_name
] = parameters_
.bloom_filter_size_bytes
;
43 void Sample::SetFlagsField(const std::string
& field_name
,
46 DVLOG(2) << "Recording flags " << flags
47 << " for sample metric field \"" << field_name
<< "\"";
48 DCHECK_EQ(0u, sizes_
[field_name
]);
49 DCHECK_GT(num_flags
, 0u);
50 DCHECK_LE(num_flags
, 64u);
51 DCHECK(num_flags
== 64u || flags
>> num_flags
== 0);
52 fields_
[field_name
] = flags
;
53 sizes_
[field_name
] = (num_flags
+ 7) / 8;
56 void Sample::ExportMetrics(const std::string
& secret
,
57 const std::string
& metric_name
,
58 RapporReports
* reports
) const {
59 for (const auto& kv
: fields_
) {
60 uint64_t value
= kv
.second
;
61 const auto it
= sizes_
.find(kv
.first
);
62 DCHECK(it
!= sizes_
.end());
63 size_t size
= it
->second
;
64 ByteVector
value_bytes(size
);
65 Uint64ToByteVector(value
, size
, &value_bytes
);
66 ByteVector report_bytes
= internal::GenerateReport(
67 secret
, parameters_
, value_bytes
);
69 RapporReports::Report
* report
= reports
->add_report();
70 report
->set_name_hash(metrics::HashMetricName(
71 metric_name
+ "." + kv
.first
));
72 report
->set_bits(std::string(report_bytes
.begin(), report_bytes
.end()));
73 DVLOG(2) << "Exporting sample " << metric_name
<< "." << kv
.first
;