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

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: Removing redundant reset() call. 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
30 const char RpcHandler::kReportRequestRpcName[] = "report";
31
32 namespace {
33
34 // UrlSafe is defined as:
35 // '/' represented by a '_' and '+' represented by a '-'
36 // TODO(rkc): Move this to the wrapper.
37 std::string ToUrlSafe(std::string token) {
38 base::ReplaceChars(token, "+", "-", &token);
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 } // namespace
175
176 // Public methods
177
178 RpcHandler::RpcHandler(CopresenceClientDelegate* delegate)
179 : delegate_(delegate),
180 invalid_audio_token_cache_(
181 base::TimeDelta::FromMilliseconds(kInvalidTokenExpiryTimeMs),
182 kMaxInvalidTokens),
183 server_post_callback_(base::Bind(&RpcHandler::SendHttpPost,
184 AsWeakPtr())) {}
18 185
19 RpcHandler::~RpcHandler() { 186 RpcHandler::~RpcHandler() {
20 } 187 for (std::set<HttpPost*>::iterator post = pending_posts_.begin();
21 188 post != pending_posts_.end(); ++post) {
22 void RpcHandler::SendReportRequest( 189 (*post)->Cancel();
23 scoped_ptr<copresence::ReportRequest> request) { 190 }
24 } 191 }
25 192
26 void RpcHandler::SendReportRequest( 193 void RpcHandler::Initialize(const SuccessCallback& init_done_callback) {
27 scoped_ptr<copresence::ReportRequest> request, 194 scoped_ptr<RegisterDeviceRequest> request(new RegisterDeviceRequest);
195 DCHECK(device_id_.empty());
196 device_id_ = delegate_->GetDeviceId();
197 if (!device_id_.empty()) {
198 init_done_callback.Run(true);
199 return;
200 }
201
202 request->mutable_push_service()->set_service(PUSH_SERVICE_NONE);
203 Identity* identity =
204 request->mutable_device_identifiers()->mutable_registrant();
205 identity->set_type(CHROME);
206 identity->set_chrome_id(base::GenerateGUID());
207 SendServerRequest(
208 kRegisterDeviceRpcName,
209 std::string(),
210 request.Pass(),
211 base::Bind(&RpcHandler::RegisterResponseHandler,
212 AsWeakPtr(),
213 init_done_callback));
214 }
215
216 void RpcHandler::SendReportRequest(scoped_ptr<ReportRequest> request) {
217 SendReportRequest(request.Pass(), std::string(), StatusCallback());
218 }
219
220 void RpcHandler::SendReportRequest(scoped_ptr<ReportRequest> request,
221 const std::string& app_id,
222 const StatusCallback& status_callback) {
223 DCHECK(request.get());
224 DCHECK(!device_id_.empty())
225 << "RpcHandler::Initialize() must complete successfully "
226 << "before other RpcHandler methods are called.";
227
228 DVLOG(3) << "Sending report request to server.";
229
230 request->mutable_update_signals_request()->set_allocated_state(
231 GetDeviceCapabilities(*request).release());
232 SendServerRequest(
233 kReportRequestRpcName,
234 app_id,
235 request.Pass(),
236 base::Bind(
237 &RpcHandler::ReportResponseHandler, AsWeakPtr(), status_callback));
238 }
239
240 void RpcHandler::ReportTokens(TokenMedium medium,
241 const std::vector<std::string>& tokens) {
242 DCHECK_EQ(medium, AUDIO_ULTRASOUND_PASSBAND);
243 DCHECK(!tokens.empty());
244
245 scoped_ptr<ReportRequest> request(new ReportRequest);
246 for (size_t i = 0; i < tokens.size(); ++i) {
247 const std::string& token = ToUrlSafe(tokens[i]);
248 if (invalid_audio_token_cache_.HasKey(token))
249 continue;
250
251 DVLOG(3) << "Sending token " << token << " to server.";
252
253 TokenObservation* token_observation =
254 request->mutable_update_signals_request()->add_token_observation();
255 token_observation->set_token_id(token);
256
257 TokenSignals* signals = token_observation->add_signals();
258 signals->set_medium(medium);
259 signals->set_observed_time_millis(base::Time::Now().ToJsTime());
260 }
261 SendReportRequest(request.Pass());
262 }
263
264 void RpcHandler::ConnectToWhispernet() {
265 WhispernetClient* whispernet_client = delegate_->GetWhispernetClient();
266
267 // |directive_handler_| will be destructed before us, so unretained is safe.
268 directive_handler_.reset(new DirectiveHandler);
269 directive_handler_->Initialize(
270 base::Bind(&WhispernetClient::DecodeSamples,
271 base::Unretained(whispernet_client)),
272 base::Bind(&RpcHandler::AudioDirectiveListToWhispernetConnector,
273 base::Unretained(this)));
274
275 whispernet_client->RegisterTokensCallback(
276 base::Bind(&RpcHandler::ReportTokens,
277 AsWeakPtr(),
278 AUDIO_ULTRASOUND_PASSBAND));
279 }
280
281 void RpcHandler::DisconnectFromWhispernet() {
282 directive_handler_.reset();
283 }
284
285 // Private methods
286
287 void RpcHandler::RegisterResponseHandler(
288 const SuccessCallback& init_done_callback,
289 int http_status_code,
290 const std::string& response_data,
291 HttpPost* completed_post) {
292 if (completed_post)
293 pending_posts_.erase(completed_post);
294
295 if (http_status_code != net::HTTP_OK) {
296 init_done_callback.Run(false);
297 return;
298 }
299
300 RegisterDeviceResponse response;
301 if (!response.ParseFromString(response_data)) {
302 LOG(ERROR) << "Invalid RegisterDeviceResponse:\n" << response_data;
303 init_done_callback.Run(false);
304 return;
305 }
306
307 if (CopresenceErrorLogged(response.header().status()))
308 return;
309 device_id_ = response.registered_device_id();
310 DCHECK(!device_id_.empty());
311 DVLOG(2) << "Device registration successful: id " << device_id_;
312 delegate_->SaveDeviceId(device_id_);
313 init_done_callback.Run(true);
314 }
315
316 void RpcHandler::ReportResponseHandler(const StatusCallback& status_callback,
317 int http_status_code,
318 const std::string& response_data,
319 HttpPost* completed_post) {
320 if (completed_post)
321 pending_posts_.erase(completed_post);
322
323 if (http_status_code != net::HTTP_OK) {
324 if (!status_callback.is_null())
325 status_callback.Run(FAIL);
326 return;
327 }
328
329 DVLOG(3) << "Received ReportResponse.";
330 ReportResponse response;
331 if (!response.ParseFromString(response_data)) {
332 LOG(ERROR) << "Invalid ReportResponse";
333 if (!status_callback.is_null())
334 status_callback.Run(FAIL);
335 return;
336 }
337
338 if (ReportErrorLogged(response)) {
339 if (!status_callback.is_null())
340 status_callback.Run(FAIL);
341 return;
342 }
343
344 const RepeatedPtrField<MessageResult>& message_results =
345 response.manage_messages_response().published_message_result();
346 for (int i = 0; i < message_results.size(); ++i) {
347 DVLOG(2) << "Published message with id "
348 << message_results.Get(i).published_message_id();
349 }
350
351 const RepeatedPtrField<SubscriptionResult>& subscription_results =
352 response.manage_subscriptions_response().subscription_result();
353 for (int i = 0; i < subscription_results.size(); ++i) {
354 DVLOG(2) << "Created subscription with id "
355 << subscription_results.Get(i).subscription_id();
356 }
357
358 if (response.has_update_signals_response()) {
359 const UpdateSignalsResponse& update_response =
360 response.update_signals_response();
361 DispatchMessages(update_response.message());
362
363 if (directive_handler_.get()) {
364 for (int i = 0; i < update_response.directive_size(); ++i)
365 directive_handler_->AddDirective(update_response.directive(i));
366 } else {
367 DVLOG(1) << "No directive handler.";
368 }
369
370 const RepeatedPtrField<Token>& tokens = update_response.token();
371 for (int i = 0; i < tokens.size(); ++i) {
372 switch (tokens.Get(i).status()) {
373 case VALID:
374 // TODO(rkc/ckehoe): Store the token in a |valid_token_cache_| with a
375 // short TTL (like 10s) and send it up with every report request.
376 // Then we'll still get messages while we're waiting to hear it again.
377 VLOG(1) << "Got valid token " << tokens.Get(i).id();
378 break;
379 case INVALID:
380 DVLOG(3) << "Discarding invalid token " << tokens.Get(i).id();
381 invalid_audio_token_cache_.Add(tokens.Get(i).id(), true);
382 break;
383 default:
384 DVLOG(2) << "Token " << tokens.Get(i).id() << " has status code "
385 << tokens.Get(i).status();
386 }
387 }
388 }
389
390 // TODO(ckehoe): Return a more detailed status response.
391 if (!status_callback.is_null())
392 status_callback.Run(SUCCESS);
393 }
394
395 void RpcHandler::DispatchMessages(
396 const RepeatedPtrField<SubscribedMessage>& messages) {
397 if (messages.size() == 0)
398 return;
399
400 // Index the messages by subscription id.
401 std::map<std::string, std::vector<Message> > messages_by_subscription;
402 DVLOG(3) << "Dispatching " << messages.size() << " messages";
403 for (int m = 0; m < messages.size(); ++m) {
404 const RepeatedPtrField<std::string>& subscription_ids =
405 messages.Get(m).subscription_id();
406 for (int s = 0; s < subscription_ids.size(); ++s) {
407 messages_by_subscription[subscription_ids.Get(s)].push_back(
408 messages.Get(m).published_message());
409 }
410 }
411
412 // Send the messages for each subscription.
413 for (std::map<std::string, std::vector<Message> >::const_iterator
414 subscription = messages_by_subscription.begin();
415 subscription != messages_by_subscription.end();
416 ++subscription) {
417 // TODO(ckehoe): Once we have the app ID from the server, we need to pass
418 // it in here and get rid of the app id registry from the main API class.
419 delegate_->HandleMessages("", subscription->first, subscription->second);
420 }
421 }
422
423 RequestHeader* RpcHandler::CreateRequestHeader(
424 const std::string& client_name) const {
425 RequestHeader* header = new RequestHeader;
426
427 header->set_allocated_framework_version(
428 CreateVersion("Chrome", delegate_->GetPlatformVersionString()));
429 if (!client_name.empty()) {
430 header->set_allocated_client_version(
431 CreateVersion(client_name, std::string()));
432 }
433 header->set_current_time_millis(base::Time::Now().ToJsTime());
434 header->set_registered_device_id(device_id_);
435
436 return header;
437 }
438
439 template <class T>
440 void RpcHandler::SendServerRequest(
441 const std::string& rpc_name,
28 const std::string& app_id, 442 const std::string& app_id,
29 const StatusCallback& status_callback) { 443 scoped_ptr<T> request,
30 } 444 const HttpPost::ResponseCallback& response_handler) {
31 445 request->set_allocated_header(CreateRequestHeader(app_id));
32 void RpcHandler::ReportTokens(copresence::TokenMedium medium, 446 server_post_callback_.Run(delegate_->GetRequestContext(),
33 const std::vector<std::string>& tokens) { 447 rpc_name,
34 } 448 make_scoped_ptr<MessageLite>(request.release()),
35 449 response_handler);
36 void RpcHandler::ConnectToWhispernet(WhispernetClient* whispernet_client) { 450 }
37 } 451
38 452 void RpcHandler::SendHttpPost(net::URLRequestContextGetter* url_context_getter,
39 void RpcHandler::DisconnectFromWhispernet() { 453 const std::string& rpc_name,
454 scoped_ptr<MessageLite> request_proto,
455 const HttpPost::ResponseCallback& callback) {
456 // Create the base URL to call.
457 CommandLine* command_line = CommandLine::ForCurrentProcess();
458 const std::string copresence_server_host =
459 command_line->HasSwitch(switches::kCopresenceServer) ?
460 command_line->GetSwitchValueASCII(switches::kCopresenceServer) :
461 kDefaultCopresenceServer;
462
463 // Create the request and keep a pointer until it completes.
464 pending_posts_.insert(new HttpPost(url_context_getter,
465 copresence_server_host,
466 rpc_name,
467 *request_proto,
468 callback));
469 }
470
471 void RpcHandler::AudioDirectiveListToWhispernetConnector(
472 const std::string& token,
473 const WhispernetClient::SamplesCallback& samples_callback) {
474 WhispernetClient* whispernet_client = delegate_->GetWhispernetClient();
475 if (whispernet_client) {
476 whispernet_client->RegisterSamplesCallback(samples_callback);
477 whispernet_client->EncodeToken(token);
478 }
40 } 479 }
41 480
42 } // namespace copresence 481 } // namespace copresence
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698