File: external_connector_impl.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (327 lines) | stat: -rw-r--r-- 11,916 bytes parent folder | download
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
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromecast/external_mojo/external_service_support/external_connector_impl.h"

#include <utility>

#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
#include "base/synchronization/lock.h"
#include "base/task/sequenced_task_runner.h"
#include "base/thread_annotations.h"
#include "base/time/time.h"
#include "chromecast/external_mojo/broker_service/broker_service.h"
#include "chromecast/external_mojo/external_service_support/external_service.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/platform/named_platform_channel.h"
#include "mojo/public/cpp/platform/platform_channel_endpoint.h"
#include "mojo/public/cpp/system/invitation.h"
#include "services/service_manager/public/cpp/connector.h"

namespace chromecast {
namespace external_service_support {

namespace {
constexpr base::TimeDelta kConnectRetryDelay = base::Milliseconds(500);
}  // namespace

// Since we are only allowed to make a single underlying connection to the
// broker, we share the underlying connection between all ExternalConnector
// instances. The ExternalConnectors use clones of the underlying connection.
//
// Since connection error callbacks are called in some arbitrary order, we need
// to be careful to handle disconnection correctly. Each underlying connection
// has a unique token (int64_t) associated with it, which is propagated to all
// clones. If any clone receives a disconnect callback, it tries to reconnect by
// calling ConnectClone(), passing in the previous token (associated with the
// broken connection). BrokerConnection then attempts to reconnect the
// underlying connection if the broken connection token matches the token for
// the current connection; if it doesn't match, the connection was already
// recreated, so nothing needs to be done.
class ExternalConnectorImpl::BrokerConnection
    : public base::RefCountedThreadSafe<BrokerConnection> {
 public:
  explicit BrokerConnection(std::string broker_path)
      : broker_path_(std::move(broker_path)),
        task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) {
    Connect();
  }

  int64_t ConnectClone(
      int64_t dead_connection_token,
      mojo::PendingReceiver<external_mojo::mojom::ExternalConnector> receiver) {
    int64_t token;
    {
      base::AutoLock lock(lock_);
      if (dead_connection_token == connection_token_) {
        task_runner_->PostTask(
            FROM_HERE, base::BindOnce(&BrokerConnection::Connect, this));
        ++connection_token_;
      }
      token = connection_token_;
    }
    task_runner_->PostTask(FROM_HERE,
                           base::BindOnce(&BrokerConnection::AttachClone, this,
                                          std::move(receiver)));
    return token;
  }

 private:
  friend class base::RefCountedThreadSafe<BrokerConnection>;
  ~BrokerConnection() = default;

  void Connect() {
    DCHECK(task_runner_->RunsTasksInCurrentSequence());
    connector_.reset();
    pending_receiver_ = connector_.BindNewPipeAndPassReceiver();
    AttemptBrokerConnection();
  }

  void AttachClone(
      mojo::PendingReceiver<external_mojo::mojom::ExternalConnector> receiver) {
    DCHECK(task_runner_->RunsTasksInCurrentSequence());
    connector_->Clone(std::move(receiver));
  }

  void AttemptBrokerConnection() {
    mojo::NamedPlatformChannel::Options channel_options;
    channel_options.server_name = broker_path_;
#if BUILDFLAG(IS_ANDROID)
    // On Android, use the abstract namespace to avoid filesystem access.
    channel_options.use_abstract_namespace = true;
#endif
    mojo::PlatformChannelEndpoint endpoint =
        mojo::NamedPlatformChannel::ConnectToServer(channel_options);
    if (!endpoint.is_valid()) {
      task_runner_->PostDelayedTask(
          FROM_HERE,
          base::BindOnce(&BrokerConnection::AttemptBrokerConnection,
                         weak_factory_.GetWeakPtr()),
          kConnectRetryDelay);
      return;
    }

    auto invitation = mojo::IncomingInvitation::Accept(std::move(endpoint));
    auto remote_pipe = invitation.ExtractMessagePipe(0);
    if (!remote_pipe) {
      LOG(ERROR) << "Invalid message pipe";
      task_runner_->PostDelayedTask(
          FROM_HERE,
          base::BindOnce(&BrokerConnection::AttemptBrokerConnection,
                         weak_factory_.GetWeakPtr()),
          kConnectRetryDelay);
      return;
    }

    mojo::FuseMessagePipes(pending_receiver_.PassPipe(),
                           std::move(remote_pipe));
  }

  const std::string broker_path_;
  const scoped_refptr<base::SequencedTaskRunner> task_runner_;

  mojo::Remote<external_mojo::mojom::ExternalConnector> connector_;
  mojo::PendingReceiver<external_mojo::mojom::ExternalConnector>
      pending_receiver_;

  base::Lock lock_;
  int64_t connection_token_ GUARDED_BY(lock_) = 1;

  base::WeakPtrFactory<BrokerConnection> weak_factory_{this};
};

// static
void ExternalConnector::Connect(
    const std::string& broker_path,
    base::OnceCallback<void(std::unique_ptr<ExternalConnector>)> callback) {
  DCHECK(callback);
  std::move(callback).Run(Create(broker_path));
}

// static
std::unique_ptr<ExternalConnector> ExternalConnector::Create(
    const std::string& broker_path) {
  return std::make_unique<ExternalConnectorImpl>(broker_path);
}

// static
std::unique_ptr<ExternalConnector> ExternalConnector::Create(
    mojo::PendingRemote<external_mojo::mojom::ExternalConnector> remote) {
  return std::make_unique<ExternalConnectorImpl>(std::move(remote));
}

// static
std::unique_ptr<ExternalConnector> ExternalConnector::Create(
    service_manager::Connector* connector) {
  mojo::PendingRemote<external_mojo::mojom::ExternalConnector> pending_remote;
  connector->BindInterface(external_mojo::BrokerService::kServiceName,
                           pending_remote.InitWithNewPipeAndPassReceiver());
  return std::make_unique<ExternalConnectorImpl>(std::move(pending_remote));
}

ExternalConnectorImpl::ExternalConnectorImpl(const std::string& broker_path)
    : broker_connection_(base::MakeRefCounted<BrokerConnection>(broker_path)) {
  DETACH_FROM_SEQUENCE(sequence_checker_);
  Connect();
}

ExternalConnectorImpl::ExternalConnectorImpl(
    scoped_refptr<BrokerConnection> broker_connection)
    : broker_connection_(broker_connection) {
  DETACH_FROM_SEQUENCE(sequence_checker_);
  Connect();
}

ExternalConnectorImpl::ExternalConnectorImpl(
    mojo::PendingRemote<external_mojo::mojom::ExternalConnector> pending_remote)
    : pending_remote_(std::move(pending_remote)) {
  DETACH_FROM_SEQUENCE(sequence_checker_);
}

ExternalConnectorImpl::~ExternalConnectorImpl() = default;

base::CallbackListSubscription
ExternalConnectorImpl::AddConnectionErrorCallback(
    base::RepeatingClosure callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return error_closures_.Add(std::move(callback));
}

void ExternalConnectorImpl::RegisterService(const std::string& service_name,
                                            ExternalService* service) {
  RegisterService(service_name, service->GetReceiver());
}

void ExternalConnectorImpl::RegisterService(
    const std::string& service_name,
    mojo::PendingRemote<external_mojo::mojom::ExternalService> service_remote) {
  BindConnectorIfNecessary();
  auto service_instance_info =
      chromecast::external_mojo::mojom::ServiceInstanceInfo::New(
          service_name, std::move(service_remote));
  std::vector<chromecast::external_mojo::mojom::ServiceInstanceInfoPtr> v;
  v.emplace_back(std::move(service_instance_info));
  connector_->RegisterServiceInstances(std::move(v));
}

void ExternalConnectorImpl::RegisterServices(
    const std::vector<std::string>& service_names,
    const std::vector<ExternalService*>& services) {
  CHECK(service_names.size() == services.size());
  std::vector<chromecast::external_mojo::mojom::ServiceInstanceInfoPtr>
      service_instances_info;
  service_instances_info.reserve(services.size());
  for (size_t i = 0; i < services.size(); ++i) {
    service_instances_info.emplace_back(
        chromecast::external_mojo::mojom::ServiceInstanceInfo::New(
            service_names[i], services[i]->GetReceiver()));
  }

  RegisterServices(std::move(service_instances_info));
}

void ExternalConnectorImpl::RegisterServices(
    std::vector<chromecast::external_mojo::mojom::ServiceInstanceInfoPtr>
        service_instances_info) {
  BindConnectorIfNecessary();
  connector_->RegisterServiceInstances(std::move(service_instances_info));
}

void ExternalConnectorImpl::QueryServiceList(
    base::OnceCallback<void(
        std::vector<chromecast::external_mojo::mojom::ExternalServiceInfoPtr>)>
        callback) {
  BindConnectorIfNecessary();
  connector_->QueryServiceList(std::move(callback));
}

void ExternalConnectorImpl::BindInterface(
    const std::string& service_name,
    const std::string& interface_name,
    mojo::ScopedMessagePipeHandle interface_pipe,
    bool async) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!async) {
    BindInterfaceImmediately(service_name, interface_name,
                             std::move(interface_pipe));
    return;
  }
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(&ExternalConnectorImpl::BindInterfaceImmediately,
                     weak_factory_.GetWeakPtr(), service_name, interface_name,
                     std::move(interface_pipe)));
}

void ExternalConnectorImpl::BindInterfaceImmediately(
    const std::string& service_name,
    const std::string& interface_name,
    mojo::ScopedMessagePipeHandle interface_pipe) {
  BindConnectorIfNecessary();
  connector_->BindInterface(service_name, interface_name,
                            std::move(interface_pipe));
}

std::unique_ptr<ExternalConnector> ExternalConnectorImpl::Clone() {
  if (broker_connection_) {
    return std::make_unique<ExternalConnectorImpl>(broker_connection_);
  }
  // Bind to the current sequence since this is a public method.
  BindConnectorIfNecessary();
  return std::make_unique<ExternalConnectorImpl>(RequestConnector());
}

mojo::PendingRemote<external_mojo::mojom::ExternalConnector>
ExternalConnectorImpl::RequestConnector() {
  // Bind to the current sequence since this is a public method.
  BindConnectorIfNecessary();
  mojo::PendingRemote<external_mojo::mojom::ExternalConnector> remote;
  connector_->Clone(remote.InitWithNewPipeAndPassReceiver());
  return remote;
}

void ExternalConnectorImpl::SendChromiumConnectorRequest(
    mojo::ScopedMessagePipeHandle request) {
  BindConnectorIfNecessary();
  connector_->BindChromiumConnector(std::move(request));
}

void ExternalConnectorImpl::Connect() {
  DCHECK(broker_connection_);
  connection_token_ = broker_connection_->ConnectClone(
      connection_token_, pending_remote_.InitWithNewPipeAndPassReceiver());
}

void ExternalConnectorImpl::OnMojoDisconnect() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  connector_.reset();
  pending_remote_.reset();
  if (broker_connection_) {
    Connect();
    BindConnectorIfNecessary();
  }
  error_closures_.Notify();
}

void ExternalConnectorImpl::BindConnectorIfNecessary() {
  // Bind the message pipe and SequenceChecker to the current thread the first
  // time it is used to connect.
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (connector_.is_bound()) {
    return;
  }

  DCHECK(pending_remote_.is_valid());

  connector_.Bind(std::move(pending_remote_));
  connector_.set_disconnect_handler(base::BindOnce(
      &ExternalConnectorImpl::OnMojoDisconnect, base::Unretained(this)));
}

}  // namespace external_service_support
}  // namespace chromecast