Search in sources :

Example 11 with SessionConsumerImpl

use of com.google.cloud.spanner.SessionPool.SessionConsumerImpl in project java-spanner by googleapis.

the class SessionPoolTest method testSessionNotFoundWrite.

@Test
public void testSessionNotFoundWrite() {
    SpannerException sessionNotFound = SpannerExceptionFactoryTest.newSessionNotFoundException(sessionName);
    List<Mutation> mutations = Collections.singletonList(Mutation.newInsertBuilder("FOO").build());
    final SessionImpl closedSession = mockSession();
    when(closedSession.writeWithOptions(mutations)).thenThrow(sessionNotFound);
    final SessionImpl openSession = mockSession();
    com.google.cloud.spanner.CommitResponse response = mock(com.google.cloud.spanner.CommitResponse.class);
    when(response.getCommitTimestamp()).thenReturn(Timestamp.now());
    when(openSession.writeWithOptions(mutations)).thenReturn(response);
    doAnswer(invocation -> {
        executor.submit(() -> {
            SessionConsumerImpl consumer = invocation.getArgument(2, SessionConsumerImpl.class);
            consumer.onSessionReady(closedSession);
        });
        return null;
    }).doAnswer(invocation -> {
        executor.submit(() -> {
            SessionConsumerImpl consumer = invocation.getArgument(2, SessionConsumerImpl.class);
            consumer.onSessionReady(openSession);
        });
        return null;
    }).when(sessionClient).asyncBatchCreateSessions(Mockito.eq(1), Mockito.anyBoolean(), any(SessionConsumer.class));
    FakeClock clock = new FakeClock();
    clock.currentTimeMillis = System.currentTimeMillis();
    pool = createPool(clock);
    DatabaseClientImpl impl = new DatabaseClientImpl(pool);
    assertThat(impl.write(mutations)).isNotNull();
}
Also used : TransactionCallable(com.google.cloud.spanner.TransactionRunner.TransactionCallable) Arrays(java.util.Arrays) ClosedException(com.google.cloud.spanner.SpannerImpl.ClosedException) QueryAnalyzeMode(com.google.cloud.spanner.ReadContext.QueryAnalyzeMode) CommitResponse(com.google.spanner.v1.CommitResponse) Timestamp(com.google.cloud.Timestamp) Clock(com.google.cloud.spanner.SessionPool.Clock) PooledSession(com.google.cloud.spanner.SessionPool.PooledSession) Mockito.doThrow(org.mockito.Mockito.doThrow) Empty(com.google.protobuf.Empty) ResultSetStats(com.google.spanner.v1.ResultSetStats) Future(java.util.concurrent.Future) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) Parameterized(org.junit.runners.Parameterized) ResultStreamConsumer(com.google.cloud.spanner.spi.v1.SpannerRpc.ResultStreamConsumer) PrintWriter(java.io.PrintWriter) PointWithFunction(com.google.cloud.spanner.MetricRegistryTestUtils.PointWithFunction) ApiFutures(com.google.api.core.ApiFutures) Collection(java.util.Collection) NUM_READ_SESSIONS(com.google.cloud.spanner.MetricRegistryConstants.NUM_READ_SESSIONS) Executors(java.util.concurrent.Executors) ByteString(com.google.protobuf.ByteString) CountDownLatch(java.util.concurrent.CountDownLatch) NUM_SESSIONS_BEING_PREPARED(com.google.cloud.spanner.MetricRegistryConstants.NUM_SESSIONS_BEING_PREPARED) List(java.util.List) LabelValue(io.opencensus.metrics.LabelValue) Mockito.atMost(org.mockito.Mockito.atMost) ExecuteSqlRequest(com.google.spanner.v1.ExecuteSqlRequest) Mockito.any(org.mockito.Mockito.any) MetricRegistry(io.opencensus.metrics.MetricRegistry) SPANNER_LABEL_KEYS_WITH_TYPE(com.google.cloud.spanner.MetricRegistryConstants.SPANNER_LABEL_KEYS_WITH_TYPE) Mockito.eq(org.mockito.Mockito.eq) Mockito.mock(org.mockito.Mockito.mock) MockitoAnnotations.initMocks(org.mockito.MockitoAnnotations.initMocks) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Mock(org.mockito.Mock) SPANNER_LABEL_KEYS(com.google.cloud.spanner.MetricRegistryConstants.SPANNER_LABEL_KEYS) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) SpannerRpc(com.google.cloud.spanner.spi.v1.SpannerRpc) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) CommitRequest(com.google.spanner.v1.CommitRequest) PooledSessionFuture(com.google.cloud.spanner.SessionPool.PooledSessionFuture) MetricsRecord(com.google.cloud.spanner.MetricRegistryTestUtils.MetricsRecord) SessionConsumerImpl(com.google.cloud.spanner.SessionPool.SessionConsumerImpl) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) FakeMetricRegistry(com.google.cloud.spanner.MetricRegistryTestUtils.FakeMetricRegistry) Uninterruptibles(com.google.common.util.concurrent.Uninterruptibles) NUM_IN_USE_SESSIONS(com.google.cloud.spanner.MetricRegistryConstants.NUM_IN_USE_SESSIONS) Assert.assertNotNull(org.junit.Assert.assertNotNull) Parameter(org.junit.runners.Parameterized.Parameter) StringWriter(java.io.StringWriter) Assert.assertTrue(org.junit.Assert.assertTrue) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Span(io.opencensus.trace.Span) Mockito.verify(org.mockito.Mockito.verify) RollbackRequest(com.google.spanner.v1.RollbackRequest) NUM_WRITE_SESSIONS(com.google.cloud.spanner.MetricRegistryConstants.NUM_WRITE_SESSIONS) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) Mockito.anyInt(org.mockito.Mockito.anyInt) TransactionContextImpl(com.google.cloud.spanner.TransactionRunnerImpl.TransactionContextImpl) ExecuteBatchDmlRequest(com.google.spanner.v1.ExecuteBatchDmlRequest) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) SessionConsumer(com.google.cloud.spanner.SessionClient.SessionConsumer) SessionConsumer(com.google.cloud.spanner.SessionClient.SessionConsumer) SessionConsumerImpl(com.google.cloud.spanner.SessionPool.SessionConsumerImpl) Test(org.junit.Test)

Example 12 with SessionConsumerImpl

use of com.google.cloud.spanner.SessionPool.SessionConsumerImpl in project java-spanner by googleapis.

the class SessionPoolTest method poolClosureFailsNewRequests.

@Test
public void poolClosureFailsNewRequests() {
    final SessionImpl session = mockSession();
    doAnswer(invocation -> {
        executor.submit(() -> {
            SessionConsumerImpl consumer = invocation.getArgument(2, SessionConsumerImpl.class);
            consumer.onSessionReady(session);
        });
        return null;
    }).when(sessionClient).asyncBatchCreateSessions(Mockito.eq(1), Mockito.anyBoolean(), any(SessionConsumer.class));
    pool = createPool();
    PooledSessionFuture leakedSession = pool.getSession();
    leakedSession.get();
    // Suppress expected leakedSession warning.
    leakedSession.clearLeakedException();
    pool.closeAsync(new SpannerImpl.ClosedException());
    IllegalStateException e = assertThrows(IllegalStateException.class, () -> pool.getSession());
    assertNotNull(e.getMessage());
}
Also used : SessionConsumer(com.google.cloud.spanner.SessionClient.SessionConsumer) SessionConsumerImpl(com.google.cloud.spanner.SessionPool.SessionConsumerImpl) PooledSessionFuture(com.google.cloud.spanner.SessionPool.PooledSessionFuture) ClosedException(com.google.cloud.spanner.SpannerImpl.ClosedException) Test(org.junit.Test)

Example 13 with SessionConsumerImpl

use of com.google.cloud.spanner.SessionPool.SessionConsumerImpl in project java-spanner by googleapis.

the class SessionPoolTest method keepAlive.

@Test
public void keepAlive() throws Exception {
    options = SessionPoolOptions.newBuilder().setMinSessions(2).setMaxSessions(3).build();
    final SessionImpl session = mockSession();
    mockKeepAlive(session);
    // This is cheating as we are returning the same session each but it makes the verification
    // easier.
    doAnswer(invocation -> {
        executor.submit(() -> {
            int sessionCount = invocation.getArgument(0, Integer.class);
            SessionConsumerImpl consumer = invocation.getArgument(2, SessionConsumerImpl.class);
            for (int i = 0; i < sessionCount; i++) {
                consumer.onSessionReady(session);
            }
        });
        return null;
    }).when(sessionClient).asyncBatchCreateSessions(anyInt(), Mockito.anyBoolean(), any(SessionConsumer.class));
    FakeClock clock = new FakeClock();
    clock.currentTimeMillis = System.currentTimeMillis();
    pool = createPool(clock);
    PooledSessionFuture session1 = pool.getSession();
    PooledSessionFuture session2 = pool.getSession();
    session1.get();
    session2.get();
    session1.close();
    session2.close();
    runMaintenanceLoop(clock, pool, pool.poolMaintainer.numKeepAliveCycles);
    verify(session, never()).singleUse(any(TimestampBound.class));
    runMaintenanceLoop(clock, pool, pool.poolMaintainer.numKeepAliveCycles);
    verify(session, times(2)).singleUse(any(TimestampBound.class));
    clock.currentTimeMillis += clock.currentTimeMillis + (options.getKeepAliveIntervalMinutes() + 5) * 60 * 1000;
    session1 = pool.getSession();
    session1.writeAtLeastOnceWithOptions(new ArrayList<>());
    session1.close();
    runMaintenanceLoop(clock, pool, pool.poolMaintainer.numKeepAliveCycles);
    // The session pool only keeps MinSessions + MaxIdleSessions alive.
    verify(session, times(options.getMinSessions() + options.getMaxIdleSessions())).singleUse(any(TimestampBound.class));
    pool.closeAsync(new SpannerImpl.ClosedException()).get(5L, TimeUnit.SECONDS);
}
Also used : SessionConsumer(com.google.cloud.spanner.SessionClient.SessionConsumer) SessionConsumerImpl(com.google.cloud.spanner.SessionPool.SessionConsumerImpl) ClosedException(com.google.cloud.spanner.SpannerImpl.ClosedException) PooledSessionFuture(com.google.cloud.spanner.SessionPool.PooledSessionFuture) Test(org.junit.Test)

Example 14 with SessionConsumerImpl

use of com.google.cloud.spanner.SessionPool.SessionConsumerImpl in project java-spanner by googleapis.

the class SessionPoolTest method poolClosesEvenIfCreationFails.

@Test
public void poolClosesEvenIfCreationFails() throws Exception {
    final CountDownLatch insideCreation = new CountDownLatch(1);
    final CountDownLatch releaseCreation = new CountDownLatch(1);
    doAnswer(invocation -> {
        executor.submit(() -> {
            insideCreation.countDown();
            releaseCreation.await();
            SessionConsumerImpl consumer = invocation.getArgument(2, SessionConsumerImpl.class);
            consumer.onSessionCreateFailure(SpannerExceptionFactory.newSpannerException(new RuntimeException()), 1);
            return null;
        });
        return null;
    }).when(sessionClient).asyncBatchCreateSessions(Mockito.eq(1), Mockito.anyBoolean(), any(SessionConsumer.class));
    pool = createPool();
    AtomicBoolean failed = new AtomicBoolean(false);
    CountDownLatch latch = new CountDownLatch(1);
    getSessionAsync(latch, failed);
    insideCreation.await();
    ListenableFuture<Void> f = pool.closeAsync(new SpannerImpl.ClosedException());
    releaseCreation.countDown();
    f.get();
    assertThat(f.isDone()).isTrue();
}
Also used : SessionConsumer(com.google.cloud.spanner.SessionClient.SessionConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SessionConsumerImpl(com.google.cloud.spanner.SessionPool.SessionConsumerImpl) ClosedException(com.google.cloud.spanner.SpannerImpl.ClosedException) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 15 with SessionConsumerImpl

use of com.google.cloud.spanner.SessionPool.SessionConsumerImpl in project java-spanner by googleapis.

the class SessionPoolMaintainerTest method setupMockSessionCreation.

private void setupMockSessionCreation() {
    doAnswer(invocation -> {
        executor.submit(() -> {
            int sessionCount = invocation.getArgument(0, Integer.class);
            SessionConsumerImpl consumer = invocation.getArgument(2, SessionConsumerImpl.class);
            for (int i = 0; i < sessionCount; i++) {
                consumer.onSessionReady(setupMockSession(mockSession()));
            }
        });
        return null;
    }).when(sessionClient).asyncBatchCreateSessions(Mockito.anyInt(), Mockito.anyBoolean(), any(SessionConsumer.class));
}
Also used : SessionConsumer(com.google.cloud.spanner.SessionClient.SessionConsumer) SessionConsumerImpl(com.google.cloud.spanner.SessionPool.SessionConsumerImpl)

Aggregations

SessionConsumer (com.google.cloud.spanner.SessionClient.SessionConsumer)18 SessionConsumerImpl (com.google.cloud.spanner.SessionPool.SessionConsumerImpl)18 Test (org.junit.Test)15 ClosedException (com.google.cloud.spanner.SpannerImpl.ClosedException)13 PooledSessionFuture (com.google.cloud.spanner.SessionPool.PooledSessionFuture)12 PooledSession (com.google.cloud.spanner.SessionPool.PooledSession)10 ApiFutures (com.google.api.core.ApiFutures)8 Timestamp (com.google.cloud.Timestamp)8 NUM_IN_USE_SESSIONS (com.google.cloud.spanner.MetricRegistryConstants.NUM_IN_USE_SESSIONS)8 NUM_READ_SESSIONS (com.google.cloud.spanner.MetricRegistryConstants.NUM_READ_SESSIONS)8 NUM_SESSIONS_BEING_PREPARED (com.google.cloud.spanner.MetricRegistryConstants.NUM_SESSIONS_BEING_PREPARED)8 NUM_WRITE_SESSIONS (com.google.cloud.spanner.MetricRegistryConstants.NUM_WRITE_SESSIONS)8 SPANNER_LABEL_KEYS (com.google.cloud.spanner.MetricRegistryConstants.SPANNER_LABEL_KEYS)8 SPANNER_LABEL_KEYS_WITH_TYPE (com.google.cloud.spanner.MetricRegistryConstants.SPANNER_LABEL_KEYS_WITH_TYPE)8 FakeMetricRegistry (com.google.cloud.spanner.MetricRegistryTestUtils.FakeMetricRegistry)8 MetricsRecord (com.google.cloud.spanner.MetricRegistryTestUtils.MetricsRecord)8 PointWithFunction (com.google.cloud.spanner.MetricRegistryTestUtils.PointWithFunction)8 QueryAnalyzeMode (com.google.cloud.spanner.ReadContext.QueryAnalyzeMode)8 Clock (com.google.cloud.spanner.SessionPool.Clock)8 TransactionCallable (com.google.cloud.spanner.TransactionRunner.TransactionCallable)8