File: exclusive_operation_coordinator.cc

package info (click to toggle)
chromium 145.0.7632.159-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,976,224 kB
  • sloc: cpp: 36,198,469; ansic: 7,634,080; javascript: 3,564,060; python: 1,649,622; xml: 838,470; asm: 717,087; pascal: 185,708; sh: 88,786; perl: 88,718; objc: 79,984; sql: 59,811; cs: 42,452; fortran: 24,101; makefile: 21,144; tcl: 15,277; php: 14,022; yacc: 9,066; ruby: 7,553; awk: 3,720; lisp: 3,233; lex: 1,328; ada: 727; jsp: 228; sed: 36
file content (198 lines) | stat: -rw-r--r-- 7,693 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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/disk_cache/sql/exclusive_operation_coordinator.h"

#include <optional>
#include <utility>

#include "base/check.h"
#include "base/metrics/histogram_functions.h"
#include "base/timer/elapsed_timer.h"
#include "net/disk_cache/sql/cache_entry_key.h"

namespace disk_cache {

namespace {

// Wraps an operation to record its queuing time in a UMA histogram.
base::OnceCallback<
    void(std::unique_ptr<ExclusiveOperationCoordinator::OperationHandle>)>
WrapWithUmaQueuingTime(
    base::OnceCallback<
        void(std::unique_ptr<ExclusiveOperationCoordinator::OperationHandle>)>
        operation,
    const std::string_view histogram_name) {
  return base::BindOnce(
      [](base::OnceCallback<void(
             std::unique_ptr<ExclusiveOperationCoordinator::OperationHandle>)>
             operation,
         const std::string_view histogram_name, base::ElapsedTimer timer,
         std::unique_ptr<ExclusiveOperationCoordinator::OperationHandle>
             handle) {
        base::UmaHistogramMicrosecondsTimes(histogram_name, timer.Elapsed());
        std::move(operation).Run(std::move(handle));
      },
      std::move(operation), histogram_name, base::ElapsedTimer());
}

}  // namespace

ExclusiveOperationCoordinator::OperationHandle::OperationHandle(
    base::PassKey<ExclusiveOperationCoordinator>,
    base::WeakPtr<ExclusiveOperationCoordinator> coordinator,
    std::optional<CacheEntryKey> key)
    : coordinator_(std::move(coordinator)), key_(std::move(key)) {}

ExclusiveOperationCoordinator::OperationHandle::~OperationHandle() {
  if (coordinator_) {
    coordinator_->OnOperationFinished(key_);
  }
}

ExclusiveOperationCoordinator::ExclusiveOperationCoordinator() = default;
ExclusiveOperationCoordinator::~ExclusiveOperationCoordinator() = default;

void ExclusiveOperationCoordinator::PostOrRunExclusiveOperation(
    OperationCallback operation) {
  CHECK(operation);
  operation = WrapWithUmaQueuingTime(
      std::move(operation), "Net.SqlDiskCache.ExclusiveOperationDelay");
  queue_.emplace(std::move(operation));
  TryToRunNextOperation(std::nullopt);
}

void ExclusiveOperationCoordinator::PostOrRunNormalOperation(
    const CacheEntryKey& key,
    OperationCallback operation) {
  CHECK(operation);
  operation = WrapWithUmaQueuingTime(std::move(operation),
                                     "Net.SqlDiskCache.NormalOperationDelay");
  // If there is no queue, or the back of the queue is an exclusive operation,
  // add a new `NormalOperationsQueueMap` to the back of the queue.
  if (queue_.empty() ||
      std::holds_alternative<ExclusiveOperation>(queue_.back())) {
    queue_.push(NormalOperationsQueueMap());
  }
  // Add the callback to the queue for the given `key`.
  // Normal operations with the same key are serialized.
  std::get<NormalOperationsQueueMap>(queue_.back())[key].push(
      std::move(operation));
  TryToRunNextOperation(key);
}

void ExclusiveOperationCoordinator::OnOperationFinished(
    const std::optional<CacheEntryKey>& key) {
  CHECK(!queue_.empty());
  // Verify that the front of the queue is a `NormalOperationsQueueMap` iff a
  // `key` was provided.
  CHECK_EQ(std::holds_alternative<NormalOperationsQueueMap>(queue_.front()),
           key.has_value());

  if (key.has_value()) {
    // The operation that just finished was a normal operation.
    // Get a reference to the `NormalOperationsQueueMap` at the front of the
    // queue.
    NormalOperationsQueueMap& normal_operations_map =
        std::get<NormalOperationsQueueMap>(queue_.front());
    auto it = normal_operations_map.find(key.value());
    // The `NormalOperationsQueueMap` at the front of `queue_` must have a
    // `base::queue<OperationCallback>` corresponding to `key`,
    CHECK(it != normal_operations_map.end());
    // and that `base::queue<OperationCallback>` must not be empty,
    CHECK(!it->second.empty());
    // and the OperationCallback at the front must be a null callback.
    CHECK(it->second.front().is_null());
    // Remove the OperationCallback that just finished running.
    it->second.pop();
    if (it->second.empty()) {
      // There are no more operations for this key, so remove the key from the
      // map.
      normal_operations_map.erase(it);
      if (normal_operations_map.empty()) {
        // There are no more operations in the map, so remove the map from the
        // queue. This phase has completed.
        queue_.pop();
      }
    }
  } else {
    // The operation that just finished was an exclusive operation.
    // Get a reference to the `ExclusiveOperation` at the front of the queue.
    ExclusiveOperation& exclusive_operation =
        std::get<ExclusiveOperation>(queue_.front());
    // The ExclusiveOperation at the front of `queue_` must be a null callback.
    CHECK(exclusive_operation.is_null());
    // Remove the ExclusiveOperation from the queue. This phase has completed.
    queue_.pop();
  }

  // The completion of an operation might allow the next one to start.
  TryToRunNextOperation(key);
}

void ExclusiveOperationCoordinator::TryToRunNextOperation(
    const std::optional<CacheEntryKey>& key) {
  if (queue_.empty()) {
    // Nothing to do.
    return;
  }

  // A list of operations that can be run in this pass. We collect them first
  // and run them later to avoid iterator invalidation issues caused by
  // re-entrant calls if an operation completes synchronously.
  std::vector<base::OnceClosure> runnable_ops;

  if (std::holds_alternative<NormalOperationsQueueMap>(queue_.front())) {
    // The next phase in the queue is a batch of normal operations.
    // Get a reference to the `NormalOperationsQueueMap` at the front of the
    // queue.
    NormalOperationsQueueMap& normal_operations_map =
        std::get<NormalOperationsQueueMap>(queue_.front());
    // If a `key` was provided, attempt to run the next operation for that
    // `key`. Otherwise, attempt to run operations for all keys.
    if (key.has_value()) {
      if (auto it = normal_operations_map.find(key.value());
          it != normal_operations_map.end()) {
        CHECK(!it->second.empty());
        MaybeTakeAndResetPendingOperation(it->second.front(), key,
                                          runnable_ops);
      }
    } else {
      // Attempt to run one operation for each key in the map.
      for (auto& pair : normal_operations_map) {
        CHECK(!pair.second.empty());
        MaybeTakeAndResetPendingOperation(pair.second.front(), pair.first,
                                          runnable_ops);
      }
    }
  } else {
    // The next phase in the queue is an exclusive operation.
    MaybeTakeAndResetPendingOperation(
        std::get<ExclusiveOperation>(queue_.front()), std::nullopt,
        runnable_ops);
  }

  // Run the collected operations.
  for (auto& runnable_op : runnable_ops) {
    std::move(runnable_op).Run();
  }
}

void ExclusiveOperationCoordinator::MaybeTakeAndResetPendingOperation(
    ExclusiveOperationCoordinator::OperationCallback& operation,
    const std::optional<CacheEntryKey>& key,
    std::vector<base::OnceClosure>& runnable_ops) {
  if (!operation) {
    return;
  }
  runnable_ops.push_back(base::BindOnce(
      std::move(operation), std::make_unique<OperationHandle>(
                                base::PassKey<ExclusiveOperationCoordinator>(),
                                weak_factory_.GetWeakPtr(), key)));
  // Reset to a null callback to indicate that the operation is
  // currently running.
  operation.Reset();
}

}  // namespace disk_cache