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

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

Powered by Google App Engine
This is Rietveld 408576698