File: context.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (272 lines) | stat: -rw-r--r-- 9,154 bytes parent folder | download | duplicates (5)
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
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/domain_reliability/context.h"

#include <algorithm>
#include <limits>
#include <utility>

#include "base/functional/bind.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/rand_util.h"
#include "base/values.h"
#include "components/domain_reliability/dispatcher.h"
#include "components/domain_reliability/uploader.h"
#include "components/domain_reliability/util.h"
#include "net/base/isolation_info.h"
#include "net/base/net_errors.h"
#include "net/base/network_isolation_key.h"

namespace domain_reliability {

// static
const int DomainReliabilityContext::kMaxUploadDepthToSchedule = 1;

// static
const size_t DomainReliabilityContext::kMaxQueuedBeacons = 150;

DomainReliabilityContext::DomainReliabilityContext(
    const MockableTime* time,
    const DomainReliabilityScheduler::Params& scheduler_params,
    const std::string& upload_reporter_string,
    const base::TimeTicks* last_network_change_time,
    const UploadAllowedCallback& upload_allowed_callback,
    DomainReliabilityDispatcher* dispatcher,
    DomainReliabilityUploader* uploader,
    std::unique_ptr<const DomainReliabilityConfig> config)
    : config_(std::move(config)),
      time_(time),
      upload_reporter_string_(upload_reporter_string),
      scheduler_(time,
                 config_->collectors.size(),
                 scheduler_params,
                 base::BindRepeating(&DomainReliabilityContext::ScheduleUpload,
                                     base::Unretained(this))),
      dispatcher_(dispatcher),
      uploader_(uploader),
      uploading_beacons_size_(0),
      last_network_change_time_(last_network_change_time),
      upload_allowed_callback_(upload_allowed_callback) {}

DomainReliabilityContext::~DomainReliabilityContext() {
  for (auto& beacon_ptr : beacons_) {
    beacon_ptr->outcome = DomainReliabilityBeacon::Outcome::kContextShutDown;
  }
}

void DomainReliabilityContext::OnBeacon(
    std::unique_ptr<DomainReliabilityBeacon> beacon) {
  bool success = (beacon->status == "ok");
  double sample_rate = beacon->details.quic_port_migration_detected
                           ? 1.0
                           : config().GetSampleRate(success);
  if (base::RandDouble() >= sample_rate)
    return;
  beacon->sample_rate = sample_rate;

  // Allow beacons about reports, but don't schedule an upload for more than
  // one layer of recursion, to avoid infinite report loops.
  if (beacon->upload_depth <= kMaxUploadDepthToSchedule)
    scheduler_.OnBeaconAdded();
  beacons_.push_back(std::move(beacon));
  bool should_evict = beacons_.size() > kMaxQueuedBeacons;
  if (should_evict)
    RemoveOldestBeacon();
}

void DomainReliabilityContext::ClearBeacons() {
  for (auto& beacon_ptr : beacons_) {
    beacon_ptr->outcome = DomainReliabilityBeacon::Outcome::kCleared;
  }
  beacons_.clear();
  uploading_beacons_size_ = 0;
}

void DomainReliabilityContext::GetQueuedBeaconsForTesting(
    std::vector<const DomainReliabilityBeacon*>* beacons_out) const {
  DCHECK(beacons_out);
  beacons_out->clear();
  for (const auto& beacon : beacons_)
    beacons_out->push_back(beacon.get());
}

void DomainReliabilityContext::ScheduleUpload(
    base::TimeDelta min_delay,
    base::TimeDelta max_delay) {
  dispatcher_->ScheduleTask(
      base::BindOnce(&DomainReliabilityContext::CallUploadAllowedCallback,
                     weak_factory_.GetWeakPtr()),
      min_delay, max_delay);
}

void DomainReliabilityContext::CallUploadAllowedCallback() {
  RemoveExpiredBeacons();
  if (beacons_.empty())
    return;

  upload_allowed_callback_->Run(
      config().origin,
      base::BindOnce(&DomainReliabilityContext::OnUploadAllowedCallbackComplete,
                     weak_factory_.GetWeakPtr()));
}

void DomainReliabilityContext::OnUploadAllowedCallbackComplete(bool allowed) {
  if (allowed)
    StartUpload();
}

void DomainReliabilityContext::StartUpload() {
  RemoveExpiredBeacons();
  if (beacons_.empty())
    return;

  // Find the first beacon with an `upload_depth` of at most
  // kMaxUploadDepthToSchedule, in preparation to create a report containing all
  // beacons with matching NetworkIsolationKeys.
  bool found_beacon_to_upload = false;
  for (const auto& beacon : beacons_) {
    if (beacon->upload_depth <= kMaxUploadDepthToSchedule) {
      uploading_beacons_isolation_info_ = beacon->isolation_info;
      found_beacon_to_upload = true;
      break;
    }
  }
  if (!found_beacon_to_upload)
    return;

  size_t collector_index = scheduler_.OnUploadStart();
  const GURL& collector_url = *config().collectors[collector_index];

  DCHECK(upload_time_.is_null());
  upload_time_ = time_->NowTicks();
  std::string report_json = "{}";
  int max_upload_depth = -1;
  bool wrote = base::JSONWriter::Write(
      CreateReport(upload_time_, collector_url, &max_upload_depth),
      &report_json);
  DCHECK(wrote);
  DCHECK_NE(-1, max_upload_depth);

  uploader_->UploadReport(
      report_json, max_upload_depth, collector_url,
      uploading_beacons_isolation_info_,
      base::BindOnce(&DomainReliabilityContext::OnUploadComplete,
                     weak_factory_.GetWeakPtr()));
}

void DomainReliabilityContext::OnUploadComplete(
    const DomainReliabilityUploader::UploadResult& result) {
  if (result.is_success()) {
    CommitUpload();
  } else {
    RollbackUpload();
  }
  scheduler_.OnUploadComplete(result);
  DCHECK(!upload_time_.is_null());
  last_upload_time_ = upload_time_;
  upload_time_ = base::TimeTicks();

  // If there are pending beacons with a low enough depth, inform the scheduler
  // - it's possible only some beacons were added because of NetworkIsolationKey
  // mismatches, rather than due to new beacons being created.
  if (GetMinBeaconUploadDepth() <= kMaxUploadDepthToSchedule)
    scheduler_.OnBeaconAdded();
}

base::Value DomainReliabilityContext::CreateReport(base::TimeTicks upload_time,
                                                   const GURL& collector_url,
                                                   int* max_upload_depth_out) {
  DCHECK_GT(beacons_.size(), 0u);
  DCHECK_EQ(0u, uploading_beacons_size_);

  int max_upload_depth = 0;

  base::Value::List beacons_value;
  for (const auto& beacon : beacons_) {
    // Only include beacons with a matching NetworkIsolationKey in the report.
    if (beacon->isolation_info.network_isolation_key() !=
        uploading_beacons_isolation_info_.network_isolation_key()) {
      continue;
    }

    beacons_value.Append(
        beacon->ToValue(upload_time, *last_network_change_time_, collector_url,
                        config().path_prefixes));
    if (beacon->upload_depth > max_upload_depth)
      max_upload_depth = beacon->upload_depth;
    ++uploading_beacons_size_;
  }

  DCHECK_GT(uploading_beacons_size_, 0u);

  base::Value::Dict report_value;
  report_value.Set("reporter", *upload_reporter_string_);
  report_value.Set("entries", std::move(beacons_value));

  *max_upload_depth_out = max_upload_depth;
  return base::Value(std::move(report_value));
}

void DomainReliabilityContext::CommitUpload() {
  auto current = beacons_.begin();
  while (uploading_beacons_size_ > 0) {
    CHECK(current != beacons_.end());

    auto last = current;
    ++current;
    if ((*last)->isolation_info.network_isolation_key() ==
        uploading_beacons_isolation_info_.network_isolation_key()) {
      (*last)->outcome = DomainReliabilityBeacon::Outcome::kUploaded;
      beacons_.erase(last);
      --uploading_beacons_size_;
    }
  }
}

void DomainReliabilityContext::RollbackUpload() {
  uploading_beacons_size_ = 0;
}

void DomainReliabilityContext::RemoveOldestBeacon() {
  DCHECK(!beacons_.empty());

  DVLOG(1) << "Beacon queue for " << config().origin << " full; "
           << "removing oldest beacon";

  // If the beacon being removed has a NetworkIsolationKey that matches that of
  // the current upload, decrement `uploading_beacons_size_`.
  if (uploading_beacons_size_ > 0 &&
      beacons_.front()->isolation_info.network_isolation_key() ==
          uploading_beacons_isolation_info_.network_isolation_key()) {
    --uploading_beacons_size_;
  }

  beacons_.front()->outcome = DomainReliabilityBeacon::Outcome::kEvicted;
  beacons_.pop_front();
}

void DomainReliabilityContext::RemoveExpiredBeacons() {
  base::TimeTicks now = time_->NowTicks();
  const base::TimeDelta kMaxAge = base::Hours(1);
  while (!beacons_.empty() && now - beacons_.front()->start_time >= kMaxAge) {
    beacons_.front()->outcome = DomainReliabilityBeacon::Outcome::kExpired;
    beacons_.pop_front();
  }
}

// Gets the minimum depth of all entries in |beacons_|.
int DomainReliabilityContext::GetMinBeaconUploadDepth() const {
  int min = std::numeric_limits<int>::max();
  for (const auto& beacon : beacons_) {
    if (beacon->upload_depth < min)
      min = beacon->upload_depth;
  }
  return min;
}

}  // namespace domain_reliability