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): wire up ResumableUploadProgressTracker by whowes · Pull Request #14427 · googleapis/google-cloud-java

feat(gax): wire up ResumableUploadProgressTracker #14427

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-progress
Sep 29, 2026

Uh oh!

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

Merged

feat(gax): wire up ResumableUploadProgressTracker #14427

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
1 commit
Select commit
96b37da
feat(gax): wire progress listener into coordinator and attempt lifecycle
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

11 changes: 10 additions & 1 deletion 11 ...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 @@ -72,6 +72,7 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
private final ApiCallContext callContext;
private final ExponentialRetryAlgorithm recoveryAlgorithm;
private final ScheduledExecutorService executor;
private final ResumableUploadProgressTracker progressTracker;
private final SettableApiFuture<ResponseT> uploadResultFuture = SettableApiFuture.create();
private volatile @Nullable Future<?> inFlightFuture;
private TimedAttemptSettings recoverySettings;
Expand All @@ -85,7 +86,8 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
int chunkSize,
ApiCallContext callContext,
ExponentialRetryAlgorithm recoveryAlgorithm,
ScheduledExecutorService executor) {
ScheduledExecutorService executor,
ResumableUploadProgressTracker progressTracker) {
this.uploadChunkCallable =
checkNotNull(uploadChunkCallable, "uploadChunkCallable must not be null");
this.queryStatusCallable =
Expand All @@ -96,6 +98,7 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
this.recoveryAlgorithm = checkNotNull(recoveryAlgorithm, "recoveryAlgorithm must not be null");
this.executor = checkNotNull(executor, "executor must not be null");
this.recoverySettings = recoveryAlgorithm.createFirstAttempt();
this.progressTracker = checkNotNull(progressTracker, "progressTracker must not be null");
this.buffer = new RewindableStreamBuffer(payload, chunkSize, uploadUrl);
}

Expand All @@ -104,6 +107,7 @@ ApiFuture<ResponseT> getFuture() {
}

void start() {
progressTracker.onStarted(uploadUrl);
uploadResultFuture.addListener(
() -> {
Future<?> inFlight = inFlightFuture;
Expand Down Expand Up @@ -180,6 +184,7 @@ public void onFailure(Throwable t) {
}

private void recover(Throwable cause) {
progressTracker.onRecovering();
try {
if (madeProgressSinceRecovery) {
recoverySettings =
Expand Down Expand Up @@ -262,6 +267,7 @@ private void handleQueryResponse(QueryStatusResponse<ResponseT> queryResponse)
"Query status response missing X-Goog-Upload-Status header for upload URL: " + uploadUrl);
}
if (queryResponse.getUploadStatus() == ResumableUploadStatus.FINAL) {
progressTracker.onFinalized(buffer.getBufferBaseOffset() + buffer.getPayload().length);
uploadResultFuture.set(queryResponse.getResponse());
return;
}
Expand All @@ -271,12 +277,14 @@ private void handleQueryResponse(QueryStatusResponse<ResponseT> queryResponse)
"Incomplete query status response did not include a committed offset for upload URL: "
+ uploadUrl);
}
progressTracker.onOffsetReceived(committedOffset);
Comment thread
whowes marked this conversation as resolved.
Resolved

Uh oh!

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

buffer.realignTo(committedOffset);
transmitChunk();
}

private void handleChunkResponse(ChunkUploadResponse<ResponseT> response) throws IOException {
if (response.getUploadStatus() == ResumableUploadStatus.FINAL) {
progressTracker.onFinalized(buffer.getBufferBaseOffset() + buffer.getPayload().length);
uploadResultFuture.set(response.getResponse());
} else if (buffer.isFinal()) {
uploadResultFuture.setException(
Expand All @@ -287,6 +295,7 @@ private void handleChunkResponse(ChunkUploadResponse<ResponseT> response) throws
} else {
madeProgressSinceRecovery = true;
buffer.fill();
progressTracker.onChunkUploaded(buffer.getBufferBaseOffset());
transmitChunk();
}
}
Expand Down
11 changes: 10 additions & 1 deletion 11 ...orm-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ResumableUploadFutureImpl.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ final class ResumableUploadFutureImpl<ResponseT> implements ResumableUploadFutur
private final ApiCallContext callContext;
private final ScheduledExecutorService executor;
private final ExponentialRetryAlgorithm recoveryAlgorithm;
private final ResumableUploadProgressTracker progressTracker =
new ResumableUploadProgressTracker();
private final SettableApiFuture<ResponseT> resultFuture = SettableApiFuture.create();

private volatile @Nullable String uploadSessionUrl;
Expand Down Expand Up @@ -143,6 +145,10 @@ private ResumableUploadFutureImpl(
this.executor = checkNotNull(clientContext.getExecutor(), "executor must not be null");
this.recoveryAlgorithm = checkNotNull(recoveryAlgorithm, "recoveryAlgorithm must not be null");
this.inFlightFuture = startFuture;
ResumableUploadProgressListener progressListener = options.getProgressListener();
if (progressListener != null) {
progressTracker.addListener(progressListener, executor);
}
}

private void start() {
Expand All @@ -165,7 +171,8 @@ public void onSuccess(ResumableUploadSession session) {
options.getChunkSize(),
callContext,
recoveryAlgorithm,
executor);
executor,
progressTracker);
ApiFuture<ResponseT> uploadFuture = coordinator.getFuture();
synchronized (lock) {
if (inFlightFuture == null) {
Expand Down Expand Up @@ -237,6 +244,7 @@ private void fail(Throwable t) {
inFlightFuture = null;
}
inFlight.cancel(true);
progressTracker.onFailed();
closePayload();
resultFuture.setException(t);
}
Expand Down Expand Up @@ -272,6 +280,7 @@ public boolean cancel(boolean mayInterruptIfRunning) {
inFlightFuture = null;
}
inFlight.cancel(mayInterruptIfRunning);
progressTracker.onFailed();
closePayload();
return cancelled;
}
Expand Down
33 changes: 33 additions & 0 deletions 33 ...atform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ResumableUploadOptions.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ public abstract class ResumableUploadOptions {
*/
public abstract @Nullable Duration getGlobalTimeout();

/**
* Returns the listener notified of upload progress and state transitions, or {@code null} if not
* set.
*/
public abstract @Nullable ResumableUploadProgressListener getProgressListener();

/**
* Merges another {@code ResumableUploadOptions} instance with this one. Fields set in {@code
* other} override fields in this instance.
Expand All @@ -73,6 +79,10 @@ public ResumableUploadOptions merge(@Nullable ResumableUploadOptions other) {
if (other.getGlobalTimeout() != null) {
builder.setGlobalTimeout(other.getGlobalTimeout());
}
ResumableUploadProgressListener otherProgressListener = other.getProgressListener();
if (otherProgressListener != null) {
builder.setProgressListener(otherProgressListener);
}
return builder.build();
}

Expand All @@ -85,14 +95,37 @@ public static Builder newBuilder() {
/** Builder for {@link ResumableUploadOptions}. */
@AutoValue.Builder
public abstract static class Builder {
/**
* Sets the chunk size in bytes. The payload is sent in chunks of this size, and each chunk is
* buffered in memory so it can be resent if the upload needs to recover. Must be positive;
* defaults to 8 MB.
*/
public abstract Builder setChunkSize(int chunkSize);

/** Returns the chunk size in bytes. See {@link #setChunkSize(int)}. */
public abstract int getChunkSize();

/**
* Sets the global timeout bounding the entire upload, including session initiation, chunk
* transmission, and recovery. If the upload has not completed when the timeout elapses, it is
* cancelled and fails. Must be positive.
*/
public abstract Builder setGlobalTimeout(@Nullable Duration globalTimeout);

/**
* Returns the global upload timeout, or {@code null} if unset. See {@link
* #setGlobalTimeout(Duration)}.
*/
public abstract @Nullable Duration getGlobalTimeout();

/**
* Sets the listener notified of upload progress and state transitions. Updates are delivered in
* order, beginning with {@link ResumableUploadProgress#STATE_STARTING}. Callbacks are
* dispatched on the client's background executor.
*/
public abstract Builder setProgressListener(
@Nullable ResumableUploadProgressListener progressListener);

abstract ResumableUploadOptions autoBuild();

public ResumableUploadOptions build() {
Expand Down
161 changes: 161 additions & 0 deletions 161 ...va/gax-java/gax/src/test/java/com/google/api/gax/rpc/ResumableUploadCallableImplTest.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
Expand Down Expand Up @@ -1069,6 +1070,166 @@ void testGlobalTimeout_coversStartSessionTimeout() throws Exception {
assertThat(hungStartFuture.isCancelled()).isTrue();
}

@Test
void testProgressListener_prescribedStateTransitions() throws Exception {
SettableApiFuture<ResumableUploadSession> startFuture = SettableApiFuture.create();
when(mockStartCallable.futureCall(any(), any())).thenReturn(startFuture);

// 20 bytes with chunkSize = 8 -> 3 chunks: [0..8), [8..16), [16..20)
// Chunk 1 succeeds -> [0..8)
// Chunk 2 fails with recoverable 400
// Query succeeds -> committed offset = 8
// Chunk 2 resend succeeds -> [8..16)
// Chunk 3 succeeds and finalizes -> [16..20)
when(mockChunkCallable.futureCall(any(ChunkUploadRequest.class), any()))
.thenReturn(
ApiFutures.immediateFuture(
ChunkUploadResponse.create(ResumableUploadStatus.ACTIVE, null)))
.thenReturn(
ApiFutures.immediateFailedFuture(
createApiException(400, StatusCode.Code.INVALID_ARGUMENT)))
.thenReturn(
ApiFutures.immediateFuture(
ChunkUploadResponse.create(ResumableUploadStatus.ACTIVE, null)))
.thenReturn(
ApiFutures.immediateFuture(
ChunkUploadResponse.create(ResumableUploadStatus.FINAL, "done")));

when(mockQueryCallable.futureCall(any(QueryStatusRequest.class), any()))
.thenReturn(
ApiFutures.immediateFuture(
QueryStatusResponse.<String>newBuilder()
.setCommittedOffset(8L)
.setUploadStatus(ResumableUploadStatus.ACTIVE)
.build()));

RecordingProgressListener listener = new RecordingProgressListener();
ResumableUploadOptions options =
defaultSettings.toBuilder().setProgressListener(listener).build();

ResumableUploadFuture<String> future =
callable.futureCall("resource-path", streamOf("01234567890123456789"), options);

String url = "https://upload.url/progress-transitions";
startFuture.set(ResumableUploadSession.newBuilder().setUploadUrl(url).build());

assertThat(future.get()).isEqualTo("done");

assertThat(listener.awaitTerminal())
.containsExactly(
createProgress(ResumableUploadProgress.STATE_STARTING, 0L, null),
createProgress(ResumableUploadProgress.STATE_STARTED, 0L, url),
createProgress(ResumableUploadProgress.STATE_UPLOADING, 8L, url),
createProgress(ResumableUploadProgress.STATE_RECOVERING, 8L, url),
createProgress(ResumableUploadProgress.STATE_OFFSET_RECEIVED, 8L, url),
createProgress(ResumableUploadProgress.STATE_UPLOADING, 16L, url),
createProgress(ResumableUploadProgress.STATE_FINALIZED, 20L, url))
.inOrder();
}

@Test
void testProgressListener_uploadFailure_transitionsToFailed() throws Exception {
when(mockStartCallable.futureCall(any(), any()))
.thenReturn(
ApiFutures.immediateFailedFuture(
createApiException(401, StatusCode.Code.UNAUTHENTICATED)));

RecordingProgressListener listener = new RecordingProgressListener();
ResumableUploadOptions options =
defaultSettings.toBuilder().setProgressListener(listener).build();

ResumableUploadFuture<String> future =
callable.futureCall("resource-path", streamOf("hello"), options);
assertThrows(ExecutionException.class, future::get);

assertThat(listener.awaitTerminal())
.containsExactly(
createProgress(ResumableUploadProgress.STATE_STARTING, 0L, null),
createProgress(ResumableUploadProgress.STATE_FAILED, 0L, null))
.inOrder();
}

@Test
void testProgressListener_cancel_transitionsToFailed() throws Exception {
stubStartSession("https://upload.url/cancel-progress");
SettableApiFuture<ChunkUploadResponse<String>> hungChunk = SettableApiFuture.create();
when(mockChunkCallable.futureCall(any(ChunkUploadRequest.class), any())).thenReturn(hungChunk);

RecordingProgressListener listener = new RecordingProgressListener();
ResumableUploadOptions options =
defaultSettings.toBuilder().setProgressListener(listener).build();

ResumableUploadFuture<String> future =
callable.futureCall("resource-path", streamOf("hello"), options);

assertThat(future.cancel(true)).isTrue();
assertThat(hungChunk.isCancelled()).isTrue();
List<ResumableUploadProgress> receivedStatuses = listener.awaitTerminal();
assertThat(receivedStatuses.get(receivedStatuses.size() - 1))
.isEqualTo(
createProgress(
ResumableUploadProgress.STATE_FAILED, 0L, "https://upload.url/cancel-progress"));
}

@Test
void testProgressListener_queryFinal_transitionsToFinalized() throws Exception {
stubStartSession("https://upload.url/query-final-progress");
when(mockChunkCallable.futureCall(any(), any()))
.thenReturn(
ApiFutures.immediateFailedFuture(
createApiException(400, StatusCode.Code.INVALID_ARGUMENT)));
when(mockQueryCallable.futureCall(any(), any()))
.thenReturn(
ApiFutures.immediateFuture(
createQueryResponse(null, "done", ResumableUploadStatus.FINAL)));

RecordingProgressListener listener = new RecordingProgressListener();
ResumableUploadOptions options =
defaultSettings.toBuilder().setProgressListener(listener).build();

ResumableUploadFuture<String> future =
callable.futureCall("resource-path", streamOf("hello"), options);

assertThat(future.get()).isEqualTo("done");
List<ResumableUploadProgress> receivedStatuses = listener.awaitTerminal();
assertThat(receivedStatuses.get(receivedStatuses.size() - 1))
.isEqualTo(
createProgress(
ResumableUploadProgress.STATE_FINALIZED,
5L,
"https://upload.url/query-final-progress"));
}

private static ResumableUploadProgress createProgress(
String state, long bytesUploaded, @Nullable String uploadUrl) {
return ResumableUploadProgress.newBuilder()
.setState(state)
.setBytesUploaded(bytesUploaded)
.setUploadUrl(uploadUrl)
.build();
}

/** Records progress updates delivered asynchronously and signals the terminal update. */
private static final class RecordingProgressListener implements ResumableUploadProgressListener {
private final List<ResumableUploadProgress> received = new CopyOnWriteArrayList<>();
private final CountDownLatch terminal = new CountDownLatch(1);

@Override
public void onProgress(ResumableUploadProgress progress) {
received.add(progress);
String state = progress.getState();
if (ResumableUploadProgress.STATE_FINALIZED.equals(state)
|| ResumableUploadProgress.STATE_FAILED.equals(state)) {
terminal.countDown();
}
}

List<ResumableUploadProgress> awaitTerminal() throws InterruptedException {
assertThat(terminal.await(5, TimeUnit.SECONDS)).isTrue();
return received;
}
}

private static class HttpStatusStatusCode implements StatusCode {
private final int httpStatus;
private final StatusCode.Code code;
Expand Down
26 changes: 26 additions & 0 deletions 26 ...rm-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/ResumableUploadOptionsTest.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,30 @@ public void testMerge_nullGlobalTimeoutDoesNotOverride() {
assertEquals(32 * 1024 * 1024, merged.getChunkSize());
assertEquals(Duration.ofMinutes(10), merged.getGlobalTimeout());
}

@Test
public void testMerge_overridesProgressListener() {
ResumableUploadProgressListener defaultListener = progress -> {};
ResumableUploadProgressListener perRequestListener = progress -> {};
ResumableUploadOptions defaultOptions =
ResumableUploadOptions.newBuilder().setProgressListener(defaultListener).build();
ResumableUploadOptions perRequestOptions =
ResumableUploadOptions.newBuilder().setProgressListener(perRequestListener).build();

ResumableUploadOptions merged = defaultOptions.merge(perRequestOptions);

assertSame(perRequestListener, merged.getProgressListener());
}

@Test
public void testMerge_nullProgressListenerDoesNotOverride() {
ResumableUploadProgressListener defaultListener = progress -> {};
ResumableUploadOptions defaultOptions =
ResumableUploadOptions.newBuilder().setProgressListener(defaultListener).build();
ResumableUploadOptions perRequestOptions = ResumableUploadOptions.newBuilder().build();

ResumableUploadOptions merged = defaultOptions.merge(perRequestOptions);

assertSame(defaultListener, merged.getProgressListener());
}
}
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.