Skip to content

Commit 12f0b82

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 18e2288 commit 12f0b82

7 files changed

Lines changed: 543 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
@@ -46,6 +46,7 @@
4646
import java.io.ByteArrayInputStream;
4747
import java.io.InputStream;
4848
import java.nio.charset.StandardCharsets;
49+
import java.util.Arrays;
4950
import java.util.Collections;
5051
import java.util.List;
5152
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: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,10 @@
4343
import com.google.api.gax.retrying.RetryAlgorithm;
4444
import com.google.api.gax.retrying.RetrySettings;
4545
import com.google.api.gax.retrying.ScheduledRetryingExecutor;
46-
import com.google.common.io.ByteStreams;
4746
import com.google.common.util.concurrent.MoreExecutors;
4847
import java.io.IOException;
4948
import java.io.InputStream;
5049
import java.time.Duration;
51-
import java.util.Arrays;
5250
import java.util.concurrent.CancellationException;
5351
import java.util.concurrent.Executor;
5452
import org.jspecify.annotations.NullMarked;
@@ -71,17 +69,13 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
7169
.setMaxAttempts(5)
7270
.build();
7371

74-
private static final byte[] EMPTY_PAYLOAD = new byte[0];
75-
7672
private final Executor chunkExecutor =
7773
MoreExecutors.newSequentialExecutor(MoreExecutors.directExecutor());
7874

7975
private final UnaryCallable<ChunkUploadRequest, ChunkUploadResponse<ResponseT>>
8076
uploadChunkCallable;
8177
private final String uploadUrl;
82-
private final InputStream payload;
83-
private final byte[] buffer;
84-
private final int chunkSize;
78+
private final RewindableStreamBuffer buffer;
8579
private final ApiCallContext callContext;
8680
private final SettableApiFuture<ResponseT> result = SettableApiFuture.create();
8781
private volatile @Nullable ApiFuture<?> currentChunkFuture;
@@ -94,11 +88,10 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
9488
ClientContext clientContext) {
9589
checkNotNull(uploadChunkCallable, "uploadChunkCallable must not be null");
9690
this.uploadUrl = checkNotNull(uploadUrl, "uploadUrl must not be null");
97-
this.payload = checkNotNull(payload, "payload must not be null");
98-
this.chunkSize = chunkSize;
91+
checkNotNull(payload, "payload must not be null");
9992
checkNotNull(clientContext, "clientContext must not be null");
10093
this.callContext = clientContext.getDefaultCallContext();
101-
this.buffer = new byte[chunkSize];
94+
this.buffer = new RewindableStreamBuffer(payload, chunkSize, uploadUrl);
10295

10396
RetryAlgorithm<ChunkUploadResponse<ResponseT>> retryAlgorithm =
10497
new RetryAlgorithm<>(
@@ -131,35 +124,26 @@ private void transmitChunk(long currentOffset) {
131124
}
132125

133126
// Read the next chunk slice from the payload stream.
134-
int bytesRead;
135127
try {
136-
bytesRead = ByteStreams.read(payload, buffer, 0, chunkSize);
128+
buffer.fill(currentOffset);
137129
} catch (IOException e) {
138130
result.setException(e);
139131
return;
140132
}
141133

142134
// Determine if this is the final chunk and build the chunk request.
143-
boolean isFinal = bytesRead < chunkSize;
144-
byte[] chunkPayload;
145-
if (bytesRead == chunkSize) {
146-
chunkPayload = buffer;
147-
} else if (bytesRead == 0) {
148-
chunkPayload = EMPTY_PAYLOAD;
149-
} else {
150-
chunkPayload = Arrays.copyOf(buffer, bytesRead);
151-
}
152-
153135
ChunkUploadRequest chunkRequest =
154136
ChunkUploadRequest.newBuilder()
155137
.setUploadUrl(uploadUrl)
156-
.setPayload(chunkPayload)
157-
.setOffset(currentOffset)
158-
.setFinal(isFinal)
138+
.setPayload(buffer.getBuffer())
139+
.setPayloadLength(buffer.getPayloadLength())
140+
.setOffset(buffer.getBufferBaseOffset())
141+
.setFinal(buffer.isFinal())
159142
.build();
160143

161144
// Dispatch the chunk upload call and register the in-flight future for cancellation.
162-
long chunkLength = chunkPayload.length;
145+
long chunkLength = chunkRequest.getPayloadLength();
146+
boolean isFinal = chunkRequest.isFinal();
163147
try {
164148
ApiFuture<ChunkUploadResponse<ResponseT>> chunkFuture =
165149
uploadChunkCallable.futureCall(chunkRequest, callContext);
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+
private static FailedPreconditionException protocolViolation(String message) {
173+
return new FailedPreconditionException(message, null, FAILED_PRECONDITION_STATUS_CODE, false);
174+
}
175+
}

0 commit comments

Comments
 (0)