Skip to content

Commit 6d89325

Browse files
committed
feat(gax): add rewindable stream buffer for chunk recovery
Introduce RewindableStreamBuffer managing a single-chunk buffer over an InputStream, supporting forward compaction and topping up upon recovery realignment without mark()/reset(). Enforces boundaries by throwing FailedPreconditionException when a server offset is below the base offset or beyond the current buffer window. Use payloadLength in ChunkUploadRequest to avoid allocating temporary byte arrays for full-sized chunks while reusing a single backing array.
1 parent d186a68 commit 6d89325

7 files changed

Lines changed: 616 additions & 33 deletions

File tree

sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/ResumableUploadChunkCallable.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
import java.io.ByteArrayInputStream;
4646
import java.io.InputStream;
4747
import java.nio.charset.StandardCharsets;
48+
import java.util.Arrays;
4849
import java.util.Collections;
4950
import java.util.List;
5051
import java.util.Map;
@@ -81,7 +82,12 @@ public Map<String, List<String>> getQueryParamNames(ChunkUploadRequest request)
8182

8283
@Override
8384
public byte[] getBinaryRequestBody(ChunkUploadRequest request) {
84-
return request.getPayload();
85+
int length = request.getPayloadLength();
86+
byte[] payload = request.getPayload();
87+
if (length == payload.length) {
88+
return payload;
89+
}
90+
return Arrays.copyOf(payload, length);
8591
}
8692

8793
@Override
@@ -110,7 +116,7 @@ private ResumableUploadChunkCallable(
110116
public ApiFuture<ChunkUploadResponse<ResponseT>> futureCall(
111117
ChunkUploadRequest request, @Nullable ApiCallContext inputContext) {
112118
Preconditions.checkNotNull(request);
113-
boolean isPayloadEmpty = request.getPayload().length == 0;
119+
boolean isPayloadEmpty = request.getPayloadLength() == 0;
114120
String command;
115121
if (request.isFinal()) {
116122
command = !isPayloadEmpty ? COMMAND_UPLOAD_FINALIZE : COMMAND_FINALIZE;

sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/resumable/ChunkUploadRequest.java

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import com.google.api.core.BetaApi;
3333
import com.google.api.core.InternalApi;
3434
import com.google.auto.value.AutoValue;
35+
import com.google.common.base.Preconditions;
3536
import org.jspecify.annotations.NullMarked;
3637

3738
/** Request value object for uploading a chunk to an active resumable upload session. */
@@ -48,6 +49,9 @@ public abstract class ChunkUploadRequest {
4849
@SuppressWarnings("mutable")
4950
public abstract byte[] getPayload();
5051

52+
/** The number of bytes within {@link #getPayload()} to upload. */
53+
public abstract int getPayloadLength();
54+
5155
/** The byte offset of this chunk in the overall stream. */
5256
public abstract long getOffset();
5357

@@ -56,8 +60,12 @@ public abstract class ChunkUploadRequest {
5660

5761
public abstract Builder toBuilder();
5862

63+
private static final int UNSET_PAYLOAD_LENGTH = Integer.MIN_VALUE;
64+
5965
public static Builder newBuilder() {
60-
return new AutoValue_ChunkUploadRequest.Builder().setFinal(false);
66+
return new AutoValue_ChunkUploadRequest.Builder()
67+
.setFinal(false)
68+
.setPayloadLength(UNSET_PAYLOAD_LENGTH);
6169
}
6270

6371
@AutoValue.Builder
@@ -66,10 +74,29 @@ public abstract static class Builder {
6674

6775
public abstract Builder setPayload(byte[] payload);
6876

77+
public abstract Builder setPayloadLength(int payloadLength);
78+
6979
public abstract Builder setOffset(long offset);
7080

7181
public abstract Builder setFinal(boolean isFinal);
7282

73-
public abstract ChunkUploadRequest build();
83+
abstract byte[] getPayload();
84+
85+
abstract int getPayloadLength();
86+
87+
abstract ChunkUploadRequest autoBuild();
88+
89+
public ChunkUploadRequest build() {
90+
if (getPayloadLength() == UNSET_PAYLOAD_LENGTH) {
91+
setPayloadLength(getPayload().length);
92+
}
93+
ChunkUploadRequest request = autoBuild();
94+
Preconditions.checkArgument(
95+
request.getPayloadLength() >= 0, "payloadLength must be non-negative");
96+
Preconditions.checkArgument(
97+
request.getPayloadLength() <= request.getPayload().length,
98+
"payloadLength exceeds payload array length");
99+
return request;
100+
}
74101
}
75102
}

sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ResumableUploadChunkCoordinator.java

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,11 @@
4444
import com.google.api.gax.retrying.RetrySettings;
4545
import com.google.api.gax.retrying.RetryingFuture;
4646
import com.google.api.gax.retrying.ScheduledRetryingExecutor;
47-
import com.google.common.io.ByteStreams;
4847
import com.google.common.util.concurrent.MoreExecutors;
4948
import com.google.errorprone.annotations.concurrent.GuardedBy;
5049
import java.io.IOException;
5150
import java.io.InputStream;
5251
import java.time.Duration;
53-
import java.util.Arrays;
5452
import java.util.concurrent.CancellationException;
5553
import org.jspecify.annotations.NullMarked;
5654
import org.jspecify.annotations.Nullable;
@@ -75,22 +73,20 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
7573
.setMaxAttempts(5)
7674
.build();
7775

78-
private static final byte[] EMPTY_PAYLOAD = new byte[0];
79-
8076
private final Object lock = new Object();
8177

8278
private final SettableApiFuture<ResponseT> result;
8379
private final ApiFuture<ResumableUploadSession> startFuture;
8480
private final UnaryCallable<ChunkUploadRequest, ChunkUploadResponse<ResponseT>>
8581
uploadChunkCallable;
8682
private final InputStream payload;
87-
private final byte[] buffer;
8883
private final int chunkSize;
8984
private final ApiCallContext callContext;
9085
private final ClientContext clientContext;
9186
private final RetrySettings chunkRetrySettings;
9287

9388
private volatile @Nullable String uploadSessionUrl;
89+
private volatile @Nullable RewindableStreamBuffer buffer;
9490

9591
@GuardedBy("lock")
9692
private boolean done;
@@ -120,7 +116,6 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
120116
this.callContext = checkNotNull(callContext, "callContext must not be null");
121117
this.clientContext = checkNotNull(clientContext, "clientContext must not be null");
122118
this.chunkRetrySettings = DEFAULT_CHUNK_RETRY_SETTINGS;
123-
this.buffer = new byte[chunkSize];
124119
synchronized (lock) {
125120
this.inFlightFuture = startFuture;
126121
}
@@ -138,6 +133,7 @@ public void onSuccess(ResumableUploadSession session) {
138133
}
139134
}
140135
uploadSessionUrl = session.getUploadUrl();
136+
buffer = new RewindableStreamBuffer(payload, chunkSize, uploadSessionUrl);
141137
transmitChunk(0L);
142138
}
143139

@@ -227,39 +223,42 @@ private void transmitChunk(long currentOffset) {
227223
}
228224
}
229225

230-
int bytesRead;
226+
String url = uploadSessionUrl;
227+
if (url == null) {
228+
finish(null, new IllegalStateException("Upload session URL not available"));
229+
return;
230+
}
231+
232+
RewindableStreamBuffer streamBuffer = buffer;
233+
if (streamBuffer == null) {
234+
finish(null, new IllegalStateException("Upload buffer not initialized"));
235+
return;
236+
}
237+
231238
try {
232-
bytesRead = ByteStreams.read(payload, buffer, 0, chunkSize);
239+
streamBuffer.fill(currentOffset);
233240
} catch (IOException e) {
234241
finish(null, e);
235242
return;
236243
}
237244

238-
boolean isFinal = bytesRead < chunkSize;
239-
byte[] chunkPayload;
240-
if (bytesRead == chunkSize) {
241-
chunkPayload = buffer;
242-
} else if (bytesRead == 0) {
243-
chunkPayload = EMPTY_PAYLOAD;
245+
UploadCommand command;
246+
if (streamBuffer.isFinal()) {
247+
command =
248+
streamBuffer.isEmpty() ? UploadCommand.FINALIZE : UploadCommand.UPLOAD_FINALIZE;
244249
} else {
245-
chunkPayload = Arrays.copyOf(buffer, bytesRead);
246-
}
247-
248-
String url = uploadSessionUrl;
249-
if (url == null) {
250-
finish(null, new IllegalStateException("Upload session URL not available"));
251-
return;
250+
command = UploadCommand.UPLOAD;
252251
}
253252

254253
ChunkUploadRequest chunkRequest =
255254
ChunkUploadRequest.newBuilder()
256255
.setUploadUrl(url)
257-
.setPayload(chunkPayload)
258-
.setOffset(currentOffset)
259-
.setFinal(isFinal)
256+
.setPayload(streamBuffer.getBuffer())
257+
.setPayloadLength(streamBuffer.getPayloadLength())
258+
.setOffset(streamBuffer.getBufferBaseOffset())
259+
.setFinal(streamBuffer.isFinal())
260260
.build();
261261

262-
UploadCommand command = isFinal ? UploadCommand.UPLOAD_FINALIZE : UploadCommand.UPLOAD;
263262
ChunkAttemptCallable<ResponseT> attemptCallable =
264263
new ChunkAttemptCallable<>(
265264
uploadChunkCallable, chunkRequest, callContext, command);
@@ -277,7 +276,8 @@ private void transmitChunk(long currentOffset) {
277276
attemptCallable.setRetryingFuture(retryingFuture);
278277
setInFlightFuture(retryingFuture);
279278

280-
long chunkLength = chunkPayload.length;
279+
long chunkLength = chunkRequest.getPayloadLength();
280+
boolean isFinal = chunkRequest.isFinal();
281281
ApiFutures.addCallback(
282282
retryingFuture,
283283
new ApiFutureCallback<ChunkUploadResponse<ResponseT>>() {
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
/*
2+
* Copyright 2026 Google LLC
3+
*
4+
* Redistribution and use in source and binary forms, with or without
5+
* modification, are permitted provided that the following conditions are
6+
* met:
7+
*
8+
* * Redistributions of source code must retain the above copyright
9+
* notice, this list of conditions and the following disclaimer.
10+
* * Redistributions in binary form must reproduce the above
11+
* copyright notice, this list of conditions and the following disclaimer
12+
* in the documentation and/or other materials provided with the
13+
* distribution.
14+
* * Neither the name of Google LLC nor the names of its
15+
* contributors may be used to endorse or promote products derived from
16+
* this software without specific prior written permission.
17+
*
18+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19+
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20+
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21+
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22+
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23+
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24+
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25+
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26+
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28+
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29+
*/
30+
package com.google.api.gax.rpc;
31+
32+
import static com.google.common.base.Preconditions.checkArgument;
33+
import static com.google.common.base.Preconditions.checkNotNull;
34+
35+
import com.google.common.io.ByteStreams;
36+
import java.io.IOException;
37+
import java.io.InputStream;
38+
import org.jspecify.annotations.NullMarked;
39+
import org.jspecify.annotations.Nullable;
40+
41+
/**
42+
* Manages a single-chunk buffer over an {@link InputStream} for resumable uploads.
43+
*
44+
* <p>The buffer holds at most one chunk of data in a reused backing array. It supports forward
45+
* compaction and topping up upon recovery realignment, and enforces the boundary condition that
46+
* requests to rewind before the buffer's base offset fail with an unrecoverable {@link
47+
* FailedPreconditionException}.
48+
*/
49+
@NullMarked
50+
final class RewindableStreamBuffer {
51+
52+
private final InputStream inputStream;
53+
private final int chunkSize;
54+
private final String uploadUrl;
55+
private final byte[] buffer;
56+
57+
private long bufferBaseOffset;
58+
private int payloadLength;
59+
private boolean isFinal;
60+
private boolean streamExhausted;
61+
62+
RewindableStreamBuffer(InputStream inputStream, int chunkSize, String uploadUrl) {
63+
this.inputStream = checkNotNull(inputStream, "inputStream must not be null");
64+
checkArgument(chunkSize > 0, "chunkSize must be > 0");
65+
this.chunkSize = chunkSize;
66+
this.uploadUrl = checkNotNull(uploadUrl, "uploadUrl must not be null");
67+
this.buffer = new byte[chunkSize];
68+
this.bufferBaseOffset = 0L;
69+
this.payloadLength = 0;
70+
this.isFinal = false;
71+
this.streamExhausted = false;
72+
}
73+
74+
/**
75+
* Advances the buffer from the stream starting at {@code targetOffset}, reading up to chunk size.
76+
*
77+
* @param targetOffset the absolute stream offset corresponding to the start of this chunk
78+
* @throws IOException if reading from the stream fails
79+
*/
80+
void fill(long targetOffset) throws IOException {
81+
this.bufferBaseOffset = targetOffset;
82+
this.payloadLength = ByteStreams.read(inputStream, buffer, 0, chunkSize);
83+
this.isFinal = (payloadLength < chunkSize);
84+
if (this.isFinal) {
85+
this.streamExhausted = true;
86+
}
87+
}
88+
89+
/**
90+
* Realigns the buffer window to {@code committedOffset}.
91+
*
92+
* <p>Compacts forward within the existing buffer to discard already-committed bytes, and then
93+
* tops up the buffer to capacity from the underlying stream.
94+
*
95+
* @param committedOffset the server's committed byte offset
96+
* @throws FailedPreconditionException if {@code committedOffset} is below the buffer's base
97+
* offset or beyond the current buffer window
98+
* @throws IOException if reading from the stream fails
99+
*/
100+
void realignTo(long committedOffset) throws IOException {
101+
if (committedOffset < bufferBaseOffset) {
102+
throw protocolViolation(
103+
String.format(
104+
"Server committed offset %d is below buffer base offset %d for upload URL %s; cannot"
105+
+ " rewind stream before buffer base",
106+
committedOffset, bufferBaseOffset, uploadUrl));
107+
}
108+
109+
if (committedOffset > bufferBaseOffset + payloadLength) {
110+
throw protocolViolation(
111+
String.format(
112+
"Server committed offset %d is beyond current buffer window [%d, %d] for upload URL"
113+
+ " %s",
114+
committedOffset, bufferBaseOffset, bufferBaseOffset + payloadLength, uploadUrl));
115+
}
116+
117+
int committedWithinBuffer = (int) (committedOffset - bufferBaseOffset);
118+
int remainingBytes = payloadLength - committedWithinBuffer;
119+
120+
if (remainingBytes > 0 && committedWithinBuffer > 0) {
121+
System.arraycopy(buffer, committedWithinBuffer, buffer, 0, remainingBytes);
122+
}
123+
124+
this.bufferBaseOffset = committedOffset;
125+
this.payloadLength = remainingBytes;
126+
127+
if (!streamExhausted && payloadLength < chunkSize) {
128+
int space = chunkSize - payloadLength;
129+
int additionalRead = ByteStreams.read(inputStream, buffer, payloadLength, space);
130+
payloadLength += additionalRead;
131+
if (additionalRead < space) {
132+
streamExhausted = true;
133+
}
134+
}
135+
136+
this.isFinal = streamExhausted;
137+
}
138+
139+
byte[] getBuffer() {
140+
return buffer;
141+
}
142+
143+
int getPayloadLength() {
144+
return payloadLength;
145+
}
146+
147+
long getBufferBaseOffset() {
148+
return bufferBaseOffset;
149+
}
150+
151+
boolean isFinal() {
152+
return isFinal;
153+
}
154+
155+
boolean isEmpty() {
156+
return payloadLength == 0;
157+
}
158+
159+
private static final StatusCode FAILED_PRECONDITION_STATUS_CODE =
160+
new StatusCode() {
161+
@Override
162+
public StatusCode.Code getCode() {
163+
return StatusCode.Code.FAILED_PRECONDITION;
164+
}
165+
166+
@Override
167+
public @Nullable Object getTransportCode() {
168+
return null;
169+
}
170+
};
171+
172+
static FailedPreconditionException protocolViolation(String message) {
173+
return new FailedPreconditionException(message, null, FAILED_PRECONDITION_STATUS_CODE, false);
174+
}
175+
}

0 commit comments

Comments
 (0)