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

Side by Side Diff: extensions/browser/api/cast_channel/cast_transport.cc

Issue 555283002: Create new class "CastTransport", which encapsulates the message read and write event loops. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Addressed code review feedback. Created 6 years, 3 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
(Empty)
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
3 // found in the LICENSE file.
4
5 #include "extensions/browser/api/cast_channel/cast_transport.h"
6
7 #include <string>
8
9 #include "base/bind.h"
10 #include "base/format_macros.h"
11 #include "base/numerics/safe_conversions.h"
12 #include "base/strings/stringprintf.h"
13 #include "extensions/browser/api/cast_channel/cast_channel.pb.h"
14 #include "extensions/browser/api/cast_channel/cast_framer.h"
15 #include "extensions/browser/api/cast_channel/cast_message_util.h"
16 #include "extensions/browser/api/cast_channel/logger.h"
17 #include "extensions/browser/api/cast_channel/logger_util.h"
18 #include "net/base/net_errors.h"
19
20 #define VLOG_WITH_CONNECTION(level) \
21 VLOG(level) << "[" << socket_->ip_endpoint().ToString() \
22 << ", auth=" << socket_->channel_auth() << "] "
23
24 namespace extensions {
25 namespace core_api {
26 namespace cast_channel {
27 namespace {
28 proto::ReadState ReadStateToProto(CastTransport::ReadState state) {
29 switch (state) {
30 case CastTransport::READ_STATE_NONE:
31 return proto::READ_STATE_NONE;
32 case CastTransport::READ_STATE_READ:
33 return proto::READ_STATE_READ;
34 case CastTransport::READ_STATE_READ_COMPLETE:
35 return proto::READ_STATE_READ_COMPLETE;
36 case CastTransport::READ_STATE_DO_CALLBACK:
37 return proto::READ_STATE_DO_CALLBACK;
38 case CastTransport::READ_STATE_ERROR:
39 return proto::READ_STATE_ERROR;
40 default:
41 NOTREACHED();
42 return proto::READ_STATE_NONE;
43 }
44 }
45
46 proto::WriteState WriteStateToProto(CastTransport::WriteState state) {
47 switch (state) {
48 case CastTransport::WRITE_STATE_NONE:
49 return proto::WRITE_STATE_NONE;
50 case CastTransport::WRITE_STATE_WRITE:
51 return proto::WRITE_STATE_WRITE;
52 case CastTransport::WRITE_STATE_WRITE_COMPLETE:
53 return proto::WRITE_STATE_WRITE_COMPLETE;
54 case CastTransport::WRITE_STATE_DO_CALLBACK:
55 return proto::WRITE_STATE_DO_CALLBACK;
56 case CastTransport::WRITE_STATE_ERROR:
57 return proto::WRITE_STATE_ERROR;
58 default:
59 NOTREACHED();
60 return proto::WRITE_STATE_NONE;
61 }
62 }
63
64 proto::ErrorState ErrorStateToProto(ChannelError state) {
65 switch (state) {
66 case CHANNEL_ERROR_NONE:
67 return proto::CHANNEL_ERROR_NONE;
68 case CHANNEL_ERROR_CHANNEL_NOT_OPEN:
69 return proto::CHANNEL_ERROR_CHANNEL_NOT_OPEN;
70 case CHANNEL_ERROR_AUTHENTICATION_ERROR:
71 return proto::CHANNEL_ERROR_AUTHENTICATION_ERROR;
72 case CHANNEL_ERROR_CONNECT_ERROR:
73 return proto::CHANNEL_ERROR_CONNECT_ERROR;
74 case CHANNEL_ERROR_SOCKET_ERROR:
75 return proto::CHANNEL_ERROR_SOCKET_ERROR;
76 case CHANNEL_ERROR_TRANSPORT_ERROR:
77 return proto::CHANNEL_ERROR_TRANSPORT_ERROR;
78 case CHANNEL_ERROR_INVALID_MESSAGE:
79 return proto::CHANNEL_ERROR_INVALID_MESSAGE;
80 case CHANNEL_ERROR_INVALID_CHANNEL_ID:
81 return proto::CHANNEL_ERROR_INVALID_CHANNEL_ID;
82 case CHANNEL_ERROR_CONNECT_TIMEOUT:
83 return proto::CHANNEL_ERROR_CONNECT_TIMEOUT;
84 case CHANNEL_ERROR_UNKNOWN:
85 return proto::CHANNEL_ERROR_UNKNOWN;
86 default:
87 NOTREACHED();
88 return proto::CHANNEL_ERROR_NONE;
89 }
90 }
91 } // namespace
92
93 CastTransport::CastTransport(CastSocketInterface* socket,
94 Delegate* read_delegate,
95 scoped_refptr<Logger> logger)
96 : socket_(socket),
97 read_delegate_(read_delegate),
98 write_state_(WRITE_STATE_NONE),
99 read_state_(READ_STATE_NONE),
100 logger_(logger) {
101 DCHECK(socket);
102 DCHECK(read_delegate);
103
104 // Buffer is reused across messages.
105 read_buffer_ = new net::GrowableIOBuffer();
106 read_buffer_->SetCapacity(MessageFramer::MessageHeader::max_message_size());
107 framer_.reset(new MessageFramer(read_buffer_));
108 }
109
110 CastTransport::~CastTransport() {
111 DCHECK(thread_checker_.CalledOnValidThread());
112 FlushWriteQueue();
113 }
114
115 void CastTransport::FlushWriteQueue() {
116 for (; !write_queue_.empty(); write_queue_.pop()) {
117 net::CompletionCallback& callback = write_queue_.front().callback;
118 callback.Run(net::ERR_FAILED);
119 callback.Reset();
120 }
121 }
122
123 void CastTransport::SendMessage(const CastMessage& message,
124 const net::CompletionCallback& callback) {
125 DCHECK(thread_checker_.CalledOnValidThread());
126 std::string serialized_message;
127 if (!MessageFramer::Serialize(message, &serialized_message)) {
128 logger_->LogSocketEventForMessage(socket_->id(),
129 proto::SEND_MESSAGE_FAILED,
130 message.namespace_(),
131 "Error when serializing message.");
132 callback.Run(net::ERR_FAILED);
133 return;
134 }
135 WriteRequest write_request(
136 message.namespace_(), serialized_message, callback);
137
138 write_queue_.push(write_request);
139 logger_->LogSocketEventForMessage(
140 socket_->id(),
141 proto::MESSAGE_ENQUEUED,
142 message.namespace_(),
143 base::StringPrintf("Queue size: %" PRIuS, write_queue_.size()));
144 if (write_state_ == WRITE_STATE_NONE) {
145 SetWriteState(WRITE_STATE_WRITE);
146 OnWriteResult(net::OK);
147 }
148 }
149
150 CastTransport::WriteRequest::WriteRequest(
151 const std::string& namespace_,
152 const std::string& payload,
153 const net::CompletionCallback& callback)
154 : message_namespace(namespace_), callback(callback) {
155 VLOG(2) << "WriteRequest size: " << payload.size();
156 io_buffer = new net::DrainableIOBuffer(new net::StringIOBuffer(payload),
157 payload.size());
158 }
159
160 CastTransport::WriteRequest::~WriteRequest() {
161 }
162
163 void CastTransport::SetReadState(ReadState read_state) {
164 if (read_state_ != read_state) {
165 read_state_ = read_state;
166 logger_->LogSocketReadState(socket_->id(), ReadStateToProto(read_state_));
167 }
168 }
169
170 void CastTransport::SetWriteState(WriteState write_state) {
171 if (write_state_ != write_state) {
172 write_state_ = write_state;
173 logger_->LogSocketWriteState(socket_->id(),
174 WriteStateToProto(write_state_));
175 }
176 }
177
178 void CastTransport::SetErrorState(ChannelError error_state) {
179 if (error_state_ != error_state) {
180 error_state_ = error_state;
181 logger_->LogSocketErrorState(socket_->id(),
182 ErrorStateToProto(error_state_));
183 }
184 }
185
186 void CastTransport::OnWriteResult(int result) {
187 DCHECK(thread_checker_.CalledOnValidThread());
188 VLOG_WITH_CONNECTION(1) << "OnWriteResult queue size: "
189 << write_queue_.size();
190
191 if (write_queue_.empty()) {
192 SetWriteState(WRITE_STATE_NONE);
193 return;
194 }
195
196 // Network operations can either finish synchronously or asynchronously.
197 // This method executes the state machine transitions in a loop so that
198 // write state transitions happen even when network operations finish
199 // synchronously.
200 int rv = result;
201 do {
202 WriteState state = write_state_;
203 write_state_ = WRITE_STATE_NONE;
204 switch (state) {
205 case WRITE_STATE_WRITE:
206 rv = DoWrite();
207 break;
208 case WRITE_STATE_WRITE_COMPLETE:
209 rv = DoWriteComplete(rv);
210 break;
211 case WRITE_STATE_DO_CALLBACK:
212 rv = DoWriteCallback();
213 break;
214 case WRITE_STATE_ERROR:
215 rv = DoWriteError(rv);
216 break;
217 default:
218 NOTREACHED() << "BUG in write flow. Unknown state: " << state;
219 break;
220 }
221 } while (!write_queue_.empty() && rv != net::ERR_IO_PENDING &&
222 write_state_ != WRITE_STATE_NONE);
223
224 // No state change occurred in do-while loop above. This means state has
225 // transitioned to NONE.
226 if (write_state_ == WRITE_STATE_NONE) {
227 logger_->LogSocketWriteState(socket_->id(),
228 WriteStateToProto(write_state_));
229 }
230
231 // If write loop is done because the queue is empty then set write
232 // state to NONE
233 if (write_queue_.empty()) {
234 SetWriteState(WRITE_STATE_NONE);
235 }
236
237 // Write loop is done - if the result is ERR_FAILED then close with error.
238 if (rv == net::ERR_FAILED) {
239 DCHECK_NE(CHANNEL_ERROR_NONE, error_state_);
240 socket_->CloseWithError(error_state_);
241 FlushWriteQueue();
242 }
243 }
244
245 int CastTransport::DoWrite() {
246 DCHECK(!write_queue_.empty());
247 WriteRequest& request = write_queue_.front();
248
249 VLOG_WITH_CONNECTION(2) << "WriteData byte_count = "
250 << request.io_buffer->size() << " bytes_written "
251 << request.io_buffer->BytesConsumed();
252
253 SetWriteState(WRITE_STATE_WRITE_COMPLETE);
254
255 int rv = socket_->Write(
256 request.io_buffer.get(),
257 request.io_buffer->BytesRemaining(),
258 base::Bind(&CastTransport::OnWriteResult, base::Unretained(this)));
259 logger_->LogSocketEventWithRv(socket_->id(), proto::SOCKET_WRITE, rv);
260
261 return rv;
262 }
263
264 int CastTransport::DoWriteComplete(int result) {
265 VLOG_WITH_CONNECTION(2) << "DoWriteComplete result=" << result;
266 DCHECK(!write_queue_.empty());
267 if (result <= 0) { // NOTE that 0 also indicates an error
268 SetErrorState(CHANNEL_ERROR_TRANSPORT_ERROR);
269 SetWriteState(WRITE_STATE_ERROR);
270 return result == 0 ? net::ERR_FAILED : result;
271 }
272
273 // Some bytes were successfully written
274 WriteRequest& request = write_queue_.front();
275 scoped_refptr<net::DrainableIOBuffer> io_buffer = request.io_buffer;
276 io_buffer->DidConsume(result);
277 if (io_buffer->BytesRemaining() == 0) { // Message fully sent
278 SetWriteState(WRITE_STATE_DO_CALLBACK);
279 } else {
280 SetWriteState(WRITE_STATE_WRITE);
281 }
282
283 return net::OK;
284 }
285
286 int CastTransport::DoWriteCallback() {
287 VLOG_WITH_CONNECTION(2) << "DoWriteCallback";
288 DCHECK(!write_queue_.empty());
289
290 SetWriteState(WRITE_STATE_WRITE);
291
292 WriteRequest& request = write_queue_.front();
293 int bytes_consumed = request.io_buffer->BytesConsumed();
294 logger_->LogSocketEventForMessage(
295 socket_->id(),
296 proto::MESSAGE_WRITTEN,
297 request.message_namespace,
298 base::StringPrintf("Bytes: %d", bytes_consumed));
299 request.callback.Run(net::OK);
300 write_queue_.pop();
301 return net::OK;
302 }
303
304 int CastTransport::DoWriteError(int result) {
305 VLOG_WITH_CONNECTION(2) << "DoWriteError result=" << result;
306 DCHECK_NE(CHANNEL_ERROR_NONE, error_state_);
307 DCHECK_LT(result, 0);
308 return net::ERR_FAILED;
309 }
310
311 void CastTransport::StartReadLoop() {
312 DCHECK(thread_checker_.CalledOnValidThread());
313 // Read loop would have already been started if read state is not NONE
314 if (read_state_ == READ_STATE_NONE) {
315 SetReadState(READ_STATE_READ);
316 OnReadResult(net::OK);
317 }
318 }
319
320 void CastTransport::OnReadResult(int result) {
321 DCHECK(thread_checker_.CalledOnValidThread());
322 // Network operations can either finish synchronously or asynchronously.
323 // This method executes the state machine transitions in a loop so that
324 // write state transitions happen even when network operations finish
325 // synchronously.
326 int rv = result;
327 do {
328 ReadState state = read_state_;
329 read_state_ = READ_STATE_NONE;
330
331 switch (state) {
332 case READ_STATE_READ:
333 rv = DoRead();
334 break;
335 case READ_STATE_READ_COMPLETE:
336 rv = DoReadComplete(rv);
337 break;
338 case READ_STATE_DO_CALLBACK:
339 rv = DoReadCallback();
340 break;
341 case READ_STATE_ERROR:
342 rv = DoReadError(rv);
343 DCHECK_EQ(read_state_, READ_STATE_NONE);
344 break;
345 default:
346 NOTREACHED() << "BUG in read flow. Unknown state: " << state;
347 break;
348 }
349 } while (rv != net::ERR_IO_PENDING && read_state_ != READ_STATE_NONE);
350
351 // No state change occurred in do-while loop above. This means state has
352 // transitioned to NONE.
353 if (read_state_ == READ_STATE_NONE) {
354 logger_->LogSocketReadState(socket_->id(), ReadStateToProto(read_state_));
355 }
356
357 if (rv == net::ERR_FAILED) {
358 DCHECK_NE(CHANNEL_ERROR_NONE, error_state_);
359 socket_->CloseWithError(error_state_);
360 FlushWriteQueue();
361 read_delegate_->OnError(
362 socket_, error_state_, logger_->GetLastErrors(socket_->id()));
363 }
364 }
365
366 int CastTransport::DoRead() {
367 VLOG_WITH_CONNECTION(2) << "DoRead";
368 SetReadState(READ_STATE_READ_COMPLETE);
369
370 // Determine how many bytes need to be read.
371 size_t num_bytes_to_read = framer_->BytesRequested();
372
373 // Read up to num_bytes_to_read into |current_read_buffer_|.
374 int rv = socket_->Read(
375 read_buffer_.get(),
376 base::checked_cast<uint32>(num_bytes_to_read),
377 base::Bind(&CastTransport::OnReadResult, base::Unretained(this)));
378
379 return rv;
380 }
381
382 int CastTransport::DoReadComplete(int result) {
383 VLOG_WITH_CONNECTION(2) << "DoReadComplete result = " << result;
384
385 if (result <= 0) {
386 SetErrorState(CHANNEL_ERROR_TRANSPORT_ERROR);
387 SetReadState(READ_STATE_ERROR);
388 return result == 0 ? net::ERR_FAILED : result;
389 }
390
391 size_t message_size;
392 DCHECK(current_message_.get() == NULL);
393 current_message_ = framer_->Ingest(result, &message_size, &error_state_);
394 if (current_message_.get()) {
395 DCHECK_EQ(error_state_, CHANNEL_ERROR_NONE);
396 DCHECK_GT(message_size, static_cast<size_t>(0));
397 logger_->LogSocketEventForMessage(
398 socket_->id(),
399 proto::MESSAGE_READ,
400 current_message_->namespace_(),
401 base::StringPrintf("Message size: %zu", message_size));
402 SetReadState(READ_STATE_DO_CALLBACK);
403 } else if (error_state_ != CHANNEL_ERROR_NONE) {
404 DCHECK(current_message_.get() == NULL);
405 SetErrorState(CHANNEL_ERROR_INVALID_MESSAGE);
406 SetReadState(READ_STATE_ERROR);
407 } else {
408 DCHECK(current_message_.get() == NULL);
409 SetReadState(READ_STATE_READ);
410 }
411 return net::OK;
412 }
413
414 int CastTransport::DoReadCallback() {
415 VLOG_WITH_CONNECTION(2) << "DoReadCallback";
416 SetReadState(READ_STATE_READ);
417 if (!IsCastMessageValid(*current_message_)) {
418 SetReadState(READ_STATE_ERROR);
419 SetErrorState(CHANNEL_ERROR_INVALID_MESSAGE);
420 return net::ERR_INVALID_RESPONSE;
421 }
422 logger_->LogSocketEventForMessage(socket_->id(),
423 proto::NOTIFY_ON_MESSAGE,
424 current_message_->namespace_(),
425 std::string());
426 read_delegate_->OnMessage(socket_, *current_message_);
427 current_message_.reset();
428 return net::OK;
429 }
430
431 int CastTransport::DoReadError(int result) {
432 VLOG_WITH_CONNECTION(2) << "DoReadError";
433 DCHECK_NE(CHANNEL_ERROR_NONE, error_state_);
434 DCHECK_LE(result, 0);
435 return net::ERR_FAILED;
436 }
437 } // namespace cast_channel
438 } // namespace core_api
439 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698