Search in sources :

Example 31 with TransactionContextFuture

use of com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture in project java-spanner by googleapis.

the class AsyncTransactionManagerTest method asyncTransactionManagerRead.

@Test
public void asyncTransactionManagerRead() throws Exception {
    try (AsyncTransactionManager manager = client().transactionManagerAsync()) {
        TransactionContextFuture transactionContextFuture = manager.beginAsync();
        while (true) {
            try {
                AsyncTransactionStep<Void, List<String>> values = transactionContextFuture.then((transactionContext, ignored) -> transactionContext.readAsync(READ_TABLE_NAME, KeySet.all(), READ_COLUMN_NAMES).toListAsync(input -> input.getString("Value"), MoreExecutors.directExecutor()), executor);
                // Commit the transaction.
                values.commitAsync().get();
                assertThat(values.get()).containsExactly("v1", "v2", "v3");
                break;
            } catch (AbortedException e) {
                transactionContextFuture = manager.resetForRetryAsync();
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) BatchCreateSessionsRequest(com.google.spanner.v1.BatchCreateSessionsRequest) TimeoutException(java.util.concurrent.TimeoutException) StatementResult(com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) UPDATE_STATEMENT(com.google.cloud.spanner.MockSpannerTestUtil.UPDATE_STATEMENT) TransactionSelector(com.google.spanner.v1.TransactionSelector) Status(io.grpc.Status) BeginTransactionRequest(com.google.spanner.v1.BeginTransactionRequest) Parameterized(org.junit.runners.Parameterized) CommitTimestampFuture(com.google.cloud.spanner.AsyncTransactionManager.CommitTimestampFuture) ApiFutures(com.google.api.core.ApiFutures) SpannerApiFutures.get(com.google.cloud.spanner.SpannerApiFutures.get) Collection(java.util.Collection) READ_COLUMN_NAMES(com.google.cloud.spanner.MockSpannerTestUtil.READ_COLUMN_NAMES) Range(com.google.common.collect.Range) ApiFutureCallback(com.google.api.core.ApiFutureCallback) Executors(java.util.concurrent.Executors) ApiFuture(com.google.api.core.ApiFuture) SettableApiFuture(com.google.api.core.SettableApiFuture) UPDATE_COUNT(com.google.cloud.spanner.MockSpannerTestUtil.UPDATE_COUNT) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ExecuteSqlRequest(com.google.spanner.v1.ExecuteSqlRequest) Iterables(com.google.common.collect.Iterables) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) INVALID_UPDATE_STATEMENT(com.google.cloud.spanner.MockSpannerTestUtil.INVALID_UPDATE_STATEMENT) READ_TABLE_NAME(com.google.cloud.spanner.MockSpannerTestUtil.READ_TABLE_NAME) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) CommitRequest(com.google.spanner.v1.CommitRequest) ImmutableList(com.google.common.collect.ImmutableList) SimulatedExecutionTime(com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) AbstractMessage(com.google.protobuf.AbstractMessage) Executor(java.util.concurrent.Executor) Assert.assertNotNull(org.junit.Assert.assertNotNull) Parameter(org.junit.runners.Parameterized.Parameter) Test(org.junit.Test) Truth.assertThat(com.google.common.truth.Truth.assertThat) RollbackRequest(com.google.spanner.v1.RollbackRequest) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ReadOption(com.google.cloud.spanner.Options.ReadOption) AsyncTransactionFunction(com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionFunction) AsyncTransactionStep(com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep) SessionPoolTransactionContext(com.google.cloud.spanner.SessionPool.SessionPoolTransactionContext) UPDATE_ABORTED_STATEMENT(com.google.cloud.spanner.MockSpannerTestUtil.UPDATE_ABORTED_STATEMENT) TransactionContextImpl(com.google.cloud.spanner.TransactionRunnerImpl.TransactionContextImpl) ExecuteBatchDmlRequest(com.google.spanner.v1.ExecuteBatchDmlRequest) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) Test(org.junit.Test)

Example 32 with TransactionContextFuture

use of com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture in project java-spanner by googleapis.

the class DatabaseClientImplTest method testAsyncTransactionManagerCommitWithTag.

@Test
public void testAsyncTransactionManagerCommitWithTag() {
    DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE));
    try (AsyncTransactionManager manager = client.transactionManagerAsync(Options.tag("app=spanner,env=test,action=manager"))) {
        TransactionContextFuture transaction = manager.beginAsync();
        get(transaction.then((txn, input) -> {
            txn.buffer(Mutation.delete("TEST", KeySet.all()));
            return ApiFutures.immediateFuture(null);
        }, executor).commitAsync());
    }
    List<CommitRequest> requests = mockSpanner.getRequestsOfType(CommitRequest.class);
    assertThat(requests).hasSize(1);
    CommitRequest request = requests.get(0);
    assertNotNull(request.getRequestOptions());
    assertThat(request.getRequestOptions().getRequestTag()).isEmpty();
    assertThat(request.getRequestOptions().getTransactionTag()).isEqualTo("app=spanner,env=test,action=manager");
}
Also used : CommitRequest(com.google.spanner.v1.CommitRequest) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) Test(org.junit.Test)

Example 33 with TransactionContextFuture

use of com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture in project java-spanner by googleapis.

the class RetryOnInvalidatedSessionTest method asyncTransactionManager_readSync.

private void asyncTransactionManager_readSync(final Function<TransactionContext, ResultSet> fn) throws InterruptedException {
    final ExecutorService queryExecutor = Executors.newSingleThreadExecutor();
    try (AsyncTransactionManager manager = client.transactionManagerAsync()) {
        TransactionContextFuture context = manager.beginAsync();
        while (true) {
            try {
                AsyncTransactionStep<Void, Long> count = context.then((transaction, ignored) -> {
                    long counter = 0L;
                    try (ResultSet rs = fn.apply(transaction)) {
                        while (rs.next()) {
                            counter++;
                        }
                    }
                    return ApiFutures.immediateFuture(counter);
                }, executor);
                CommitTimestampFuture ts = count.commitAsync();
                assertThrowsSessionNotFoundIfShouldFail(() -> get(ts));
                break;
            } catch (AbortedException e) {
                context = manager.resetForRetryAsync();
            }
        }
    } finally {
        queryExecutor.shutdown();
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) AtomicLong(java.util.concurrent.atomic.AtomicLong) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) CommitTimestampFuture(com.google.cloud.spanner.AsyncTransactionManager.CommitTimestampFuture)

Example 34 with TransactionContextFuture

use of com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture in project java-spanner by googleapis.

the class RetryOnInvalidatedSessionTest method asyncTransactionManager_updateFunction.

private <T> void asyncTransactionManager_updateFunction(final Function<TransactionContext, ApiFuture<T>> fn, T expected) throws InterruptedException {
    try (AsyncTransactionManager manager = client.transactionManagerAsync()) {
        TransactionContextFuture transaction = manager.beginAsync();
        while (true) {
            try {
                AsyncTransactionStep<Void, T> res = transaction.then((txn, input) -> fn.apply(txn), executor);
                CommitTimestampFuture ts = res.commitAsync();
                assertThrowsSessionNotFoundIfShouldFail(() -> get(ts));
                break;
            } catch (AbortedException e) {
                transaction = manager.resetForRetryAsync();
            }
        }
    }
}
Also used : TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) CommitTimestampFuture(com.google.cloud.spanner.AsyncTransactionManager.CommitTimestampFuture)

Example 35 with TransactionContextFuture

use of com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture in project java-spanner by googleapis.

the class ITTransactionManagerAsyncTest method testInvalidInsert.

@Test
public void testInvalidInsert() throws InterruptedException {
    try (AsyncTransactionManager manager = client.transactionManagerAsync()) {
        TransactionContextFuture txn = manager.beginAsync();
        while (true) {
            try {
                txn.then((transaction, ignored) -> {
                    transaction.buffer(Mutation.newInsertBuilder("InvalidTable").set("K").to("Key1").set("BoolValue").to(true).build());
                    return ApiFutures.immediateFuture(null);
                }, executor).commitAsync().get();
                fail("Expected exception");
            } catch (AbortedException e) {
                Thread.sleep(e.getRetryDelayInMillis());
                txn = manager.resetForRetryAsync();
            } catch (ExecutionException e) {
                assertThat(e.getCause()).isInstanceOf(SpannerException.class);
                SpannerException se = (SpannerException) e.getCause();
                assertThat(se.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
                // expected
                break;
            }
        }
        assertThat(manager.getState()).isEqualTo(TransactionState.COMMIT_FAILED);
        // We cannot retry for non aborted errors.
        try {
            manager.resetForRetryAsync();
            fail("Expected exception");
        } catch (IllegalStateException ex) {
            assertNotNull(ex.getMessage());
        }
    }
}
Also used : AsyncTransactionManager(com.google.cloud.spanner.AsyncTransactionManager) AbortedException(com.google.cloud.spanner.AbortedException) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) SpannerException(com.google.cloud.spanner.SpannerException) ExecutionException(java.util.concurrent.ExecutionException) ParallelIntegrationTest(com.google.cloud.spanner.ParallelIntegrationTest) Test(org.junit.Test)

Aggregations

TransactionContextFuture (com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture)37 Test (org.junit.Test)32 CommitTimestampFuture (com.google.cloud.spanner.AsyncTransactionManager.CommitTimestampFuture)23 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)17 ExecutionException (java.util.concurrent.ExecutionException)16 ApiFutures (com.google.api.core.ApiFutures)15 AsyncTransactionStep (com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep)15 ImmutableList (com.google.common.collect.ImmutableList)15 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)15 CommitRequest (com.google.spanner.v1.CommitRequest)15 Arrays (java.util.Arrays)15 ApiFuture (com.google.api.core.ApiFuture)14 Truth.assertThat (com.google.common.truth.Truth.assertThat)14 Collection (java.util.Collection)14 Collections (java.util.Collections)14 ApiFutureCallback (com.google.api.core.ApiFutureCallback)13 SettableApiFuture (com.google.api.core.SettableApiFuture)13 AsyncTransactionFunction (com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionFunction)13 SimulatedExecutionTime (com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime)13 StatementResult (com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult)13