Skip to content

Commit 31fb81a

Browse files
committed
chore: address review comment + add tests
1 parent 3975ab5 commit 31fb81a

3 files changed

Lines changed: 137 additions & 4 deletions

File tree

‎java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -973,17 +973,15 @@ public void cancel() {
973973
Preconditions.checkState(
974974
state != State.INITIALIZED && state != State.SYNC,
975975
"cannot cancel a result set without a callback");
976-
if (completed) {
976+
if (completed || state == State.DONE || cursorReturnedDoneOrException) {
977977
return;
978978
}
979979
if (cancelledException == null) {
980980
cancelledException =
981981
SpannerExceptionFactory.newSpannerException(
982982
ErrorCode.CANCELLED, "This AsyncResultSet has been cancelled");
983983
}
984-
if (!cursorReturnedDoneOrException) {
985-
executionException = null;
986-
}
984+
executionException = null;
987985
state = State.CANCELLED;
988986
}
989987
closeDelegateResultSet();

‎java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1266,4 +1266,57 @@ public void testInitializedDelegateCachedOnlyAfterStartOrCloseCompletes() {
12661266
assertEquals(1, failingStartCalls.get());
12671267
}
12681268
}
1269+
1270+
@Test(timeout = 60_000)
1271+
public void testCancelAfterCallbackDoneWhileProducerStillRunningPreservesDoneState()
1272+
throws Exception {
1273+
CountDownLatch producerInRow2Latch = new CountDownLatch(1);
1274+
CountDownLatch releaseProducerLatch = new CountDownLatch(1);
1275+
CountDownLatch callbackInvokedLatch = new CountDownLatch(1);
1276+
ExecutorService callbackExecutor = Executors.newSingleThreadExecutor();
1277+
ResultSet slowRow2Delegate = mock(ResultSet.class);
1278+
AtomicInteger nextCalls = new AtomicInteger();
1279+
when(slowRow2Delegate.next())
1280+
.thenAnswer(
1281+
invocation -> {
1282+
if (nextCalls.incrementAndGet() == 1) {
1283+
return true;
1284+
}
1285+
producerInRow2Latch.countDown();
1286+
assertTrue(releaseProducerLatch.await(30, TimeUnit.SECONDS));
1287+
return false;
1288+
});
1289+
when(slowRow2Delegate.getCurrentRowAsStruct())
1290+
.thenReturn(Struct.newBuilder().set("id").to(1L).build());
1291+
1292+
try (AsyncResultSetImpl resultSet =
1293+
new AsyncResultSetImpl(simpleProvider, slowRow2Delegate, 4)) {
1294+
ApiFuture<Void> future =
1295+
resultSet.setCallback(
1296+
callbackExecutor,
1297+
cursor -> {
1298+
assertEquals(CursorState.OK, cursor.tryNext());
1299+
assertEquals(1L, cursor.getLong(0));
1300+
callbackInvokedLatch.countDown();
1301+
return CallbackResponse.DONE;
1302+
});
1303+
1304+
assertTrue(producerInRow2Latch.await(30, TimeUnit.SECONDS));
1305+
assertTrue(callbackInvokedLatch.await(30, TimeUnit.SECONDS));
1306+
callbackExecutor.submit(() -> null).get(30, TimeUnit.SECONDS);
1307+
1308+
assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState());
1309+
assertFalse(future.isDone());
1310+
1311+
resultSet.cancel();
1312+
assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState());
1313+
1314+
releaseProducerLatch.countDown();
1315+
assertNull(future.get(30, TimeUnit.SECONDS));
1316+
assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState());
1317+
} finally {
1318+
releaseProducerLatch.countDown();
1319+
callbackExecutor.shutdownNow();
1320+
}
1321+
}
12691322
}

‎java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import java.util.concurrent.BlockingQueue;
5353
import java.util.concurrent.ConcurrentLinkedDeque;
5454
import java.util.concurrent.CountDownLatch;
55+
import java.util.concurrent.ExecutionException;
5556
import java.util.concurrent.ExecutorService;
5657
import java.util.concurrent.Executors;
5758
import java.util.concurrent.ScheduledThreadPoolExecutor;
@@ -624,6 +625,87 @@ private void assertSchemaGettersWorkOnDone(Statement statement, List<String> exp
624625
assertEquals(expectedValues, actualValues);
625626
}
626627

628+
@Test(timeout = 60_000)
629+
public void cancelAfterCursorStateDonePreservesSuccess() throws Exception {
630+
List<String> actualValues = Collections.synchronizedList(new ArrayList<>());
631+
CountDownLatch doneObservedLatch = new CountDownLatch(1);
632+
CountDownLatch cancelCalledLatch = new CountDownLatch(1);
633+
try (AsyncResultSet resultSet =
634+
client.singleUse().executeQueryAsync(READ_MULTIPLE_KEY_VALUE_STATEMENT)) {
635+
ApiFuture<Void> finished =
636+
resultSet.setCallback(
637+
executor,
638+
cursor -> {
639+
while (true) {
640+
switch (cursor.tryNext()) {
641+
case OK:
642+
actualValues.add(cursor.getString("Value"));
643+
break;
644+
case NOT_READY:
645+
return CallbackResponse.CONTINUE;
646+
case DONE:
647+
doneObservedLatch.countDown();
648+
try {
649+
assertTrue(cancelCalledLatch.await(30, TimeUnit.SECONDS));
650+
} catch (InterruptedException interruptedException) {
651+
Thread.currentThread().interrupt();
652+
throw new RuntimeException(interruptedException);
653+
}
654+
assertEquals(READ_TABLE_TYPE, cursor.getType());
655+
return CallbackResponse.DONE;
656+
}
657+
}
658+
});
659+
660+
assertTrue(doneObservedLatch.await(30, TimeUnit.SECONDS));
661+
resultSet.cancel();
662+
cancelCalledLatch.countDown();
663+
assertNull(finished.get(30, TimeUnit.SECONDS));
664+
} finally {
665+
cancelCalledLatch.countDown();
666+
}
667+
assertEquals(Arrays.asList("v1", "v2", "v3"), actualValues);
668+
}
669+
670+
@Test(timeout = 60_000)
671+
public void cancelAfterCursorExceptionPreservesOriginalError() throws Exception {
672+
Statement failingStatement = Statement.of("SELECT * FROM MissingTable");
673+
mockSpanner.putStatementResult(
674+
StatementResult.exception(
675+
failingStatement,
676+
Status.INVALID_ARGUMENT.withDescription("missing table").asRuntimeException()));
677+
CountDownLatch exceptionObservedLatch = new CountDownLatch(1);
678+
CountDownLatch cancelCalledLatch = new CountDownLatch(1);
679+
try (AsyncResultSet resultSet = client.singleUse().executeQueryAsync(failingStatement)) {
680+
ApiFuture<Void> finished =
681+
resultSet.setCallback(
682+
executor,
683+
cursor -> {
684+
SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext);
685+
assertEquals(ErrorCode.INVALID_ARGUMENT, thrown.getErrorCode());
686+
exceptionObservedLatch.countDown();
687+
try {
688+
assertTrue(cancelCalledLatch.await(30, TimeUnit.SECONDS));
689+
} catch (InterruptedException interruptedException) {
690+
Thread.currentThread().interrupt();
691+
throw new RuntimeException(interruptedException);
692+
}
693+
return CallbackResponse.DONE;
694+
});
695+
696+
assertTrue(exceptionObservedLatch.await(30, TimeUnit.SECONDS));
697+
resultSet.cancel();
698+
cancelCalledLatch.countDown();
699+
ExecutionException executionException =
700+
assertThrows(ExecutionException.class, () -> finished.get(30, TimeUnit.SECONDS));
701+
assertEquals(
702+
ErrorCode.INVALID_ARGUMENT,
703+
((SpannerException) executionException.getCause()).getErrorCode());
704+
} finally {
705+
cancelCalledLatch.countDown();
706+
}
707+
}
708+
627709
private Spanner createSingleThreadSpanner(
628710
SpannerOptions.CloseableExecutorProvider asyncExecutorProvider) {
629711
return SpannerOptions.newBuilder()

0 commit comments

Comments
 (0)