/
RequestBodyConverterImpl.java
336 lines (291 loc) · 13.1 KB
/
RequestBodyConverterImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.net.cronet.okhttptransport;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import androidx.annotation.VisibleForTesting;
import com.google.common.base.Verify;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.net.cronet.okhttptransport.UploadBodyDataBroker.ReadResult;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import org.chromium.net.UploadDataProvider;
import org.chromium.net.UploadDataSink;
final class RequestBodyConverterImpl implements RequestBodyConverter {
private static final long IN_MEMORY_BODY_LENGTH_THRESHOLD_BYTES = 1024 * 1024;
private final InMemoryRequestBodyConverter inMemoryRequestBodyConverter;
private final StreamingRequestBodyConverter streamingRequestBodyConverter;
RequestBodyConverterImpl(
InMemoryRequestBodyConverter inMemoryConverter,
StreamingRequestBodyConverter streamingConverter) {
this.inMemoryRequestBodyConverter = inMemoryConverter;
this.streamingRequestBodyConverter = streamingConverter;
}
static RequestBodyConverterImpl create(ExecutorService bodyReaderExecutor) {
return new RequestBodyConverterImpl(
new InMemoryRequestBodyConverter(), new StreamingRequestBodyConverter(bodyReaderExecutor));
}
@Override
public UploadDataProvider convertRequestBody(RequestBody requestBody, int writeTimeoutMillis)
throws IOException {
long contentLength = requestBody.contentLength();
if (contentLength == -1 || contentLength > IN_MEMORY_BODY_LENGTH_THRESHOLD_BYTES) {
return streamingRequestBodyConverter.convertRequestBody(requestBody, writeTimeoutMillis);
} else {
return inMemoryRequestBodyConverter.convertRequestBody(requestBody, writeTimeoutMillis);
}
}
/**
* Implementation of {@link RequestBodyConverter} that doesn't need to hold the entire request
* body in memory.
*
* <p>
*
* <ol>
* <li>{@link RequestBody#writeTo(BufferedSink)} is invoked on the body, but the sink doesn't
* accept any data
* <li>A call to {@link UploadDataProvider#read(UploadDataSink, ByteBuffer)} unblocks the sink,
* which accepts a part of the body (size depends on the buffer's capacity), then blocks
* again. Buffer is sent to Cronet.
* </ol>
*
* This is repeated until the entire body has been read.
*/
@VisibleForTesting
static final class StreamingRequestBodyConverter implements RequestBodyConverter {
private final ExecutorService readerExecutor;
StreamingRequestBodyConverter(ExecutorService readerExecutor) {
this.readerExecutor = readerExecutor;
}
@Override
public UploadDataProvider convertRequestBody(RequestBody requestBody, int writeTimeoutMillis) {
return new StreamingUploadDataProvider(
requestBody, new UploadBodyDataBroker(), readerExecutor, writeTimeoutMillis);
}
private static class StreamingUploadDataProvider extends UploadDataProvider {
private final RequestBody okHttpRequestBody;
private final UploadBodyDataBroker broker;
private final ListeningExecutorService readTaskExecutor;
private final long writeTimeoutMillis;
/** The future for the task that reads the OkHttp request body in the background. */
private ListenableFuture<?> readTaskFuture;
/** The number of bytes we read from the OkHttp body thus far. */
private long totalBytesReadFromOkHttp;
private StreamingUploadDataProvider(
RequestBody okHttpRequestBody,
UploadBodyDataBroker broker,
ExecutorService readTaskExecutor,
long writeTimeoutMillis) {
this.okHttpRequestBody = okHttpRequestBody;
this.broker = broker;
if (readTaskExecutor instanceof ListeningExecutorService) {
this.readTaskExecutor = (ListeningExecutorService) readTaskExecutor;
} else {
this.readTaskExecutor = MoreExecutors.listeningDecorator(readTaskExecutor);
}
// So that we don't have to special case infinity. Int.MAX_VALUE is ~infinity for all
// practical use cases.
this.writeTimeoutMillis = writeTimeoutMillis == 0 ? Integer.MAX_VALUE : writeTimeoutMillis;
}
@Override
public long getLength() throws IOException {
return okHttpRequestBody.contentLength();
}
@Override
public void read(UploadDataSink uploadDataSink, ByteBuffer byteBuffer) throws IOException {
ensureReadTaskStarted();
if (getLength() == -1) {
readUnknownBodyLength(uploadDataSink, byteBuffer);
} else {
readKnownBodyLength(uploadDataSink, byteBuffer);
}
}
private void readKnownBodyLength(UploadDataSink uploadDataSink, ByteBuffer byteBuffer)
throws IOException {
try {
UploadBodyDataBroker.ReadResult readResult = readFromOkHttp(byteBuffer);
if (totalBytesReadFromOkHttp > getLength()) {
throw prepareBodyTooLongException(getLength(), totalBytesReadFromOkHttp);
}
if (totalBytesReadFromOkHttp < getLength()) {
switch (readResult) {
case SUCCESS:
uploadDataSink.onReadSucceeded(false);
break;
case END_OF_BODY:
throw new IOException("The source has been exhausted but we expected more data!");
}
return;
}
// Else we're handling what's supposed to be the last chunk
handleLastBodyRead(uploadDataSink, byteBuffer);
} catch (TimeoutException | ExecutionException e) {
readTaskFuture.cancel(true);
uploadDataSink.onReadError(new IOException(e));
}
}
/**
* The last body read is special for fixed length bodies - if Cronet receives exactly the
* right amount of data it won't ask for more, even if there is more data in the stream. As a
* result, when we read the advertised number of bytes, we need to make sure that the stream
* is indeed finished.
*/
private void handleLastBodyRead(UploadDataSink uploadDataSink, ByteBuffer filledByteBuffer)
throws IOException, TimeoutException, ExecutionException {
// We reuse the same buffer for the END_OF_DATA read (it should be non-destructive and if
// it overwrites what's in there we don't mind as that's an error anyway). We just need
// to make sure we restore the original position afterwards. We don't use mark() / reset()
// as the mark position can be invalidated by limit manipulation.
int bufferPosition = filledByteBuffer.position();
filledByteBuffer.position(0);
UploadBodyDataBroker.ReadResult readResult = readFromOkHttp(filledByteBuffer);
if (!readResult.equals(ReadResult.END_OF_BODY)) {
throw prepareBodyTooLongException(getLength(), totalBytesReadFromOkHttp);
}
Verify.verify(
filledByteBuffer.position() == 0,
"END_OF_BODY reads shouldn't write anything to the buffer");
// revert the position change
filledByteBuffer.position(bufferPosition);
uploadDataSink.onReadSucceeded(false);
}
private void readUnknownBodyLength(UploadDataSink uploadDataSink, ByteBuffer byteBuffer) {
try {
UploadBodyDataBroker.ReadResult readResult = readFromOkHttp(byteBuffer);
uploadDataSink.onReadSucceeded(readResult.equals(ReadResult.END_OF_BODY));
} catch (TimeoutException | ExecutionException e) {
readTaskFuture.cancel(true);
uploadDataSink.onReadError(new IOException(e));
}
}
private void ensureReadTaskStarted() {
// We don't expect concurrent calls so a simple flag is sufficient
if (readTaskFuture == null) {
readTaskFuture =
readTaskExecutor.submit(
(Callable<Void>)
() -> {
BufferedSink bufferedSink = Okio.buffer(broker);
okHttpRequestBody.writeTo(bufferedSink);
bufferedSink.flush();
broker.handleEndOfStreamSignal();
return null;
});
Futures.addCallback(
readTaskFuture,
new FutureCallback<Object>() {
@Override
public void onSuccess(Object result) {}
@Override
public void onFailure(Throwable t) {
broker.setBackgroundReadError(t);
}
},
MoreExecutors.directExecutor());
}
}
private ReadResult readFromOkHttp(ByteBuffer byteBuffer)
throws TimeoutException, ExecutionException {
int positionBeforeRead = byteBuffer.position();
UploadBodyDataBroker.ReadResult readResult =
Uninterruptibles.getUninterruptibly(
broker.enqueueBodyRead(byteBuffer), writeTimeoutMillis, MILLISECONDS);
int bytesRead = byteBuffer.position() - positionBeforeRead;
totalBytesReadFromOkHttp += bytesRead;
return readResult;
}
private static IOException prepareBodyTooLongException(
long expectedLength, long minActualLength) {
return new IOException(
"Expected " + expectedLength + " bytes but got at least " + minActualLength);
}
@Override
public void rewind(UploadDataSink uploadDataSink) {
// TODO(danstahr): OkHttp 4 can use isOneShot flag here and rewind safely.
uploadDataSink.onRewindError(new UnsupportedOperationException("Rewind is not supported!"));
}
}
}
/**
* Converts OkHttp's {@link RequestBody} to Cronet's {@link UploadDataProvider} by materializing
* the body in memory first.
*
* <p>This strategy shouldn't be used for large requests (and for requests with uncapped length)
* to avoid OOM issues.
*/
@VisibleForTesting
static final class InMemoryRequestBodyConverter implements RequestBodyConverter {
@Override
public UploadDataProvider convertRequestBody(RequestBody requestBody, int writeTimeoutMillis)
throws IOException {
// content length is immutable by contract
long length = requestBody.contentLength();
if (length < 0 || length > IN_MEMORY_BODY_LENGTH_THRESHOLD_BYTES) {
throw new IOException(
"Expected definite length less than "
+ IN_MEMORY_BODY_LENGTH_THRESHOLD_BYTES
+ "but got "
+ length);
}
return new UploadDataProvider() {
private volatile boolean isMaterialized = false;
private final Buffer materializedBody = new Buffer();
@Override
public long getLength() {
return length;
}
@Override
public void read(UploadDataSink uploadDataSink, ByteBuffer byteBuffer) throws IOException {
// We're not expecting any concurrent calls here so a simple flag should be sufficient.
if (!isMaterialized) {
requestBody.writeTo(materializedBody);
materializedBody.flush();
isMaterialized = true;
long reportedLength = getLength();
long actualLength = materializedBody.size();
if (actualLength != reportedLength) {
throw new IOException(
"Expected " + reportedLength + " bytes but got " + actualLength);
}
}
if (materializedBody.read(byteBuffer) == -1) {
// This should never happen - for known body length we shouldn't be called at all
// if there's no more data to read.
throw new IllegalStateException("The source has been exhausted but we expected more!");
}
uploadDataSink.onReadSucceeded(false);
}
@Override
public void rewind(UploadDataSink uploadDataSink) {
// TODO(danstahr): OkHttp 4 can use isOneShot flag here and rewind safely.
uploadDataSink.onRewindError(new UnsupportedOperationException());
}
};
}
}
}