Search in sources :

Example 16 with TransactionContextFuture

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

the class DatabaseClientImplTest method testAsyncTransactionManagerCommitWithPriority.

@Test
public void testAsyncTransactionManagerCommitWithPriority() {
    DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE));
    try (AsyncTransactionManager manager = client.transactionManagerAsync(Options.priority(RpcPriority.HIGH))) {
        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());
    assertEquals(Priority.PRIORITY_HIGH, request.getRequestOptions().getPriority());
}
Also used : CommitRequest(com.google.spanner.v1.CommitRequest) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) Test(org.junit.Test)

Example 17 with TransactionContextFuture

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

the class RetryOnInvalidatedSessionTest method asyncTransactionManager_readAsync.

private void asyncTransactionManager_readAsync(final Function<TransactionContext, AsyncResultSet> fn) throws InterruptedException {
    final ExecutorService queryExecutor = Executors.newSingleThreadExecutor();
    try (AsyncTransactionManager manager = client.transactionManagerAsync()) {
        TransactionContextFuture context = manager.beginAsync();
        while (true) {
            try {
                final AtomicLong counter = new AtomicLong();
                AsyncTransactionStep<Void, Long> count = context.then((transaction, ignored) -> {
                    AsyncResultSet rs = fn.apply(transaction);
                    ApiFuture<Void> fut = rs.setCallback(queryExecutor, resultSet -> {
                        while (true) {
                            switch(resultSet.tryNext()) {
                                case OK:
                                    counter.incrementAndGet();
                                    break;
                                case DONE:
                                    return CallbackResponse.DONE;
                                case NOT_READY:
                                    return CallbackResponse.CONTINUE;
                            }
                        }
                    });
                    return ApiFutures.transform(fut, input -> counter.get(), MoreExecutors.directExecutor());
                }, executor);
                CommitTimestampFuture ts = count.commitAsync();
                assertThrowsSessionNotFoundIfShouldFail(() -> get(ts));
                break;
            } catch (AbortedException e) {
                context = manager.resetForRetryAsync();
            }
        }
    } finally {
        queryExecutor.shutdown();
    }
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) 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 18 with TransactionContextFuture

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

the class RetryOnInvalidatedSessionTest method asyncTransactionManager_readRowFunction.

private void asyncTransactionManager_readRowFunction(final Function<TransactionContext, ApiFuture<Struct>> fn) throws InterruptedException {
    final ExecutorService queryExecutor = Executors.newSingleThreadExecutor();
    try (AsyncTransactionManager manager = client.transactionManagerAsync()) {
        TransactionContextFuture context = manager.beginAsync();
        while (true) {
            try {
                AsyncTransactionStep<Void, Struct> row = context.then((transaction, ignored) -> fn.apply(transaction), executor);
                CommitTimestampFuture ts = row.commitAsync();
                assertThrowsSessionNotFoundIfShouldFail(() -> get(ts));
                break;
            } catch (AbortedException e) {
                context = manager.resetForRetryAsync();
            }
        }
    } finally {
        queryExecutor.shutdown();
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) CommitTimestampFuture(com.google.cloud.spanner.AsyncTransactionManager.CommitTimestampFuture)

Example 19 with TransactionContextFuture

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

the class ITAsyncAPITest method testAsyncTransactionManagerReturnsCommitStats.

@Test
public void testAsyncTransactionManagerReturnsCommitStats() throws InterruptedException {
    assumeFalse("Emulator does not return commit statistics", isUsingEmulator());
    try (AsyncTransactionManager manager = client.transactionManagerAsync(Options.commitStats())) {
        TransactionContextFuture context = manager.beginAsync();
        while (true) {
            try {
                get(context.then((transaction, ignored) -> {
                    transaction.buffer(Mutation.newInsertOrUpdateBuilder(TABLE_NAME).set("Key").to("k_commit_stats").set("StringValue").to("Should return commit stats").build());
                    return ApiFutures.immediateFuture(null);
                }, executor).commitAsync());
                assertNotNull(get(manager.getCommitResponse()).getCommitStats());
                assertEquals(4L, get(manager.getCommitResponse()).getCommitStats().getMutationCount());
                break;
            } catch (AbortedException e) {
                Thread.sleep(e.getRetryDelayInMillis());
                context = manager.resetForRetryAsync();
            }
        }
    }
}
Also used : AsyncTransactionManager(com.google.cloud.spanner.AsyncTransactionManager) AbortedException(com.google.cloud.spanner.AbortedException) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) SerialIntegrationTest(com.google.cloud.spanner.SerialIntegrationTest) Test(org.junit.Test)

Example 20 with TransactionContextFuture

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

the class ITTransactionManagerAsyncTest method testAbortAndRetry.

@Ignore("Cloud Spanner now seems to return CANCELLED instead of ABORTED when a transaction is invalidated by a later transaction in the same session")
@Test
public void testAbortAndRetry() throws InterruptedException, ExecutionException {
    assumeFalse("Emulator does not support more than 1 simultaneous transaction. " + "This test would therefore loop indefinitely on the emulator.", isUsingEmulator());
    client.write(Collections.singletonList(Mutation.newInsertBuilder("T").set("K").to("Key3").set("BoolValue").to(true).build()));
    try (AsyncTransactionManager manager1 = client.transactionManagerAsync()) {
        TransactionContextFuture txn1 = manager1.beginAsync();
        AsyncTransactionManager manager2;
        TransactionContextFuture txn2;
        AsyncTransactionStep<Void, Struct> txn2Step1;
        while (true) {
            try {
                AsyncTransactionStep<Void, Struct> txn1Step1 = txn1.then((transaction, ignored) -> transaction.readRowAsync("T", Key.of("Key3"), Arrays.asList("K", "BoolValue")), executor);
                manager2 = client.transactionManagerAsync();
                txn2 = manager2.beginAsync();
                txn2Step1 = txn2.then((transaction, ignored) -> transaction.readRowAsync("T", Key.of("Key3"), Arrays.asList("K", "BoolValue")), executor);
                AsyncTransactionStep<Struct, Void> txn1Step2 = txn1Step1.then((transaction, ignored) -> {
                    transaction.buffer(Mutation.newUpdateBuilder("T").set("K").to("Key3").set("BoolValue").to(false).build());
                    return ApiFutures.immediateFuture(null);
                }, executor);
                txn2Step1.get();
                txn1Step2.commitAsync().get();
                break;
            } catch (AbortedException e) {
                Thread.sleep(e.getRetryDelayInMillis());
                // In that case we should just retry without resetting anything.
                if (manager1.getState() == TransactionState.ABORTED) {
                    txn1 = manager1.resetForRetryAsync();
                }
            }
        }
        // txn2 should have been aborted.
        try {
            txn2Step1.commitAsync().get();
            fail("Expected to abort");
        } catch (AbortedException e) {
            assertThat(manager2.getState()).isEqualTo(TransactionState.ABORTED);
            txn2 = manager2.resetForRetryAsync();
        }
        AsyncTransactionStep<Void, Void> txn2Step2 = txn2.then((transaction, ignored) -> {
            transaction.buffer(Mutation.newUpdateBuilder("T").set("K").to("Key3").set("BoolValue").to(true).build());
            return ApiFutures.immediateFuture(null);
        }, executor);
        txn2Step2.commitAsync().get();
        Struct row = client.singleUse().readRow("T", Key.of("Key3"), Arrays.asList("K", "BoolValue"));
        assertThat(row.getString(0)).isEqualTo("Key3");
        assertThat(row.getBoolean(1)).isTrue();
        manager2.close();
    }
}
Also used : MoreExecutors(com.google.common.util.concurrent.MoreExecutors) Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) Assume.assumeFalse(org.junit.Assume.assumeFalse) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) TransactionState(com.google.cloud.spanner.TransactionManager.TransactionState) DatabaseClient(com.google.cloud.spanner.DatabaseClient) Spanner(com.google.cloud.spanner.Spanner) ImmutableList(com.google.common.collect.ImmutableList) AsyncTransactionManager(com.google.cloud.spanner.AsyncTransactionManager) Key(com.google.cloud.spanner.Key) Assert.fail(org.junit.Assert.fail) ClassRule(org.junit.ClassRule) Parameterized(org.junit.runners.Parameterized) Before(org.junit.Before) AbortedException(com.google.cloud.spanner.AbortedException) ParallelIntegrationTest(com.google.cloud.spanner.ParallelIntegrationTest) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) ApiFutures(com.google.api.core.ApiFutures) Database(com.google.cloud.spanner.Database) Executor(java.util.concurrent.Executor) Assert.assertNotNull(org.junit.Assert.assertNotNull) Parameter(org.junit.runners.Parameterized.Parameter) Collection(java.util.Collection) EmulatorSpannerHelper.isUsingEmulator(com.google.cloud.spanner.testing.EmulatorSpannerHelper.isUsingEmulator) Test(org.junit.Test) Mutation(com.google.cloud.spanner.Mutation) Truth.assertThat(com.google.common.truth.Truth.assertThat) Category(org.junit.experimental.categories.Category) Executors(java.util.concurrent.Executors) IntegrationTestEnv(com.google.cloud.spanner.IntegrationTestEnv) KeySet(com.google.cloud.spanner.KeySet) ErrorCode(com.google.cloud.spanner.ErrorCode) SpannerException(com.google.cloud.spanner.SpannerException) ExecutionException(java.util.concurrent.ExecutionException) Ignore(org.junit.Ignore) Struct(com.google.cloud.spanner.Struct) AsyncTransactionStep(com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep) Collections(java.util.Collections) AsyncTransactionManager(com.google.cloud.spanner.AsyncTransactionManager) AbortedException(com.google.cloud.spanner.AbortedException) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) Struct(com.google.cloud.spanner.Struct) Ignore(org.junit.Ignore) 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