GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(gax): add RewindableStreamBuffer in prep for chunk upload recovery by whowes · Pull Request #14423 · googleapis/google-cloud-java

feat(gax): add RewindableStreamBuffer in prep for chunk upload recovery #14423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
whowes merged 1 commit into main from whowes/resumable-upload-buffer-window
Sep 25, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

feat(gax): add RewindableStreamBuffer in prep for chunk upload recovery #14423

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
1 commit
Select commit
ad7b3f0
feat(gax): add rewindable stream buffer for chunk recovery
whowes Sep 12, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

40 changes: 11 additions & 29 deletions 40 ...va/gax-java/gax/src/main/java/com/google/api/gax/rpc/ResumableUploadChunkCoordinator.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,8 @@
import com.google.api.gax.resumable.ChunkUploadRequest;
import com.google.api.gax.resumable.ChunkUploadResponse;
import com.google.api.gax.resumable.ResumableUploadStatus;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.InputStream;
import java.util.Arrays;
import java.util.concurrent.CancellationException;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
Expand All @@ -56,14 +54,10 @@
@NullMarked
final class ResumableUploadChunkCoordinator<ResponseT> {

private static final byte[] EMPTY_PAYLOAD = new byte[0];

private final UnaryCallable<ChunkUploadRequest, ChunkUploadResponse<ResponseT>>
uploadChunkCallable;
private final String uploadUrl;
private final InputStream payload;
private final byte[] buffer;
private final int chunkSize;
private final RewindableStreamBuffer buffer;
private final ApiCallContext callContext;
private final SettableApiFuture<ResponseT> uploadResultFuture = SettableApiFuture.create();
private volatile @Nullable ApiFuture<?> inFlightFuture;
Expand All @@ -77,10 +71,9 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
this.uploadChunkCallable =
checkNotNull(uploadChunkCallable, "uploadChunkCallable must not be null");
this.uploadUrl = checkNotNull(uploadUrl, "uploadUrl must not be null");
this.payload = checkNotNull(payload, "payload must not be null");
this.chunkSize = chunkSize;
checkNotNull(payload, "payload must not be null");
this.callContext = checkNotNull(callContext, "callContext must not be null");
this.buffer = new byte[chunkSize];
this.buffer = new RewindableStreamBuffer(payload, chunkSize, uploadUrl);
}

ApiFuture<ResponseT> getFuture() {
Expand All @@ -96,40 +89,30 @@ void start() {
}
},
MoreExecutors.directExecutor());
transmitChunk(0L);
transmitChunk();
}

private void transmitChunk(long currentOffset) {
private void transmitChunk() {
try {
// Abort if the session was already completed or canceled.
if (uploadResultFuture.isDone()) {
return;
}

// Read the next chunk slice from the payload stream.
int bytesRead = ByteStreams.read(payload, buffer, 0, chunkSize);
buffer.fill();

// Determine if this is the final chunk and build the chunk request.
boolean isFinal = bytesRead < chunkSize;
byte[] chunkPayload;
if (bytesRead == chunkSize) {
chunkPayload = buffer;
} else if (bytesRead == 0) {
chunkPayload = EMPTY_PAYLOAD;
} else {
chunkPayload = Arrays.copyOf(buffer, bytesRead);
}

ChunkUploadRequest chunkRequest =
ChunkUploadRequest.newBuilder()
.setUploadUrl(uploadUrl)
.setPayload(chunkPayload)
.setOffset(currentOffset)
.setFinal(isFinal)
.setPayload(buffer.getPayload())
.setOffset(buffer.getBufferBaseOffset())
.setFinal(buffer.isFinal())
.build();

// Dispatch the chunk upload call and register the in-flight future for cancellation.
long chunkLength = chunkPayload.length;
boolean isFinal = chunkRequest.isFinal();
ApiFuture<ChunkUploadResponse<ResponseT>> chunkFuture =
uploadChunkCallable.futureCall(chunkRequest, callContext);
if (!tryRegisterInFlightFuture(chunkFuture)) {
Expand All @@ -144,7 +127,6 @@ public void onSuccess(ChunkUploadResponse<ResponseT> response) {
if (uploadResultFuture.isDone()) {
return;
}
long nextOffset = currentOffset + chunkLength;
if (response.getUploadStatus() == ResumableUploadStatus.FINAL) {
uploadResultFuture.set(response.getResponse());
} else if (isFinal) {
Expand All @@ -153,7 +135,7 @@ public void onSuccess(ChunkUploadResponse<ResponseT> response) {
"Upload stream ended and final chunk was transmitted, but server returned"
+ " incomplete status"));
} else {
transmitChunk(nextOffset);
transmitChunk();
}
}

Expand Down
150 changes: 150 additions & 0 deletions 150 ...atform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/RewindableStreamBuffer.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* Copyright 2026 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.api.gax.rpc;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.jspecify.annotations.NullMarked;

/** Manages a single-chunk rewindable buffer over an {@link InputStream} for resumable uploads. */
@NullMarked
final class RewindableStreamBuffer {

private static final byte[] EMPTY_PAYLOAD = new byte[0];

private final InputStream inputStream;
private final int chunkSize;
private final String uploadUrl;
private final byte[] buffer;

private long bufferBaseOffset;
private int payloadLength;
private boolean isFinal;
private boolean streamExhausted;

RewindableStreamBuffer(InputStream inputStream, int chunkSize, String uploadUrl) {
this.inputStream = checkNotNull(inputStream, "inputStream must not be null");
checkArgument(chunkSize > 0, "chunkSize must be > 0");
this.chunkSize = chunkSize;
this.uploadUrl = checkNotNull(uploadUrl, "uploadUrl must not be null");
this.buffer = new byte[chunkSize];
this.bufferBaseOffset = 0L;
this.payloadLength = 0;
this.isFinal = false;
this.streamExhausted = false;
}

/**
* Advances the buffer past the current payload, reading up to chunk size from the stream.
*
* @throws IOException if reading from the stream fails
*/
void fill() throws IOException {
this.bufferBaseOffset += payloadLength;
this.payloadLength = ByteStreams.read(inputStream, buffer, 0, chunkSize);
this.isFinal = (payloadLength < chunkSize);
if (this.isFinal) {
this.streamExhausted = true;
}
}

/**
* Realigns the buffer window to {@code committedOffset}.
*
* <p>Compacts forward within the existing buffer to discard already-committed bytes, and then
* tops up the buffer to capacity from the underlying stream.
*
* @param committedOffset the server's committed byte offset
* @throws IllegalStateException if {@code committedOffset} is below the buffer's base offset or
* beyond the current buffer window
* @throws IOException if reading from the stream fails
*/
void realignTo(long committedOffset) throws IOException {
Comment thread
whowes marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread

@blakeli0 blakeli0 Sep 23, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this method used in this PR?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@whowes whowes Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it's used in recovery (not implemented until #14424). This PR just introduces the buffer and wires it up.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
if (committedOffset < bufferBaseOffset) {
throw new IllegalStateException(
String.format(
"Server committed offset %d is below buffer base offset %d for upload URL %s; cannot"
+ " rewind stream before buffer base",
committedOffset, bufferBaseOffset, uploadUrl));
}

if (committedOffset > bufferBaseOffset + payloadLength) {
throw new IllegalStateException(
String.format(
"Server committed offset %d is beyond current buffer window [%d, %d] for upload URL"
+ " %s",
committedOffset, bufferBaseOffset, bufferBaseOffset + payloadLength, uploadUrl));
}

int committedWithinBuffer = (int) (committedOffset - bufferBaseOffset);
int remainingBytes = payloadLength - committedWithinBuffer;

if (remainingBytes > 0 && committedWithinBuffer > 0) {
System.arraycopy(buffer, committedWithinBuffer, buffer, 0, remainingBytes);
}

this.bufferBaseOffset = committedOffset;
this.payloadLength = remainingBytes;

if (!streamExhausted && payloadLength < chunkSize) {
int space = chunkSize - payloadLength;
int additionalRead = ByteStreams.read(inputStream, buffer, payloadLength, space);
payloadLength += additionalRead;
if (additionalRead < space) {
streamExhausted = true;
}
}

this.isFinal = streamExhausted;
}

byte[] getPayload() {
if (payloadLength == buffer.length) {
return buffer;
}
if (payloadLength == 0) {
return EMPTY_PAYLOAD;
}
return Arrays.copyOf(buffer, payloadLength);
}

long getBufferBaseOffset() {
return bufferBaseOffset;
}

boolean isFinal() {
return isFinal;
}
}
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.