Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(113)

Side by Side Diff: components/copresence/rpc/rpc_handler.cc

Issue 433283002: Adding the Copresence RpcHandler and HttpPost helper. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@directive-handler
Patch Set: Fixes for DEPS review Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "components/copresence/rpc/rpc_handler.h" 5 #include "components/copresence/rpc/rpc_handler.h"
6 6
7 #include <map>
8
7 #include "base/bind.h" 9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/guid.h"
12 #include "base/logging.h"
13 #include "base/strings/string_util.h"
14 #include "base/time/time.h"
15 #include "components/copresence/copresence_switches.h"
16 #include "components/copresence/handlers/directive_handler.h"
17 #include "components/copresence/proto/codes.pb.h"
8 #include "components/copresence/proto/data.pb.h" 18 #include "components/copresence/proto/data.pb.h"
9 #include "components/copresence/proto/rpcs.pb.h" 19 #include "components/copresence/proto/rpcs.pb.h"
10 #include "components/copresence/public/copresence_client_delegate.h" 20 #include "components/copresence/public/copresence_client_delegate.h"
11 #include "components/copresence/public/whispernet_client.h" 21 #include "net/http/http_status_code.h"
22
23 // TODO(ckehoe): Return error messages for bad requests.
12 24
13 namespace copresence { 25 namespace copresence {
14 26
15 RpcHandler::RpcHandler(CopresenceClientDelegate* delegate, 27 using google::protobuf::MessageLite;
16 SuccessCallback init_done_callback) { 28 using google::protobuf::RepeatedPtrField;
17 } 29
18 30 const char RpcHandler::kReportRequestRpcName[] = "report";
19 RpcHandler::~RpcHandler() { 31
20 } 32 namespace {
21 33
22 void RpcHandler::SendReportRequest( 34 // UrlSafe is defined as:
23 scoped_ptr<copresence::ReportRequest> request) { 35 // '/' represented by a '_' and '+' represented by a '-'
24 } 36 // TODO(rkc): Move this to the wrapper.
25 37 std::string ToUrlSafe(std::string token) {
26 void RpcHandler::SendReportRequest( 38 base::ReplaceChars(token, "+", "-", &token);
27 scoped_ptr<copresence::ReportRequest> request, 39 base::ReplaceChars(token, "/", "_", &token);
40 return token;
41 }
42
43 const int kInvalidTokenExpiryTimeMs = 10 * 60 * 1000; // 10 minutes.
44 const int kMaxInvalidTokens = 10000;
45 const char kRegisterDeviceRpcName[] = "registerdevice";
46 const char kDefaultCopresenceServer[] =
47 "https://www.googleapis.com/copresence/v2/copresence";
48
49 // Logging
50
51 // Checks for a copresence error. If there is one, logs it and returns true.
52 bool CopresenceErrorLogged(const Status& status) {
53 if (status.code() != OK) {
54 LOG(ERROR) << "Copresence error code " << status.code()
55 << (status.message().empty() ? std::string() :
56 ": " + status.message());
57 }
58 return status.code() != OK;
59 }
60
61 void LogIfErrorStatus(const util::error::Code& code,
62 const std::string& context) {
63 LOG_IF(ERROR, code != util::error::OK)
64 << context << " error " << code << ". See "
65 << "cs/google3/util/task/codes.proto for more info.";
66 }
67
68 // If any errors occurred, logs them and returns true.
69 bool ReportErrorLogged(const ReportResponse& response) {
70 bool result = CopresenceErrorLogged(response.header().status());
71
72 // The Report fails or succeeds as a unit. If any responses had errors,
73 // the header will too. Thus we don't need to propagate individual errors.
74 if (response.has_update_signals_response())
75 LogIfErrorStatus(response.update_signals_response().status(), "Update");
76 if (response.has_manage_messages_response())
77 LogIfErrorStatus(response.manage_messages_response().status(), "Publish");
78 if (response.has_manage_subscriptions_response()) {
79 LogIfErrorStatus(response.manage_subscriptions_response().status(),
80 "Subscribe");
81 }
82
83 return result;
84 }
85
86 // Request construction
87
88 template <typename T>
89 BroadcastScanConfiguration GetBroadcastScanConfig(const T& msg) {
90 if (msg.has_token_exchange_strategy() &&
91 msg.token_exchange_strategy().has_broadcast_scan_configuration()) {
92 return msg.token_exchange_strategy().broadcast_scan_configuration();
93 }
94 return BROADCAST_SCAN_CONFIGURATION_UNKNOWN;
95 }
96
97 // This method will extract token exchange strategies
98 // from the publishes and subscribes in a report request.
99 // TODO(ckehoe): Delete this when the server supports
100 // BroadcastScanConfiguration.
101 BroadcastScanConfiguration ExtractTokenExchangeStrategy(
102 const ReportRequest& request) {
103 bool broadcast_only = false;
104 bool scan_only = false;
105
106 // Strategies for publishes.
107 if (request.has_manage_messages_request()) {
108 const RepeatedPtrField<PublishedMessage> messages =
109 request.manage_messages_request().message_to_publish();
110 for (int i = 0; i < messages.size(); ++i) {
111 BroadcastScanConfiguration config =
112 GetBroadcastScanConfig(messages.Get(i));
113 broadcast_only = broadcast_only || config == BROADCAST_ONLY;
114 scan_only = scan_only || config == SCAN_ONLY;
115 if (config == BROADCAST_AND_SCAN || (broadcast_only && scan_only))
116 return BROADCAST_AND_SCAN;
117 }
118 }
119
120 // Strategies for subscriptions.
121 if (request.has_manage_subscriptions_request()) {
122 const RepeatedPtrField<Subscription> messages =
123 request.manage_subscriptions_request().subscription();
124 for (int i = 0; i < messages.size(); ++i) {
125 BroadcastScanConfiguration config =
126 GetBroadcastScanConfig(messages.Get(i));
127 broadcast_only = broadcast_only || config == BROADCAST_ONLY;
128 scan_only = scan_only || config == SCAN_ONLY;
129 if (config == BROADCAST_AND_SCAN || (broadcast_only && scan_only))
130 return BROADCAST_AND_SCAN;
131 }
132 }
133
134 if (broadcast_only)
135 return BROADCAST_ONLY;
136 if (scan_only)
137 return SCAN_ONLY;
138
139 // If nothing else is specified, default to both broadcast and scan.
140 return BROADCAST_AND_SCAN;
141 }
142
143 scoped_ptr<DeviceState> GetDeviceCapabilities(const ReportRequest& request) {
144 scoped_ptr<DeviceState> state(new DeviceState);
145
146 TokenTechnology* token_technology =
147 state->mutable_capabilities()->add_token_technology();
148 token_technology->set_medium(AUDIO_ULTRASOUND_PASSBAND);
149
150 BroadcastScanConfiguration config =
151 ExtractTokenExchangeStrategy(request);
152 if (config == BROADCAST_ONLY || config == BROADCAST_AND_SCAN)
153 token_technology->add_instruction_type(TRANSMIT);
154 if (config == SCAN_ONLY || config == BROADCAST_AND_SCAN)
155 token_technology->add_instruction_type(RECEIVE);
156
157 return state.Pass();
158 }
159
160 // TODO(ckehoe): We're keeping this code in a separate function for now
161 // because we get a version string from Chrome, but the proto expects
162 // an int64 version. We should probably change the version proto
163 // to handle a more detailed version.
164 ClientVersion* CreateVersion(const std::string& client,
165 const std::string& version_name) {
166 ClientVersion* version = new ClientVersion;
167
168 version->set_client(client);
169 version->set_version_name(version_name);
170
171 return version;
172 }
173
174 // Wrapper for the http post constructor. This is the default way
175 // to contact the server, but it can be overridden for testing.
176 void SendHttpPost(net::URLRequestContextGetter* url_context_getter,
177 const std::string& rpc_name,
178 scoped_ptr<MessageLite> request_proto,
179 const HttpPost::ResponseCallback& callback) {
180 // Create the base URL to call.
181 CommandLine* command_line = CommandLine::ForCurrentProcess();
182 const std::string copresence_server_host =
183 command_line->HasSwitch(switches::kCopresenceServer) ?
184 command_line->GetSwitchValueASCII(switches::kCopresenceServer) :
185 kDefaultCopresenceServer;
186
187 new HttpPost(url_context_getter,
188 copresence_server_host,
189 rpc_name,
190 *request_proto,
191 callback);
192 }
193
194 } // namespace
195
196 // Public methods
197
198 RpcHandler::RpcHandler(CopresenceClientDelegate* delegate)
199 : delegate_(delegate),
200 invalid_audio_token_cache_(
201 base::TimeDelta::FromMilliseconds(kInvalidTokenExpiryTimeMs),
202 kMaxInvalidTokens),
203 server_post_callback_(base::Bind(&SendHttpPost)) {
204 }
205
206 RpcHandler::~RpcHandler() {}
207
208 void RpcHandler::Initialize(const SuccessCallback& init_done_callback) {
209 scoped_ptr<RegisterDeviceRequest> request(new RegisterDeviceRequest);
210 DCHECK(device_id_.empty());
211 device_id_ = delegate_->GetDeviceId();
212 if (!device_id_.empty()) {
213 init_done_callback.Run(true);
214 return;
215 }
216
217 request->mutable_push_service()->set_service(PUSH_SERVICE_NONE);
218 Identity* identity =
219 request->mutable_device_identifiers()->mutable_registrant();
220 identity->set_type(CHROME);
221 identity->set_chrome_id(base::GenerateGUID());
222 SendServerRequest(
223 kRegisterDeviceRpcName,
224 std::string(),
225 request.Pass(),
226 base::Bind(&RpcHandler::RegisterResponseHandler,
227 AsWeakPtr(),
228 init_done_callback));
229 }
230
231 void RpcHandler::SendReportRequest(scoped_ptr<ReportRequest> request) {
232 SendReportRequest(request.Pass(), std::string(), StatusCallback());
233 }
234
235 void RpcHandler::SendReportRequest(scoped_ptr<ReportRequest> request,
236 const std::string& app_id,
237 const StatusCallback& status_callback) {
238 DCHECK(request.get());
239 DCHECK(!device_id_.empty())
240 << "RpcHandler::Initialize() must complete successfully "
241 << "before other RpcHandler methods are called.";
242
243 DVLOG(3) << "Sending report request to server.";
244
245 request->mutable_update_signals_request()->set_allocated_state(
246 GetDeviceCapabilities(*request).release());
247 SendServerRequest(
248 kReportRequestRpcName,
249 app_id,
250 request.Pass(),
251 base::Bind(
252 &RpcHandler::ReportResponseHandler, AsWeakPtr(), status_callback));
253 }
254
255 void RpcHandler::ReportTokens(TokenMedium medium,
256 const std::vector<std::string>& tokens) {
257 DCHECK_EQ(medium, AUDIO_ULTRASOUND_PASSBAND);
258 DCHECK(!tokens.empty());
259
260 scoped_ptr<ReportRequest> request(new ReportRequest);
261 for (size_t i = 0; i < tokens.size(); ++i) {
262 const std::string& token = ToUrlSafe(tokens[i]);
263 if (invalid_audio_token_cache_.HasKey(token))
264 continue;
265
266 DVLOG(3) << "Sending token " << token << " to server.";
267
268 TokenObservation* token_observation =
269 request->mutable_update_signals_request()->add_token_observation();
270 token_observation->set_token_id(token);
271
272 TokenSignals* signals = token_observation->add_signals();
273 signals->set_medium(medium);
274 signals->set_observed_time_millis(base::Time::Now().ToJsTime());
275 }
276 SendReportRequest(request.Pass());
277 }
278
279 void RpcHandler::ConnectToWhispernet() {
280 WhispernetClient* whispernet_client = delegate_->GetWhispernetClient();
281
282 // |directive_handler_| will be destructed before us, so unretained is safe.
283 directive_handler_.reset(new DirectiveHandler);
284 directive_handler_->Initialize(
285 base::Bind(&WhispernetClient::DecodeSamples,
286 base::Unretained(whispernet_client)),
287 base::Bind(&RpcHandler::AudioDirectiveListToWhispernetConnector,
288 base::Unretained(this)));
289
290 whispernet_client->RegisterTokensCallback(
291 base::Bind(&RpcHandler::ReportTokens,
292 AsWeakPtr(),
293 AUDIO_ULTRASOUND_PASSBAND));
294 }
295
296 void RpcHandler::DisconnectFromWhispernet() {
297 directive_handler_.reset();
298 }
299
300 // Private methods
301
302 void RpcHandler::RegisterResponseHandler(
303 const SuccessCallback& init_done_callback,
304 int http_status_code,
305 const std::string& response_data) {
306 if (http_status_code != net::HTTP_OK) {
307 init_done_callback.Run(false);
308 return;
309 }
310
311 RegisterDeviceResponse response;
312 if (!response.ParseFromString(response_data)) {
313 LOG(ERROR) << "Invalid RegisterDeviceResponse:\n" << response_data;
314 init_done_callback.Run(false);
315 return;
316 }
317
318 if (CopresenceErrorLogged(response.header().status()))
319 return;
320 device_id_ = response.registered_device_id();
321 DCHECK(!device_id_.empty());
322 DVLOG(2) << "Device registration successful: id " << device_id_;
323 delegate_->SaveDeviceId(device_id_);
324 init_done_callback.Run(true);
325 }
326
327 void RpcHandler::ReportResponseHandler(const StatusCallback& status_callback,
328 int http_status_code,
329 const std::string& response_data) {
330 if (http_status_code != net::HTTP_OK) {
331 if (!status_callback.is_null())
332 status_callback.Run(FAIL);
333 return;
334 }
335
336 DVLOG(3) << "Received ReportResponse.";
337 ReportResponse response;
338 if (!response.ParseFromString(response_data)) {
339 LOG(ERROR) << "Invalid ReportResponse";
340 if (!status_callback.is_null())
341 status_callback.Run(FAIL);
342 return;
343 }
344
345 if (ReportErrorLogged(response)) {
346 if (!status_callback.is_null())
347 status_callback.Run(FAIL);
348 return;
349 }
350
351 const RepeatedPtrField<MessageResult>& message_results =
352 response.manage_messages_response().published_message_result();
353 for (int i = 0; i < message_results.size(); ++i) {
354 DVLOG(2) << "Published message with id "
355 << message_results.Get(i).published_message_id();
356 }
357
358 const RepeatedPtrField<SubscriptionResult>& subscription_results =
359 response.manage_subscriptions_response().subscription_result();
360 for (int i = 0; i < subscription_results.size(); ++i) {
361 DVLOG(2) << "Created subscription with id "
362 << subscription_results.Get(i).subscription_id();
363 }
364
365 if (response.has_update_signals_response()) {
366 const UpdateSignalsResponse& update_response =
367 response.update_signals_response();
368 DispatchMessages(update_response.message());
369
370 if (directive_handler_.get()) {
371 for (int i = 0; i < update_response.directive_size(); ++i)
372 directive_handler_->AddDirective(update_response.directive(i));
373 } else {
374 DVLOG(1) << "No directive handler.";
375 }
376
377 const RepeatedPtrField<Token>& tokens = update_response.token();
378 for (int i = 0; i < tokens.size(); ++i) {
379 switch (tokens.Get(i).status()) {
380 case VALID:
381 // TODO(rkc/ckehoe): Store the token in a |valid_token_cache_| with a
382 // short TTL (like 10s) and send it up with every report request.
383 // Then we'll still get messages while we're waiting to hear it again.
384 VLOG(1) << "Got valid token " << tokens.Get(i).id();
385 break;
386 case INVALID:
387 DVLOG(3) << "Discarding invalid token " << tokens.Get(i).id();
388 invalid_audio_token_cache_.Add(tokens.Get(i).id(), true);
389 break;
390 default:
391 DVLOG(2) << "Token " << tokens.Get(i).id() << " has status code "
392 << tokens.Get(i).status();
393 }
394 }
395 }
396
397 // TODO(ckehoe): Return a more detailed status response.
398 if (!status_callback.is_null())
399 status_callback.Run(SUCCESS);
400 }
401
402 void RpcHandler::DispatchMessages(
403 const RepeatedPtrField<SubscribedMessage>& messages) {
404 if (messages.size() == 0)
405 return;
406
407 // Index the messages by subscription id.
408 std::map<std::string, std::vector<Message> > messages_by_subscription;
409 DVLOG(3) << "Dispatching " << messages.size() << " messages";
410 for (int m = 0; m < messages.size(); ++m) {
411 const RepeatedPtrField<std::string>& subscription_ids =
412 messages.Get(m).subscription_id();
413 for (int s = 0; s < subscription_ids.size(); ++s) {
414 messages_by_subscription[subscription_ids.Get(s)].push_back(
415 messages.Get(m).published_message());
416 }
417 }
418
419 // Send the messages for each subscription.
420 for (std::map<std::string, std::vector<Message> >::const_iterator
421 subscription = messages_by_subscription.begin();
422 subscription != messages_by_subscription.end();
423 ++subscription) {
424 // TODO(ckehoe): Once we have the app ID from the server, we need to pass
425 // it in here and get rid of the app id registry from the main API class.
426 delegate_->HandleMessages("", subscription->first, subscription->second);
427 }
428 }
429
430 RequestHeader* RpcHandler::CreateRequestHeader(
431 const std::string& client_name) const {
432 RequestHeader* header = new RequestHeader;
433
434 header->set_allocated_framework_version(
435 CreateVersion("Chrome", delegate_->GetPlatformVersionString()));
436 if (!client_name.empty()) {
437 header->set_allocated_client_version(
438 CreateVersion(client_name, std::string()));
439 }
440 header->set_current_time_millis(base::Time::Now().ToJsTime());
441 header->set_registered_device_id(device_id_);
442
443 return header;
444 }
445
446 template <class T>
447 void RpcHandler::SendServerRequest(
448 const std::string& rpc_name,
28 const std::string& app_id, 449 const std::string& app_id,
29 const StatusCallback& status_callback) { 450 scoped_ptr<T> request,
30 } 451 const HttpPost::ResponseCallback& response_handler) {
31 452 request->set_allocated_header(CreateRequestHeader(app_id));
32 void RpcHandler::ReportTokens(copresence::TokenMedium medium, 453 server_post_callback_.Run(delegate_->GetRequestContext(),
33 const std::vector<std::string>& tokens) { 454 rpc_name,
34 } 455 make_scoped_ptr<MessageLite>(request.release()),
35 456 response_handler);
36 void RpcHandler::ConnectToWhispernet(WhispernetClient* whispernet_client) { 457 }
37 } 458
38 459 void RpcHandler::AudioDirectiveListToWhispernetConnector(
39 void RpcHandler::DisconnectFromWhispernet() { 460 const std::string& token,
461 const WhispernetClient::SamplesCallback& samples_callback) {
462 WhispernetClient* whispernet_client = delegate_->GetWhispernetClient();
463 if (whispernet_client) {
464 whispernet_client->RegisterSamplesCallback(samples_callback);
465 whispernet_client->EncodeToken(token);
466 }
40 } 467 }
41 468
42 } // namespace copresence 469 } // namespace copresence
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698