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

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: Added unit tests to CL 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(CastSocketPlaceholder* 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 FlushPendingCallbacks();
113 }
114
115 void CastTransport::FlushPendingCallbacks() {
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 DoWriteLoop(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::DoWriteLoop(int result) {
187 DCHECK(thread_checker_.CalledOnValidThread());
188 VLOG_WITH_CONNECTION(1) << "DoWriteLoop queue size: " << write_queue_.size();
189
190 if (write_queue_.empty()) {
191 SetWriteState(WRITE_STATE_NONE);
192 return;
193 }
194
195 // Network operations can either finish synchronously or asynchronously.
196 // This method executes the state machine transitions in a loop so that
197 // write state transitions happen even when network operations finish
198 // synchronously.
199 int rv = result;
200 do {
201 WriteState state = write_state_;
202 write_state_ = WRITE_STATE_NONE;
203 switch (state) {
204 case WRITE_STATE_WRITE:
205 rv = DoWrite();
206 break;
207 case WRITE_STATE_WRITE_COMPLETE:
208 rv = DoWriteComplete(rv);
209 break;
210 case WRITE_STATE_DO_CALLBACK:
211 rv = DoWriteCallback();
212 break;
213 case WRITE_STATE_ERROR:
214 rv = DoWriteError(rv);
215 break;
216 default:
217 NOTREACHED() << "BUG in write flow. Unknown state: " << state;
218 break;
219 }
220 } while (!write_queue_.empty() && rv != net::ERR_IO_PENDING &&
221 write_state_ != WRITE_STATE_NONE);
222
223 // No state change occurred in do-while loop above. This means state has
224 // transitioned to NONE.
225 if (write_state_ == WRITE_STATE_NONE) {
226 logger_->LogSocketWriteState(socket_->id(),
227 WriteStateToProto(write_state_));
228 }
229
230 // If write loop is done because the queue is empty then set write
231 // state to NONE
232 if (write_queue_.empty()) {
233 SetWriteState(WRITE_STATE_NONE);
234 }
235
236 // Write loop is done - if the result is ERR_FAILED then close with error.
237 if (rv == net::ERR_FAILED) {
238 DCHECK_NE(CHANNEL_ERROR_NONE, error_state_);
239 FlushPendingCallbacks();
240 }
241 }
242
243 int CastTransport::DoWrite() {
244 DCHECK(!write_queue_.empty());
245 WriteRequest& request = write_queue_.front();
246
247 VLOG_WITH_CONNECTION(2) << "WriteData byte_count = "
248 << request.io_buffer->size() << " bytes_written "
249 << request.io_buffer->BytesConsumed();
250
251 SetWriteState(WRITE_STATE_WRITE_COMPLETE);
252
253 int rv = socket_->Write(
254 request.io_buffer.get(),
255 request.io_buffer->BytesRemaining(),
256 base::Bind(&CastTransport::DoWriteLoop, base::Unretained(this)));
257 logger_->LogSocketEventWithRv(socket_->id(), proto::SOCKET_WRITE, rv);
258
259 return rv;
260 }
261
262 int CastTransport::DoWriteComplete(int result) {
263 VLOG_WITH_CONNECTION(2) << "DoWriteComplete result=" << result;
264 DCHECK(!write_queue_.empty());
265 if (result <= 0) { // NOTE that 0 also indicates an error
266 SetErrorState(CHANNEL_ERROR_TRANSPORT_ERROR);
267 SetWriteState(WRITE_STATE_ERROR);
268 return result == 0 ? net::ERR_FAILED : result;
269 }
270
271 // Some bytes were successfully written
272 WriteRequest& request = write_queue_.front();
273 scoped_refptr<net::DrainableIOBuffer> io_buffer = request.io_buffer;
274 io_buffer->DidConsume(result);
275 if (io_buffer->BytesRemaining() == 0) { // Message fully sent
276 SetWriteState(WRITE_STATE_DO_CALLBACK);
277 } else {
278 SetWriteState(WRITE_STATE_WRITE);
279 }
280
281 return net::OK;
282 }
283
284 int CastTransport::DoWriteCallback() {
285 VLOG_WITH_CONNECTION(2) << "DoWriteCallback";
286 DCHECK(!write_queue_.empty());
287
288 SetWriteState(WRITE_STATE_WRITE);
289
290 WriteRequest& request = write_queue_.front();
291 int bytes_consumed = request.io_buffer->BytesConsumed();
292 logger_->LogSocketEventForMessage(
293 socket_->id(),
294 proto::MESSAGE_WRITTEN,
295 request.message_namespace,
296 base::StringPrintf("Bytes: %d", bytes_consumed));
297 request.callback.Run(net::OK);
298 write_queue_.pop();
299 return net::OK;
300 }
301
302 int CastTransport::DoWriteError(int result) {
303 VLOG_WITH_CONNECTION(2) << "DoWriteError result=" << result;
304 DCHECK_NE(CHANNEL_ERROR_NONE, error_state_);
305 DCHECK_LT(result, 0);
306 return net::ERR_FAILED;
307 }
308
309 void CastTransport::StartReadLoop() {
310 DCHECK(thread_checker_.CalledOnValidThread());
311 // Read loop would have already been started if read state is not NONE
312 if (read_state_ == READ_STATE_NONE) {
313 SetReadState(READ_STATE_READ);
314 DoReadLoop(net::OK);
315 }
316 }
317
318 void CastTransport::DoReadLoop(int result) {
319 DCHECK(thread_checker_.CalledOnValidThread());
320 // Network operations can either finish synchronously or asynchronously.
321 // This method executes the state machine transitions in a loop so that
322 // write state transitions happen even when network operations finish
323 // synchronously.
324 int rv = result;
325 do {
326 ReadState state = read_state_;
327 read_state_ = READ_STATE_NONE;
328
329 switch (state) {
330 case READ_STATE_READ:
331 rv = DoRead();
332 break;
333 case READ_STATE_READ_COMPLETE:
334 rv = DoReadComplete(rv);
335 break;
336 case READ_STATE_DO_CALLBACK:
337 rv = DoReadCallback();
338 break;
339 case READ_STATE_ERROR:
340 rv = DoReadError(rv);
341 DCHECK_EQ(read_state_, READ_STATE_NONE);
342 break;
343 default:
344 NOTREACHED() << "BUG in read flow. Unknown state: " << state;
345 break;
346 }
347 } while (rv != net::ERR_IO_PENDING && read_state_ != READ_STATE_NONE);
348
349 // No state change occurred in do-while loop above. This means state has
350 // transitioned to NONE.
351 if (read_state_ == READ_STATE_NONE) {
352 logger_->LogSocketReadState(socket_->id(), ReadStateToProto(read_state_));
353 }
354
355 if (rv == net::ERR_FAILED) {
356 DCHECK_NE(CHANNEL_ERROR_NONE, error_state_);
357 FlushPendingCallbacks();
358 read_delegate_->OnError(
359 socket_, error_state_, logger_->GetLastErrors(socket_->id()));
360 }
361 }
362
363 int CastTransport::DoRead() {
364 VLOG_WITH_CONNECTION(2) << "DoRead";
365 SetReadState(READ_STATE_READ_COMPLETE);
366
367 // Determine how many bytes need to be read.
368 size_t num_bytes_to_read = framer_->BytesRequested();
369
370 // Read up to num_bytes_to_read into |current_read_buffer_|.
371 int rv = socket_->Read(
372 read_buffer_.get(),
373 base::checked_cast<uint32>(num_bytes_to_read),
374 base::Bind(&CastTransport::DoReadLoop, base::Unretained(this)));
375
376 return rv;
377 }
378
379 int CastTransport::DoReadComplete(int result) {
380 VLOG_WITH_CONNECTION(2) << "DoReadComplete result = " << result;
381
382 if (result <= 0) {
383 SetErrorState(CHANNEL_ERROR_TRANSPORT_ERROR);
384 SetReadState(READ_STATE_ERROR);
385 return result == 0 ? net::ERR_FAILED : result;
386 }
387
388 size_t message_size;
389 DCHECK(current_message_.get() == NULL);
390 current_message_ = framer_->Ingest(result, &message_size, &error_state_);
391 if (current_message_.get()) {
392 DCHECK_EQ(error_state_, CHANNEL_ERROR_NONE);
393 DCHECK_GT(message_size, static_cast<size_t>(0));
394 logger_->LogSocketEventForMessage(
395 socket_->id(),
396 proto::MESSAGE_READ,
397 current_message_->namespace_(),
398 base::StringPrintf("Message size: %zu", message_size));
399 SetReadState(READ_STATE_DO_CALLBACK);
400 } else if (error_state_ != CHANNEL_ERROR_NONE) {
401 DCHECK(current_message_.get() == NULL);
402 SetErrorState(CHANNEL_ERROR_INVALID_MESSAGE);
403 SetReadState(READ_STATE_ERROR);
404 } else {
405 DCHECK(current_message_.get() == NULL);
406 SetReadState(READ_STATE_READ);
407 }
408 return net::OK;
409 }
410
411 int CastTransport::DoReadCallback() {
412 VLOG_WITH_CONNECTION(2) << "DoReadCallback";
413 SetReadState(READ_STATE_READ);
414 if (!ValidateCastMessage(*current_message_)) {
415 SetReadState(READ_STATE_ERROR);
416 SetErrorState(CHANNEL_ERROR_INVALID_MESSAGE);
417 return net::ERR_INVALID_RESPONSE;
418 }
419 logger_->LogSocketEventForMessage(socket_->id(),
420 proto::NOTIFY_ON_MESSAGE,
421 current_message_->namespace_(),
422 std::string());
423 read_delegate_->OnMessage(socket_, *current_message_);
424 current_message_.reset();
425 return net::OK;
426 }
427
428 int CastTransport::DoReadError(int result) {
429 VLOG_WITH_CONNECTION(2) << "DoReadError";
430 DCHECK_NE(CHANNEL_ERROR_NONE, error_state_);
431 DCHECK_LE(result, 0);
432 return net::ERR_FAILED;
433 }
434 } // namespace cast_channel
435 } // namespace core_api
436 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698