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

Side by Side Diff: components/cronet/android/java/src/org/chromium/net/CronetBidirectionalStream.java

Issue 1412243012: Initial implementation of CronetBidirectionalStream. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: More Helen's and Andrei's comments. Created 4 years, 11 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 2015 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 package org.chromium.net;
6
7 import org.chromium.base.Log;
8 import org.chromium.base.VisibleForTesting;
9 import org.chromium.base.annotations.CalledByNative;
10 import org.chromium.base.annotations.JNINamespace;
11 import org.chromium.base.annotations.NativeClassQualifiedName;
12
13 import java.nio.ByteBuffer;
14 import java.util.AbstractMap;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.concurrent.Executor;
19 import java.util.concurrent.RejectedExecutionException;
20
21 import javax.annotation.concurrent.GuardedBy;
22
23 /**
24 * {@link BidirectionalStream} implementation using Chromium network stack.
25 * All @CalledByNative methods are called on the native network thread
26 * and post tasks with callback calls onto Executor. Upon returning from callbac k, the native
27 * stream is called on Executor thread and posts native tasks to the native netw ork thread.
28 */
29 @JNINamespace("cronet")
30 class CronetBidirectionalStream extends BidirectionalStream {
31 /**
32 * States of BidirectionalStream are tracked in mReadState and mWriteState.
33 * The write state is separated out as it changes independently of the read state.
34 * There is one initial state: State.NOT_STARTED. There is one normal final state:
35 * State.SUCCESS, reached after State.READING_DONE and State.WRITING_DONE. T here are two
36 * exceptional final states: State.CANCELED and State.ERROR, which can be re ached from
37 * any other non-final state.
38 */
39 private enum State {
40 /* Initial state, stream not started. */
41 NOT_STARTED,
42 /* Stream started, request headers are being sent. */
43 STARTED,
44 /* Waiting for {@code read()} to be called. */
45 WAITING_FOR_READ,
46 /* Reading from the remote, {@code onReadCompleted()} callback will be c alled when done. */
47 READING,
48 /* There is no more data to read and stream is half-closed by the remote side. */
49 READING_DONE,
50 /* Stream is canceled. */
51 CANCELED,
52 /* Error has occured, stream is closed. */
53 ERROR,
54 /* Reading and writing are done, and the stream is closed successfully. */
55 SUCCESS,
56 /* Waiting for {@code write()} to be called. */
57 WAITING_FOR_WRITE,
58 /* Writing to the remote, {@code onWriteCompleted()} callback will be ca lled when done. */
59 WRITING,
60 /* Writing the last frame, so {@code State.WRITING_DONE} will be set upo n completion. */
61 WRITING_END_OF_STREAM,
62 /* There is no more data to write and stream is half-closed by the local side. */
63 WRITING_DONE,
64 }
65
66 private final CronetUrlRequestContext mRequestContext;
67 private final Executor mExecutor;
68 private final Callback mCallback;
69 private final String mInitialUrl;
70 private final int mInitialPriority;
71 private final String mInitialMethod;
72 private final String mRequestHeaders[];
73
74 /*
75 * Synchronizes access to mNativeStream, mReadState and mWriteState.
76 */
77 private final Object mNativeStreamLock = new Object();
78
79 /* Native BidirectionalStream object, owned by CronetBidirectionalStream. */
80 @GuardedBy("mNativeStreamLock") private long mNativeStream;
81
82 /**
83 * Read state is tracking reading flow.
84 * / <--- READING <--- \
85 * | |
86 * \ /
87 * NOT_STARTED -> STARTED --> WAITING_FOR_READ -> READING_DONE -> SUCCESS
88 */
89 @GuardedBy("mNativeStreamLock") private State mReadState = State.NOT_STARTED ;
90
91 /**
92 * Write state is tracking writing flow.
93 * / <--- WRITING <--- \
94 * | |
95 * \ /
96 * NOT_STARTED -> STARTED --> WAITING_FOR_WRITE -> WRITING_END_OF_STREAM -> WRITING_DONE ->
97 * SUCCESS
98 */
99 @GuardedBy("mNativeStreamLock") private State mWriteState = State.NOT_STARTE D;
100
101 private UrlResponseInfo mResponseInfo;
102
103 /*
104 * OnReadCompleted callback is repeatedly invoked when each read is complete d, so it
105 * is cached as a member variable.
106 */
107 private OnReadCompletedRunnable mOnReadCompletedTask;
108
109 /*
110 * OnWriteCompleted callback is repeatedly invoked when each write is comple ted, so it
111 * is cached as a member variable.
112 */
113 private OnWriteCompletedRunnable mOnWriteCompletedTask;
114
115 private Runnable mOnDestroyedCallbackForTesting;
116
117 private final class OnReadCompletedRunnable implements Runnable {
118 // Buffer passed back from current invocation of onReadCompleted.
119 ByteBuffer mByteBuffer;
120 // End of stream flag from current invocation of onReadCompleted.
121 boolean mEndOfStream;
122
123 @Override
124 public void run() {
125 try {
126 // Null out mByteBuffer, to pass buffer ownership to callback or release if done.
127 ByteBuffer buffer = mByteBuffer;
128 mByteBuffer = null;
129 synchronized (mNativeStreamLock) {
130 if (isDoneLocked()) {
131 return;
132 }
133 if (mEndOfStream) {
134 mReadState = State.READING_DONE;
135 if (maybeSucceedLocked()) {
136 return;
137 }
138 } else {
139 mReadState = State.WAITING_FOR_READ;
140 }
141 }
142 mCallback.onReadCompleted(CronetBidirectionalStream.this, mRespo nseInfo, buffer);
143 } catch (Exception e) {
144 onCallbackException(e);
145 }
146 }
147 }
148
149 private final class OnWriteCompletedRunnable implements Runnable {
150 // Buffer passed back from current invocation of onWriteCompleted.
151 ByteBuffer mByteBuffer;
152
153 @Override
154 public void run() {
155 try {
156 // Null out mByteBuffer, to pass buffer ownership to callback or release if done.
157 ByteBuffer buffer = mByteBuffer;
158 mByteBuffer = null;
159 synchronized (mNativeStreamLock) {
160 if (isDoneLocked()) {
161 return;
162 }
163 if (mWriteState == State.WRITING_END_OF_STREAM) {
164 mWriteState = State.WRITING_DONE;
165 if (maybeSucceedLocked()) {
166 return;
167 }
168 } else {
169 mWriteState = State.WAITING_FOR_WRITE;
170 }
171 }
172 mCallback.onWriteCompleted(CronetBidirectionalStream.this, mResp onseInfo, buffer);
173 } catch (Exception e) {
174 onCallbackException(e);
175 }
176 }
177 }
178
179 CronetBidirectionalStream(CronetUrlRequestContext requestContext, String url ,
180 @BidirectionalStream.Builder.StreamPriority int priority, Callback c allback,
181 Executor executor, String httpMethod, List<Map.Entry<String, String> > requestHeaders) {
182 mRequestContext = requestContext;
183 mInitialUrl = url;
184 mInitialPriority = convertStreamPriority(priority);
185 mCallback = callback;
186 mExecutor = executor;
187 mInitialMethod = httpMethod;
188 mRequestHeaders = stringsFromHeaderList(requestHeaders);
189 }
190
191 @Override
192 public void start() {
193 synchronized (mNativeStreamLock) {
194 if (mReadState != State.NOT_STARTED) {
195 throw new IllegalStateException("Stream is already started.");
196 }
197 try {
198 mNativeStream = nativeCreateBidirectionalStream(
199 mRequestContext.getUrlRequestContextAdapter());
200 mRequestContext.onRequestStarted();
201 // Non-zero startResult means an argument error.
202 int startResult = nativeStart(mNativeStream, mInitialUrl, mIniti alPriority,
203 mInitialMethod, mRequestHeaders, !doesMethodAllowWriteDa ta(mInitialMethod));
204 if (startResult == -1) {
205 throw new IllegalArgumentException("Invalid http method " + mInitialMethod);
206 }
207 if (startResult > 0) {
208 int headerPos = startResult - 1;
209 throw new IllegalArgumentException("Invalid header "
210 + mRequestHeaders[headerPos] + "=" + mRequestHeaders [headerPos + 1]);
211 }
212 mReadState = mWriteState = State.STARTED;
213 } catch (RuntimeException e) {
214 // If there's an exception, clean up and then throw the
215 // exception to the caller.
216 destroyNativeStreamLocked(false);
217 throw e;
218 }
219 }
220 }
221
222 @Override
223 public void read(ByteBuffer buffer) {
224 synchronized (mNativeStreamLock) {
225 Preconditions.checkHasRemaining(buffer);
226 Preconditions.checkDirect(buffer);
227 if (mReadState != State.WAITING_FOR_READ) {
228 throw new IllegalStateException("Unexpected read attempt.");
229 }
230 if (isDoneLocked()) {
231 return;
232 }
233 mReadState = State.READING;
234 if (!nativeReadData(mNativeStream, buffer, buffer.position(), buffer .limit())) {
235 // Still waiting on read. This is just to have consistent
236 // behavior with the other error cases.
237 mReadState = State.WAITING_FOR_READ;
238 throw new IllegalArgumentException("Unable to call native read") ;
239 }
240 }
241 }
242
243 @Override
244 public void write(ByteBuffer buffer, boolean endOfStream) {
245 synchronized (mNativeStreamLock) {
246 Preconditions.checkDirect(buffer);
247 if (!buffer.hasRemaining() && !endOfStream) {
248 throw new IllegalArgumentException("Empty buffer before end of s tream.");
249 }
250 if (mWriteState != State.WAITING_FOR_WRITE) {
251 throw new IllegalStateException("Unexpected write attempt.");
252 }
253 if (isDoneLocked()) {
254 return;
255 }
256 mWriteState = endOfStream ? State.WRITING_END_OF_STREAM : State.WRIT ING;
257 if (!nativeWriteData(
258 mNativeStream, buffer, buffer.position(), buffer.limit() , endOfStream)) {
259 // Still waiting on write. This is just to have consistent
260 // behavior with the other error cases.
261 mWriteState = State.WAITING_FOR_WRITE;
262 throw new IllegalArgumentException("Unable to call native write" );
263 }
264 }
265 }
266
267 @Override
268 public void ping(PingCallback callback, Executor executor) {
269 // TODO(mef): May be last thing to be implemented on Android.
270 throw new UnsupportedOperationException("ping is not supported yet.");
271 }
272
273 @Override
274 public void windowUpdate(int windowSizeIncrement) {
275 // TODO(mef): Understand the needs and semantics of this method.
276 throw new UnsupportedOperationException("windowUpdate is not supported y et.");
277 }
278
279 @Override
280 public void cancel() {
281 synchronized (mNativeStreamLock) {
282 if (isDoneLocked() || mReadState == State.NOT_STARTED) {
283 return;
284 }
285 mReadState = mWriteState = State.CANCELED;
286 destroyNativeStreamLocked(true);
287 }
288 }
289
290 @Override
291 public boolean isDone() {
292 synchronized (mNativeStreamLock) {
293 return isDoneLocked();
294 }
295 }
296
297 @GuardedBy("mNativeStreamLock")
298 private boolean isDoneLocked() {
299 return mReadState != State.NOT_STARTED && mNativeStream == 0;
300 }
301
302 @SuppressWarnings("unused")
303 @CalledByNative
304 private void onRequestHeadersSent() {
305 postTaskToExecutor(new Runnable() {
306 public void run() {
307 synchronized (mNativeStreamLock) {
308 if (isDoneLocked()) {
309 return;
310 }
311 if (doesMethodAllowWriteData(mInitialMethod)) {
312 mWriteState = State.WAITING_FOR_WRITE;
313 } else {
314 mWriteState = State.WRITING_DONE;
315 }
316 }
317
318 try {
319 mCallback.onRequestHeadersSent(CronetBidirectionalStream.thi s);
320 } catch (Exception e) {
321 onCallbackException(e);
322 }
323 }
324 });
325 }
326
327 /**
328 * Called when the final set of headers, after all redirects,
329 * is received. Can only be called once for each stream.
330 */
331 @SuppressWarnings("unused")
332 @CalledByNative
333 private void onResponseHeadersReceived(int httpStatusCode, String negotiated Protocol,
334 String[] headers, long receivedBytesCount) {
335 try {
336 mResponseInfo = prepareResponseInfoOnNetworkThread(
337 httpStatusCode, negotiatedProtocol, headers, receivedBytesCo unt);
338 } catch (Exception e) {
339 failWithException(new CronetException("Cannot prepare ResponseInfo", null));
340 return;
341 }
342 postTaskToExecutor(new Runnable() {
343 public void run() {
344 synchronized (mNativeStreamLock) {
345 if (isDoneLocked()) {
346 return;
347 }
348 mReadState = State.WAITING_FOR_READ;
349 }
350
351 try {
352 mCallback.onResponseHeadersReceived(
353 CronetBidirectionalStream.this, mResponseInfo);
354 } catch (Exception e) {
355 onCallbackException(e);
356 }
357 }
358 });
359 }
360
361 @SuppressWarnings("unused")
362 @CalledByNative
363 private void onReadCompleted(final ByteBuffer byteBuffer, int bytesRead, int initialPosition,
364 int initialLimit, long receivedBytesCount) {
365 mResponseInfo.setReceivedBytesCount(receivedBytesCount);
366 if (byteBuffer.position() != initialPosition || byteBuffer.limit() != in itialLimit) {
367 failWithException(
368 new CronetException("ByteBuffer modified externally during r ead", null));
369 return;
370 }
371 if (bytesRead < 0 || initialPosition + bytesRead > initialLimit) {
372 failWithException(new CronetException("Invalid number of bytes read" , null));
373 return;
374 }
375 if (mOnReadCompletedTask == null) {
376 mOnReadCompletedTask = new OnReadCompletedRunnable();
377 }
378 byteBuffer.position(initialPosition + bytesRead);
379 mOnReadCompletedTask.mByteBuffer = byteBuffer;
kapishnikov 2016/01/22 23:19:33 Can we add an assertion that "mOnReadCompletedTask
mef 2016/01/25 18:11:25 Done.
380 mOnReadCompletedTask.mEndOfStream = (bytesRead == 0);
381 postTaskToExecutor(mOnReadCompletedTask);
382 }
383
384 @SuppressWarnings("unused")
385 @CalledByNative
386 private void onWriteCompleted(
387 final ByteBuffer byteBuffer, int initialPosition, int initialLimit) {
388 if (byteBuffer.position() != initialPosition || byteBuffer.limit() != in itialLimit) {
389 failWithException(
390 new CronetException("ByteBuffer modified externally during w rite", null));
391 return;
392 }
393 if (mOnWriteCompletedTask == null) {
394 mOnWriteCompletedTask = new OnWriteCompletedRunnable();
395 }
396 // Current implementation always writes the complete buffer.
397 byteBuffer.position(byteBuffer.limit());
398 mOnWriteCompletedTask.mByteBuffer = byteBuffer;
399 postTaskToExecutor(mOnWriteCompletedTask);
400 }
401
402 @SuppressWarnings("unused")
403 @CalledByNative
404 private void onResponseTrailersReceived(String[] trailers) {
405 final UrlResponseInfo.HeaderBlock trailersBlock =
406 new UrlResponseInfo.HeaderBlock(headersListFromStrings(trailers) );
407 postTaskToExecutor(new Runnable() {
408 public void run() {
409 synchronized (mNativeStreamLock) {
410 if (isDoneLocked()) {
411 return;
412 }
413 }
414 try {
415 mCallback.onResponseTrailersReceived(
416 CronetBidirectionalStream.this, mResponseInfo, trail ersBlock);
417 } catch (Exception e) {
418 onCallbackException(e);
419 }
420 }
421 });
422 }
423
424 @SuppressWarnings("unused")
425 @CalledByNative
426 private void onError(final int nativeError, final String errorString, long r eceivedBytesCount) {
427 if (mResponseInfo != null) {
428 mResponseInfo.setReceivedBytesCount(receivedBytesCount);
429 }
430 failWithException(new CronetException(
431 "Exception in BidirectionalStream: " + errorString, nativeError) );
432 }
433
434 /**
435 * Called when request is canceled, no callbacks will be called afterwards.
436 */
437 @SuppressWarnings("unused")
438 @CalledByNative
439 private void onCanceled() {
440 postTaskToExecutor(new Runnable() {
441 public void run() {
442 try {
443 mCallback.onCanceled(CronetBidirectionalStream.this, mRespon seInfo);
444 } catch (Exception e) {
445 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception in onCance led method", e);
446 }
447 }
448 });
449 }
450
451 @VisibleForTesting
452 public void setOnDestroyedCallbackForTesting(Runnable onDestroyedCallbackFor Testing) {
453 mOnDestroyedCallbackForTesting = onDestroyedCallbackForTesting;
454 }
455
456 private static boolean doesMethodAllowWriteData(String methodName) {
457 return !methodName.equals("GET") && !methodName.equals("HEAD");
458 }
459
460 private static ArrayList<Map.Entry<String, String>> headersListFromStrings(S tring[] headers) {
461 ArrayList<Map.Entry<String, String>> headersList = new ArrayList<>(heade rs.length / 2);
462 for (int i = 0; i < headers.length; i += 2) {
463 headersList.add(new AbstractMap.SimpleImmutableEntry<>(headers[i], h eaders[i + 1]));
464 }
465 return headersList;
466 }
467
468 private static String[] stringsFromHeaderList(List<Map.Entry<String, String> > headersList) {
469 String headersArray[] = new String[headersList.size() * 2];
470 int i = 0;
471 for (Map.Entry<String, String> requestHeader : headersList) {
472 headersArray[i++] = requestHeader.getKey();
473 headersArray[i++] = requestHeader.getValue();
474 }
475 return headersArray;
476 }
477
478 private static int convertStreamPriority(
479 @BidirectionalStream.Builder.StreamPriority int priority) {
480 switch (priority) {
481 case Builder.STREAM_PRIORITY_IDLE:
482 return RequestPriority.IDLE;
483 case Builder.STREAM_PRIORITY_LOWEST:
484 return RequestPriority.LOWEST;
485 case Builder.STREAM_PRIORITY_LOW:
486 return RequestPriority.LOW;
487 case Builder.STREAM_PRIORITY_MEDIUM:
488 return RequestPriority.MEDIUM;
489 case Builder.STREAM_PRIORITY_HIGHEST:
490 return RequestPriority.HIGHEST;
491 default:
492 throw new IllegalArgumentException("Invalid stream priority.");
493 }
494 }
495
496 /**
497 * Checks whether reading and writing are done.
498 * @return false if either reading or writing is not done. If both reading a nd writing
499 * are done, then posts cleanup task and returns true.
500 */
501 @GuardedBy("mNativeStreamLock")
502 private boolean maybeSucceedLocked() {
503 if (mReadState != State.READING_DONE || mWriteState != State.WRITING_DON E) {
504 return false;
505 }
506
507 mReadState = mWriteState = State.SUCCESS;
508 postTaskToExecutor(new Runnable() {
509 public void run() {
510 synchronized (mNativeStreamLock) {
511 if (isDoneLocked()) {
512 return;
513 }
514 // Destroy native stream first, so UrlRequestContext could b e shut
515 // down from the listener.
516 destroyNativeStreamLocked(false);
517 }
518 try {
519 mCallback.onSucceeded(CronetBidirectionalStream.this, mRespo nseInfo);
520 } catch (Exception e) {
521 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception in onSucce eded method", e);
522 }
523 }
524 });
525 return true;
526 }
527
528 /**
529 * Posts task to application Executor. Used for callbacks
530 * and other tasks that should not be executed on network thread.
531 */
532 private void postTaskToExecutor(Runnable task) {
533 try {
534 mExecutor.execute(task);
535 } catch (RejectedExecutionException failException) {
536 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception posting task to ex ecutor",
537 failException);
538 // If posting a task throws an exception, then there is no choice
539 // but to destroy the stream without invoking the callback.
540 synchronized (mNativeStreamLock) {
541 mReadState = mWriteState = State.ERROR;
542 destroyNativeStreamLocked(false);
543 }
544 }
545 }
546
547 private UrlResponseInfo prepareResponseInfoOnNetworkThread(int httpStatusCod e,
548 String negotiatedProtocol, String[] headers, long receivedBytesCount ) {
549 synchronized (mNativeStreamLock) {
550 if (mNativeStream == 0) {
551 return null;
552 }
553 }
554
555 ArrayList<String> urlChain = new ArrayList<>();
556 urlChain.add(mInitialUrl);
557
558 UrlResponseInfo responseInfo = new UrlResponseInfo(urlChain, httpStatusC ode, "",
559 headersListFromStrings(headers), false, negotiatedProtocol, null );
560
561 responseInfo.setReceivedBytesCount(receivedBytesCount);
562 return responseInfo;
563 }
564
565 @GuardedBy("mNativeStreamLock")
566 private void destroyNativeStreamLocked(boolean sendOnCanceled) {
567 Log.i(CronetUrlRequestContext.LOG_TAG, "destroyNativeStreamLocked " + th is.toString());
568 if (mNativeStream == 0) {
569 return;
570 }
571 nativeDestroy(mNativeStream, sendOnCanceled);
572 mNativeStream = 0;
573 mRequestContext.onRequestDestroyed();
574 if (mOnDestroyedCallbackForTesting != null) {
575 mOnDestroyedCallbackForTesting.run();
576 }
577 }
578
579 /**
580 * Fails the stream with an exception. Only called on the Executor.
581 */
582 private void failWithExceptionOnExecutor(CronetException e) {
583 // Do not call into listener if request is complete.
584 synchronized (mNativeStreamLock) {
585 if (isDoneLocked()) {
586 return;
587 }
588 mReadState = mWriteState = State.ERROR;
589 destroyNativeStreamLocked(false);
590 }
591 try {
592 mCallback.onFailed(this, mResponseInfo, e);
593 } catch (Exception failException) {
594 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception notifying of faile d request",
595 failException);
596 }
597 }
598
599 /**
600 * If callback method throws an exception, stream gets canceled
601 * and exception is reported via onFailed callback.
602 * Only called on the Executor.
603 */
604 private void onCallbackException(Exception e) {
605 CronetException streamError =
606 new CronetException("CalledByNative method has thrown an excepti on", e);
607 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception in CalledByNative meth od", e);
608 failWithExceptionOnExecutor(streamError);
609 }
610
611 /**
612 * Fails the stream with an exception. Can be called on any thread.
613 */
614 private void failWithException(final CronetException exception) {
615 postTaskToExecutor(new Runnable() {
616 public void run() {
617 failWithExceptionOnExecutor(exception);
618 }
619 });
620 }
621
622 // Native methods are implemented in cronet_bidirectional_stream_adapter.cc.
623 private native long nativeCreateBidirectionalStream(long urlRequestContextAd apter);
624
625 @NativeClassQualifiedName("CronetBidirectionalStreamAdapter")
626 private native int nativeStart(long nativePtr, String url, int priority, Str ing method,
627 String[] headers, boolean endOfStream);
628
629 @NativeClassQualifiedName("CronetBidirectionalStreamAdapter")
630 private native boolean nativeReadData(
631 long nativePtr, ByteBuffer byteBuffer, int position, int limit);
632
633 @NativeClassQualifiedName("CronetBidirectionalStreamAdapter")
634 private native boolean nativeWriteData(
635 long nativePtr, ByteBuffer byteBuffer, int position, int limit, bool ean endOfStream);
636
637 @NativeClassQualifiedName("CronetBidirectionalStreamAdapter")
638 private native void nativeDestroy(long nativePtr, boolean sendOnCanceled);
639 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698