File: invalidation_listener_impl.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 (291 lines) | stat: -rw-r--r-- 10,500 bytes parent folder | download | duplicates (3)
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
// Copyright 2024 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/invalidation/invalidation_listener_impl.h"

#include <stdint.h>

#include "base/containers/map_util.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "components/gcm_driver/gcm_driver.h"
#include "components/gcm_driver/instance_id/instance_id.h"
#include "components/gcm_driver/instance_id/instance_id_driver.h"
#include "components/invalidation/invalidation_listener.h"
#include "components/invalidation/public/invalidation.h"
#include "components/invalidation/public/invalidation_util.h"

namespace invalidation {

namespace {
const char kTypeKey[] = "type";
const char kPayloadKey[] = "payload";
const char kIssueTimestampMsKey[] = "issue_timestamp_ms";

constexpr char RegistrationMetricName[] =
    "FCMInvalidations.DirectInvalidation.RegistrationTokenRetrievalStatus";

// After the first failure, retry after 1 minute, then after 2, 4 etc up to a
// maximum of 1 day.
static constexpr net::BackoffEntry::Policy kRegistrationRetryBackoffPolicy = {
    .num_errors_to_ignore = 0,
    .initial_delay_ms = base::Minutes(1).InMilliseconds(),
    .multiply_factor = 2,
    .jitter_factor = 0.1,
    .maximum_backoff_ms = base::Days(1).InMilliseconds(),
    .always_use_initial_delay = true,
};

std::string GetValueFromMessage(const gcm::IncomingMessage& message,
                                const std::string& key) {
  const gcm::MessageData::const_iterator it = message.data.find(key);
  if (it != message.data.end()) {
    return it->second;
  }
  return std::string();
}

DirectInvalidation ParseIncomingMessage(const gcm::IncomingMessage& message) {
  const std::string type = GetValueFromMessage(message, kTypeKey);
  const std::string issue_timestamp_ms_str =
      GetValueFromMessage(message, kIssueTimestampMsKey);
  int64_t issue_timestamp_ms = 0;
  if (!base::StringToInt64(issue_timestamp_ms_str, &issue_timestamp_ms)) {
    issue_timestamp_ms = 0;
  }

  // The legacy invalidation version is the timestamp in microseconds.
  // TODO(b/341376574): Replace the version` with issue timestamp once we
  // fully migrate to direct message invalidations.
  const int64_t version =
      base::Milliseconds(issue_timestamp_ms).InMicroseconds();

  const std::string payload = GetValueFromMessage(message, kPayloadKey);
  return DirectInvalidation(type, version, payload);
}

// Insert or update the invalidation in the map at `invalidation.type()`.
// If `map` does not have an invalidation for that type, a copy of
// `invalidation` will be inserted.
// Otherwise, the existing invalidation for the type will be replaced by
// `invalidation` if and only if `invalidation` has a higher version than
// `map.at(invalidation.type())`.
void Upsert(std::map<Topic, DirectInvalidation>& map,
            const DirectInvalidation& invalidation) {
  const auto it = map.find(invalidation.type());
  if (it == map.end()) {
    map.emplace(invalidation.type(), invalidation);
    return;
  }
  if (it->second.version() < invalidation.version()) {
    it->second = invalidation;
    return;
  }
}

}  // namespace

InvalidationListenerImpl::InvalidationListenerImpl(
    gcm::GCMDriver* gcm_driver,
    instance_id::InstanceIDDriver* instance_id_driver,
    int64_t project_number,
    std::string log_prefix)
    : gcm_driver_(gcm_driver),
      instance_id_driver_(instance_id_driver),
      project_number_(project_number),
      gcm_app_id_(
          base::StrCat({kFmAppId, "-", base::NumberToString(project_number_)})),
      log_prefix_(base::StrCat(
          {log_prefix, "-", base::NumberToString(project_number_)})),
      registration_retry_backoff_(&kRegistrationRetryBackoffPolicy) {}

InvalidationListenerImpl::~InvalidationListenerImpl() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

// InvalidationListener overrides.
void InvalidationListenerImpl::AddObserver(Observer* observer) {
  const std::string type = observer->GetType();
  CHECK(!type_to_handler_.contains(type));
  CHECK(!observers_.HasObserver(observer));

  observers_.AddObserver(observer);
  type_to_handler_[type] = observer;
  observer->OnExpectationChanged(AreInvalidationsExpected());

  const auto cache_map_node = type_to_invalidation_cache_.extract(type);
  if (!cache_map_node.empty()) {
    observer->OnInvalidationReceived(cache_map_node.mapped());
  }
}

bool InvalidationListenerImpl::HasObserver(const Observer* observer) const {
  return observers_.HasObserver(observer);
}

void InvalidationListenerImpl::RemoveObserver(const Observer* observer) {
  const std::string& type = observer->GetType();
  CHECK(type_to_handler_.contains(type));
  type_to_handler_.erase(type);
  observers_.RemoveObserver(observer);
}

void InvalidationListenerImpl::Start(
    RegistrationTokenHandler* registration_token_handler) {
  // Does not allow double start.
  CHECK(!registration_token_handler_);

  // Note that `AddAppHandler()` causes an immediate replay of all received
  // invalidations in background on Android.
  gcm_driver_->AddAppHandler(gcm_app_id_, this);

  registration_token_handler_ = registration_token_handler;
  FetchRegistrationToken();
}

void InvalidationListenerImpl::Shutdown() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK(observers_.empty());
  CHECK(type_to_handler_.empty());

  registration_token_handler_ = nullptr;
  gcm_driver_->RemoveAppHandler(gcm_app_id_);
  weak_ptr_factory_.InvalidateWeakPtrs();
}

void InvalidationListenerImpl::SetRegistrationUploadStatus(
    RegistrationTokenUploadStatus status) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  registration_upload_status_ = status;
  UpdateObserversExpectations();
}

int64_t InvalidationListenerImpl::project_number() const {
  return project_number_;
}

// GCMAppHandler overrides.
void InvalidationListenerImpl::ShutdownHandler() {
  NOTREACHED()
      << "Shutdown() should come before and it removes us from the list of app "
         "handlers of gcm::GCMDriver so this shouldn't ever been called.";
}

void InvalidationListenerImpl::OnStoreReset() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // The FCM registration token is not stored by FCMHandler.
}

void InvalidationListenerImpl::OnMessage(const std::string& app_id,
                                         const gcm::IncomingMessage& message) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK_EQ(app_id, gcm_app_id_);

  VLOG(2) << log_prefix_ << " Message received";
  for (const auto& [key, value] : message.data) {
    VLOG(2) << log_prefix_ << " " << key << "->" << value;
  }

  const DirectInvalidation invalidation = ParseIncomingMessage(message);

  Observer* observer =
      base::FindPtrOrNull(type_to_handler_, invalidation.type());
  if (observer) {
    observer->OnInvalidationReceived(invalidation);
    return;
  }

  // Only cache when there is not an observer for this message `type` yet,
  // so that the listener can still deliver the message after the appropriate
  // observer is attached.
  // Otherwise, the listener directly passes the message to an observer
  // without caching.
  Upsert(type_to_invalidation_cache_, invalidation);
}

void InvalidationListenerImpl::OnMessagesDeleted(const std::string& app_id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_EQ(app_id, gcm_app_id_);
}

void InvalidationListenerImpl::OnSendError(
    const std::string& app_id,
    const gcm::GCMClient::SendErrorDetails& details) {
  NOTREACHED() << "Should never be called because the invalidation "
                  "service doesn't send GCM messages to the server.";
}

void InvalidationListenerImpl::OnSendAcknowledged(
    const std::string& app_id,
    const std::string& message_id) {
  NOTREACHED() << "Should never be called because the invalidation "
                  "service doesn't send GCM messages to the server.";
}

void InvalidationListenerImpl::FetchRegistrationToken() {
  instance_id_driver_->GetInstanceID(gcm_app_id_)
      ->GetToken(
          base::NumberToString(project_number_), instance_id::kGCMScope,
          /*time_to_live=*/kRegistrationTokenTimeToLive,
          /*flags=*/{instance_id::InstanceID::Flags::kIsLazy},
          base::BindOnce(&InvalidationListenerImpl::OnRegistrationTokenReceived,
                         weak_ptr_factory_.GetWeakPtr()));
}

void InvalidationListenerImpl::OnRegistrationTokenReceived(
    const std::string& new_registration_token,
    instance_id::InstanceID::Result result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK(registration_token_handler_);

  base::UmaHistogramEnumeration(RegistrationMetricName, result);

  const bool succeeded = result == instance_id::InstanceID::SUCCESS;

  registration_retry_backoff_.InformOfRequest(succeeded);

  if (succeeded) {
    registration_token_ = new_registration_token;
    registration_token_handler_->OnRegistrationTokenReceived(
        registration_token_.value(),
        base::Time::Now() + kRegistrationTokenTimeToLive);
    registration_retry_backoff_.Reset();
  } else {
    VLOG(2) << log_prefix_ << " Message subscription failed: " << result;
    registration_token_ = std::nullopt;
  }

  UpdateObserversExpectations();

  // Schedule the next registration token refresh or retry attempt.
  const base::TimeDelta delay =
      succeeded ? kRegistrationTokenValidationPeriod
                : registration_retry_backoff_.GetTimeUntilRelease();
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&InvalidationListenerImpl::FetchRegistrationToken,
                     weak_ptr_factory_.GetWeakPtr()),
      delay);
}

InvalidationsExpected InvalidationListenerImpl::AreInvalidationsExpected()
    const {
  return (registration_token_ && registration_upload_status_ ==
                                     RegistrationTokenUploadStatus::kSucceeded)
             ? InvalidationsExpected::kYes
             : InvalidationsExpected::kMaybe;
}

void InvalidationListenerImpl::UpdateObserversExpectations() {
  const InvalidationsExpected expected = AreInvalidationsExpected();
  for (auto& observer : observers_) {
    observer.OnExpectationChanged(expected);
  }
}

}  // namespace invalidation