Skip to content

Commit b6a2334

Browse files
committed
feat(gax): surface actionable error messages with upload session URL and stream requirements
Improve error messages across resumable upload failure paths to provide actionable context for debugging and recovery. - In ResumableUploadFutureImpl, augment outgoing exception messages on terminal failures with the active upload session URL (or the endpoint if session initiation failed), ensuring callers have the session URL required for diagnostic queries and manual resume. - In RewindableStreamBuffer, clarify the UploadProtocolViolationException message when a server committed offset falls below the buffer base offset by explicitly explaining that a seekable stream is required to rewind to earlier offsets. - In ResumableUploadChunkCoordinator, include the upload session URL when reporting an incomplete upload status after transmitting the final chunk. - Add comprehensive unit tests in ResumableUploadCallableImplTest and RewindableStreamBufferTest verifying that the upload URL or endpoint appears in error messages across start failures, chunk transfer failures, recovery query failures, global timeout expirations, and rewind-below-base violations.
1 parent 9ff252b commit b6a2334

8 files changed

Lines changed: 522 additions & 56 deletions

File tree

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -105,13 +105,14 @@ void setRetryingFuture(RetryingFuture<ChunkUploadResponse<ResponseT>> retryingFu
105105

106106
private boolean needsRecovery() {
107107
if (lastFailure != null) {
108-
UploadErrorCategory category = UploadErrorClassifier.classify(lastFailure, currentCommand);
109-
return category == UploadErrorCategory.RECOVERABLE;
108+
UploadErrorClassifier.Category category =
109+
UploadErrorClassifier.classify(lastFailure, currentCommand);
110+
return category == UploadErrorClassifier.Category.RECOVERABLE;
110111
}
111112
if (lastResponse != null && lastResponse.getUploadStatus() == null) {
112-
UploadErrorCategory category =
113+
UploadErrorClassifier.Category category =
113114
UploadErrorClassifier.classifyMissingStatusHeader(currentCommand);
114-
return category == UploadErrorCategory.RECOVERABLE;
115+
return category == UploadErrorClassifier.Category.RECOVERABLE;
115116
}
116117
return false;
117118
}

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

Lines changed: 57 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -119,28 +119,6 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
119119
ResumableUploadCallSettings settings,
120120
ApiCallContext callContext,
121121
ClientContext clientContext) {
122-
this(
123-
result,
124-
startFuture,
125-
uploadChunkCallable,
126-
queryStatusCallable,
127-
payload,
128-
settings,
129-
callContext,
130-
clientContext,
131-
DEFAULT_CHUNK_RETRY_SETTINGS);
132-
}
133-
134-
ResumableUploadChunkCoordinator(
135-
SettableApiFuture<ResponseT> result,
136-
ApiFuture<ResumableUploadSession> startFuture,
137-
UnaryCallable<ChunkUploadRequest, ChunkUploadResponse<ResponseT>> uploadChunkCallable,
138-
UnaryCallable<QueryStatusRequest, QueryStatusResponse<ResponseT>> queryStatusCallable,
139-
InputStream payload,
140-
ResumableUploadCallSettings settings,
141-
ApiCallContext callContext,
142-
ClientContext clientContext,
143-
RetrySettings chunkRetrySettings) {
144122
this.result = checkNotNull(result, "result must not be null");
145123
this.startFuture = checkNotNull(startFuture, "startFuture must not be null");
146124
this.uploadChunkCallable =
@@ -153,11 +131,8 @@ final class ResumableUploadChunkCoordinator<ResponseT> {
153131
this.chunkSize = settings.getChunkSize();
154132
this.callContext = checkNotNull(callContext, "callContext must not be null");
155133
this.clientContext = checkNotNull(clientContext, "clientContext must not be null");
156-
this.chunkRetrySettings =
157-
checkNotNull(chunkRetrySettings, "chunkRetrySettings must not be null");
158-
synchronized (lock) {
159-
this.inFlightFuture = startFuture;
160-
}
134+
this.chunkRetrySettings = DEFAULT_CHUNK_RETRY_SETTINGS;
135+
this.inFlightFuture = startFuture;
161136
}
162137

163138
void start() {
@@ -179,10 +154,8 @@ void start() {
179154
new ApiFutureCallback<ResumableUploadSession>() {
180155
@Override
181156
public void onSuccess(ResumableUploadSession session) {
182-
synchronized (lock) {
183-
if (done) {
184-
return;
185-
}
157+
if (isDone()) {
158+
return;
186159
}
187160
uploadSessionUrl = session.getUploadUrl();
188161
progressTracker.onStarted(uploadSessionUrl);
@@ -209,6 +182,12 @@ ResumableUploadStatus getStatus() {
209182
return progressTracker.getStatus();
210183
}
211184

185+
private boolean isDone() {
186+
synchronized (lock) {
187+
return done;
188+
}
189+
}
190+
212191
private static final StatusCode TIMEOUT_STATUS_CODE =
213192
new StatusCode() {
214193
@Override
@@ -221,6 +200,7 @@ public StatusCode.Code getCode() {
221200
return null;
222201
}
223202
};
203+
224204
private void onTimeout() {
225205
synchronized (lock) {
226206
if (done) {
@@ -305,21 +285,55 @@ private void finish(@Nullable ResponseT response, @Nullable Throwable error) {
305285
progressTracker.onFinalized(totalBytes);
306286
result.set(response);
307287
} else {
308-
progressTracker.onFailed(error, uploadSessionUrl);
288+
Throwable augmented = augmentWithUrl(error);
309289
if (closeError != null) {
310-
error.addSuppressed(closeError);
290+
augmented.addSuppressed(closeError);
311291
}
312-
result.setException(error);
292+
progressTracker.onFailed(augmented, uploadSessionUrl);
293+
result.setException(augmented);
313294
}
314295
}
315296

316-
private @Nullable IOException closePayload() {
317-
synchronized (lock) {
318-
if (payloadClosed) {
319-
return null;
297+
private Throwable augmentWithUrl(Throwable t) {
298+
String url = uploadSessionUrl != null ? uploadSessionUrl : clientContext.getEndpoint();
299+
if (url == null || url.isEmpty()) {
300+
return t;
301+
}
302+
String message = t.getMessage();
303+
if (message != null && message.contains(url)) {
304+
return t;
305+
}
306+
String label = uploadSessionUrl != null ? "upload URL: " : "endpoint: ";
307+
String augmentedMessage =
308+
(message != null ? message : t.getClass().getSimpleName()) + " (" + label + url + ")";
309+
Throwable augmented = t;
310+
if (t instanceof ApiException) {
311+
ApiException apiException = (ApiException) t;
312+
augmented =
313+
ApiExceptionFactory.createException(
314+
augmentedMessage,
315+
apiException.getCause(),
316+
apiException.getStatusCode(),
317+
apiException.isRetryable(),
318+
apiException.getErrorDetails());
319+
} else if (t instanceof IllegalStateException) {
320+
augmented = new IllegalStateException(augmentedMessage, t.getCause());
321+
} else if (t instanceof IOException) {
322+
augmented = new IOException(augmentedMessage, t.getCause());
323+
}
324+
if (augmented != t) {
325+
for (Throwable suppressed : t.getSuppressed()) {
326+
augmented.addSuppressed(suppressed);
320327
}
321-
payloadClosed = true;
322328
}
329+
return augmented;
330+
}
331+
332+
private @Nullable IOException closePayload() {
333+
if (payloadClosed) {
334+
return null;
335+
}
336+
payloadClosed = true;
323337
try {
324338
payload.close();
325339
return null;
@@ -329,10 +343,8 @@ private void finish(@Nullable ResponseT response, @Nullable Throwable error) {
329343
}
330344

331345
private void transmitChunk(long currentOffset) {
332-
synchronized (lock) {
333-
if (done) {
334-
return;
335-
}
346+
if (isDone()) {
347+
return;
336348
}
337349

338350
String url = uploadSessionUrl;
@@ -400,10 +412,8 @@ private void transmitChunk(long currentOffset) {
400412
new ApiFutureCallback<ChunkUploadResponse<ResponseT>>() {
401413
@Override
402414
public void onSuccess(ChunkUploadResponse<ResponseT> response) {
403-
synchronized (lock) {
404-
if (done) {
405-
return;
406-
}
415+
if (isDone()) {
416+
return;
407417
}
408418
long nextOffset = streamBuffer.getBufferBaseOffset() + streamBuffer.getPayloadLength();
409419
progressTracker.onChunkUploaded(nextOffset);

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,8 @@ void realignTo(long committedOffset) throws IOException {
102102
throw protocolViolation(
103103
String.format(
104104
"Server committed offset %d is below buffer base offset %d for upload URL %s; cannot"
105-
+ " rewind stream before buffer base",
105+
+ " rewind stream before buffer base. A seekable stream is required to rewind to"
106+
+ " earlier offsets.",
106107
committedOffset, bufferBaseOffset, uploadUrl));
107108
}
108109

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,10 @@ private static void dispatchSafely(
237237
try {
238238
listener.onProgress(status);
239239
} catch (Throwable t) {
240-
LOG.log(Level.WARNING, "Exception thrown by ResumableUploadProgressListener", t);
240+
LOG.log(
241+
Level.WARNING,
242+
"Exception thrown by ResumableUploadProgressListener: " + listener.getClass().getName(),
243+
t);
241244
}
242245
}
243246
}

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public boolean shouldRetry(
6464
if (previousThrowable instanceof CancellationException) {
6565
return false;
6666
}
67-
UploadErrorCategory category = null;
67+
UploadErrorClassifier.Category category = null;
6868
if (previousThrowable != null) {
6969
category = UploadErrorClassifier.classify(previousThrowable, command);
7070
} else if (previousResponse instanceof ChunkUploadResponse) {
@@ -78,7 +78,8 @@ public boolean shouldRetry(
7878
category = UploadErrorClassifier.classifyMissingStatusHeader(command);
7979
}
8080
}
81-
return category == UploadErrorCategory.TRANSIENT || category == UploadErrorCategory.RECOVERABLE;
81+
return category == UploadErrorClassifier.Category.TRANSIENT
82+
|| category == UploadErrorClassifier.Category.RECOVERABLE;
8283
}
8384

8485
@Override

‎sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/ResumableUploadCallableImplTest.java‎

Lines changed: 133 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,11 @@ void setUp() {
107107
callContext = FakeCallContext.createDefault();
108108
executor = Executors.newScheduledThreadPool(2);
109109
clientContext =
110-
ClientContext.newBuilder().setDefaultCallContext(callContext).setExecutor(executor).build();
110+
ClientContext.newBuilder()
111+
.setDefaultCallContext(callContext)
112+
.setExecutor(executor)
113+
.setEndpoint("https://test.endpoint.com")
114+
.build();
111115
callable = new ResumableUploadCallableImpl<>(mockClient, defaultSettings, clientContext);
112116
}
113117

@@ -1409,6 +1413,134 @@ void testProgressListener_orderingUnderConcurrency_pinsSequentialExecutor() thro
14091413
}
14101414
}
14111415

1416+
@Test
1417+
void testActionableErrors_startFailureAfterRetries_messageContainsEndpointUrl() {
1418+
when(mockStartCallable.futureCall(any(), any()))
1419+
.thenReturn(
1420+
ApiFutures.immediateFailedFuture(
1421+
createApiException(401, StatusCode.Code.UNAUTHENTICATED)));
1422+
1423+
ResumableUploadFuture<String> future =
1424+
callable.futureCall("resource-path", streamOf("hello"), null);
1425+
1426+
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
1427+
assertThat(ex.getCause()).isInstanceOf(ApiException.class);
1428+
assertThat(ex.getCause().getMessage()).contains("https://test.endpoint.com");
1429+
assertThat(future.getUploadSessionUrl()).isNull();
1430+
}
1431+
1432+
@Test
1433+
void testActionableErrors_chunkFailureAfterRetries_messageContainsUploadSessionUrl() {
1434+
String sessionUrl = "https://upload.url/chunk-error-test";
1435+
stubStartSession(sessionUrl);
1436+
when(mockChunkCallable.futureCall(any(ChunkUploadRequest.class), any()))
1437+
.thenReturn(
1438+
ApiFutures.immediateFailedFuture(
1439+
createApiException(403, StatusCode.Code.PERMISSION_DENIED)));
1440+
1441+
ResumableUploadFuture<String> future =
1442+
callable.futureCall("resource-path", streamOf("hello"), null);
1443+
1444+
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
1445+
assertThat(ex.getCause()).isInstanceOf(ApiException.class);
1446+
assertThat(ex.getCause().getMessage()).contains(sessionUrl);
1447+
assertThat(future.getUploadSessionUrl()).isEqualTo(sessionUrl);
1448+
}
1449+
1450+
@Test
1451+
void testActionableErrors_preservesErrorDetailsAndSuppressedExceptions() {
1452+
String sessionUrl = "https://upload.url/chunk-error-details-test";
1453+
stubStartSession(sessionUrl);
1454+
ErrorDetails errorDetails = ErrorDetails.builder().build();
1455+
ApiException original =
1456+
ApiExceptionFactory.createException(
1457+
"HTTP 403",
1458+
null,
1459+
new HttpStatusStatusCode(403, StatusCode.Code.PERMISSION_DENIED),
1460+
false,
1461+
errorDetails);
1462+
IOException suppressed = new IOException("underlying stream error");
1463+
original.addSuppressed(suppressed);
1464+
when(mockChunkCallable.futureCall(any(ChunkUploadRequest.class), any()))
1465+
.thenReturn(ApiFutures.immediateFailedFuture(original));
1466+
1467+
ResumableUploadFuture<String> future =
1468+
callable.futureCall("resource-path", streamOf("hello"), null);
1469+
1470+
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
1471+
assertThat(ex.getCause()).isInstanceOf(ApiException.class);
1472+
ApiException cause = (ApiException) ex.getCause();
1473+
assertThat(cause.getMessage()).contains(sessionUrl);
1474+
assertThat(cause.getErrorDetails()).isSameInstanceAs(errorDetails);
1475+
assertThat(cause.getSuppressed()).asList().contains(suppressed);
1476+
assertThat(future.getUploadSessionUrl()).isEqualTo(sessionUrl);
1477+
}
1478+
1479+
@Test
1480+
void testActionableErrors_recoveryFailure_messageContainsUploadSessionUrl() {
1481+
String sessionUrl = "https://upload.url/recovery-error-test";
1482+
stubStartSession(sessionUrl);
1483+
when(mockChunkCallable.futureCall(any(ChunkUploadRequest.class), any()))
1484+
.thenReturn(
1485+
ApiFutures.immediateFailedFuture(
1486+
createApiException(400, StatusCode.Code.INVALID_ARGUMENT)));
1487+
when(mockQueryCallable.futureCall(any(QueryStatusRequest.class), any()))
1488+
.thenReturn(
1489+
ApiFutures.immediateFailedFuture(
1490+
createApiException(403, StatusCode.Code.PERMISSION_DENIED)));
1491+
1492+
ResumableUploadFuture<String> future =
1493+
callable.futureCall("resource-path", streamOf("hello"), null);
1494+
1495+
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
1496+
assertThat(ex.getCause()).isInstanceOf(ApiException.class);
1497+
assertThat(ex.getCause().getMessage()).contains(sessionUrl);
1498+
assertThat(future.getUploadSessionUrl()).isEqualTo(sessionUrl);
1499+
}
1500+
1501+
@Test
1502+
void testActionableErrors_globalTimeoutFailure_messageContainsUploadSessionUrl() {
1503+
String sessionUrl = "https://upload.url/timeout-error-test";
1504+
stubStartSession(sessionUrl);
1505+
SettableApiFuture<ChunkUploadResponse<String>> hungChunk = SettableApiFuture.create();
1506+
when(mockChunkCallable.futureCall(any(ChunkUploadRequest.class), any())).thenReturn(hungChunk);
1507+
1508+
ResumableUploadCallSettings settings =
1509+
defaultSettings.toBuilder().setGlobalTimeout(Duration.ofMillis(50)).build();
1510+
1511+
ResumableUploadFuture<String> future =
1512+
callable.futureCall("resource-path", streamOf("hello"), null, settings);
1513+
1514+
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
1515+
assertThat(ex.getCause()).isInstanceOf(DeadlineExceededException.class);
1516+
assertThat(ex.getCause().getMessage()).contains(sessionUrl);
1517+
assertThat(future.getUploadSessionUrl()).isEqualTo(sessionUrl);
1518+
}
1519+
1520+
@Test
1521+
void testActionableErrors_rewindFailure_surfacesActionableSeekableStreamMessage() {
1522+
String sessionUrl = "https://upload.url/rewind-error-test";
1523+
stubStartSession(sessionUrl);
1524+
when(mockChunkCallable.futureCall(any(ChunkUploadRequest.class), any()))
1525+
.thenReturn(ApiFutures.immediateFuture(ChunkUploadResponse.create(false, null)))
1526+
.thenReturn(
1527+
ApiFutures.immediateFailedFuture(
1528+
createApiException(400, StatusCode.Code.INVALID_ARGUMENT)));
1529+
1530+
when(mockQueryCallable.futureCall(any(QueryStatusRequest.class), any()))
1531+
.thenReturn(ApiFutures.immediateFuture(createQueryResponse(false, 4L, null, "active")));
1532+
1533+
byte[] data = new byte[16];
1534+
ResumableUploadFuture<String> future =
1535+
callable.futureCall("resource-path", new ByteArrayInputStream(data), null);
1536+
1537+
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
1538+
assertThat(ex.getCause()).isInstanceOf(FailedPreconditionException.class);
1539+
assertThat(ex.getCause().getMessage()).contains(sessionUrl);
1540+
assertThat(ex.getCause().getMessage()).contains("seekable stream");
1541+
assertThat(future.getUploadSessionUrl()).isEqualTo(sessionUrl);
1542+
}
1543+
14121544
private static class HttpStatusStatusCode implements StatusCode {
14131545
private final int httpStatus;
14141546
private final StatusCode.Code code;

0 commit comments

Comments
 (0)