|
| 1 | +/* |
| 2 | + * Copyright 2023 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.google.cloud.spanner; |
| 17 | + |
| 18 | +import static com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_RESULTSET; |
| 19 | +import static com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_STATEMENT; |
| 20 | +import static com.google.cloud.spanner.MockSpannerTestUtil.SELECT1; |
| 21 | +import static org.junit.Assert.assertEquals; |
| 22 | +import static org.junit.Assert.assertThrows; |
| 23 | + |
| 24 | +import com.google.api.gax.grpc.testing.LocalChannelProvider; |
| 25 | +import com.google.cloud.NoCredentials; |
| 26 | +import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime; |
| 27 | +import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; |
| 28 | +import com.google.common.util.concurrent.Futures; |
| 29 | +import com.google.common.util.concurrent.ListenableFuture; |
| 30 | +import com.google.common.util.concurrent.ListeningExecutorService; |
| 31 | +import com.google.common.util.concurrent.MoreExecutors; |
| 32 | +import io.grpc.Server; |
| 33 | +import io.grpc.inprocess.InProcessServerBuilder; |
| 34 | +import java.io.IOException; |
| 35 | +import java.util.ArrayList; |
| 36 | +import java.util.List; |
| 37 | +import java.util.concurrent.Executors; |
| 38 | +import java.util.concurrent.ScheduledThreadPoolExecutor; |
| 39 | +import java.util.concurrent.atomic.AtomicInteger; |
| 40 | +import org.junit.After; |
| 41 | +import org.junit.AfterClass; |
| 42 | +import org.junit.Before; |
| 43 | +import org.junit.BeforeClass; |
| 44 | +import org.junit.Test; |
| 45 | +import org.junit.experimental.categories.Category; |
| 46 | +import org.junit.runner.RunWith; |
| 47 | +import org.junit.runners.JUnit4; |
| 48 | +import org.threeten.bp.Duration; |
| 49 | + |
| 50 | +@Category(SlowTest.class) |
| 51 | +@RunWith(JUnit4.class) |
| 52 | +public class BatchCreateSessionsSlowTest { |
| 53 | + private static final String TEST_PROJECT = "my-project"; |
| 54 | + private static final String TEST_DATABASE_ROLE = "my-role"; |
| 55 | + private static MockSpannerServiceImpl mockSpanner; |
| 56 | + private static Server server; |
| 57 | + private static LocalChannelProvider channelProvider; |
| 58 | + private Spanner spanner; |
| 59 | + |
| 60 | + @BeforeClass |
| 61 | + public static void startStaticServer() throws IOException { |
| 62 | + mockSpanner = new MockSpannerServiceImpl(); |
| 63 | + mockSpanner.setAbortProbability(0.0D); // We don't want any unpredictable aborted transactions. |
| 64 | + mockSpanner.putStatementResult( |
| 65 | + StatementResult.query(SELECT1, MockSpannerTestUtil.SELECT1_RESULTSET)); |
| 66 | + mockSpanner.putStatementResult( |
| 67 | + StatementResult.query(READ_ONE_KEY_VALUE_STATEMENT, READ_ONE_KEY_VALUE_RESULTSET)); |
| 68 | + |
| 69 | + String uniqueName = InProcessServerBuilder.generateName(); |
| 70 | + server = |
| 71 | + InProcessServerBuilder.forName(uniqueName) |
| 72 | + // We need to use a real executor for timeouts to occur. |
| 73 | + .scheduledExecutorService(new ScheduledThreadPoolExecutor(1)) |
| 74 | + .addService(mockSpanner) |
| 75 | + .build() |
| 76 | + .start(); |
| 77 | + channelProvider = LocalChannelProvider.create(uniqueName); |
| 78 | + } |
| 79 | + |
| 80 | + @AfterClass |
| 81 | + public static void stopServer() throws InterruptedException { |
| 82 | + server.shutdown(); |
| 83 | + server.awaitTermination(); |
| 84 | + } |
| 85 | + |
| 86 | + @Before |
| 87 | + public void setUp() { |
| 88 | + spanner = |
| 89 | + SpannerOptions.newBuilder() |
| 90 | + .setProjectId(TEST_PROJECT) |
| 91 | + .setDatabaseRole(TEST_DATABASE_ROLE) |
| 92 | + .setChannelProvider(channelProvider) |
| 93 | + .setCredentials(NoCredentials.getInstance()) |
| 94 | + .setSessionPoolOption(SessionPoolOptions.newBuilder().setFailOnSessionLeak().build()) |
| 95 | + .build() |
| 96 | + .getService(); |
| 97 | + } |
| 98 | + |
| 99 | + @After |
| 100 | + public void tearDown() { |
| 101 | + mockSpanner.unfreeze(); |
| 102 | + spanner.close(); |
| 103 | + mockSpanner.reset(); |
| 104 | + mockSpanner.removeAllExecutionTimes(); |
| 105 | + } |
| 106 | + |
| 107 | + @Test |
| 108 | + public void testBatchCreateSessionsTimesOut_whenDeadlineExceeded() throws Exception { |
| 109 | + // Simulate a minimum execution time of 1000 milliseconds for the BatchCreateSessions RPC. |
| 110 | + mockSpanner.setBatchCreateSessionsExecutionTime( |
| 111 | + SimulatedExecutionTime.ofMinimumAndRandomTime(1000, 0)); |
| 112 | + SpannerOptions.Builder builder = |
| 113 | + SpannerOptions.newBuilder() |
| 114 | + .setProjectId("my-project") |
| 115 | + .setChannelProvider(channelProvider) |
| 116 | + .setCredentials(NoCredentials.getInstance()); |
| 117 | + // Set the timeout and retry settings for BatchCreateSessions to a simple |
| 118 | + // single-attempt-and-timeout after 100ms. |
| 119 | + builder |
| 120 | + .getSpannerStubSettingsBuilder() |
| 121 | + .batchCreateSessionsSettings() |
| 122 | + .setSimpleTimeoutNoRetries(Duration.ofMillis(100)); |
| 123 | + |
| 124 | + try (Spanner spanner = builder.build().getService()) { |
| 125 | + DatabaseId databaseId = DatabaseId.of("my-project", "my-instance", "my-database"); |
| 126 | + DatabaseClient client = spanner.getDatabaseClient(databaseId); |
| 127 | + |
| 128 | + ListeningExecutorService service = |
| 129 | + MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1000)); |
| 130 | + List<ListenableFuture<Void>> futures = new ArrayList<>(5000); |
| 131 | + AtomicInteger counter = new AtomicInteger(); |
| 132 | + for (int i = 0; i < 5000; i++) { |
| 133 | + final int index = i; |
| 134 | + futures.add( |
| 135 | + service.submit( |
| 136 | + () -> { |
| 137 | + // The following call is non-blocking and will not generate an exception. |
| 138 | + ResultSet rs = client.singleUse().executeQuery(SELECT1); |
| 139 | + // Actually trying to get any results will cause an exception. |
| 140 | + // The DEADLINE_EXCEEDED error of the BatchCreateSessions RPC is in this case |
| 141 | + // propagated to |
| 142 | + // the application. |
| 143 | + SpannerException e = assertThrows(SpannerException.class, rs::next); |
| 144 | + assertEquals(ErrorCode.DEADLINE_EXCEEDED, e.getErrorCode()); |
| 145 | + System.out.printf("finished test %d\n", counter.incrementAndGet()); |
| 146 | + |
| 147 | + return null; |
| 148 | + })); |
| 149 | + } |
| 150 | + service.shutdown(); |
| 151 | + assertEquals(5000, Futures.allAsList(futures).get().size()); |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + @Test |
| 156 | + public void testBatchCreateSessionsTimesOut_whenResourceExhausted() throws Exception { |
| 157 | + // Simulate a minimum execution time of 2000 milliseconds for the BatchCreateSessions RPC. |
| 158 | + mockSpanner.setBatchCreateSessionsExecutionTime( |
| 159 | + SimulatedExecutionTime.ofMinimumAndRandomTime(2000, 0)); |
| 160 | + // Add a timeout for the max amount of time (60ms) that a request waits when a session is |
| 161 | + // unavailable. |
| 162 | + SessionPoolOptions sessionPoolOptions = |
| 163 | + SessionPoolOptions.newBuilder().setAcquireSessionTimeout(Duration.ofMillis(60)).build(); |
| 164 | + SpannerOptions.Builder builder = |
| 165 | + SpannerOptions.newBuilder() |
| 166 | + .setProjectId("my-project") |
| 167 | + .setChannelProvider(channelProvider) |
| 168 | + .setCredentials(NoCredentials.getInstance()) |
| 169 | + .setSessionPoolOption(sessionPoolOptions); |
| 170 | + // Set the timeout and retry settings for BatchCreateSessions to a simple |
| 171 | + // single-attempt-and-timeout after 1000ms. This will ensure that session acquisition timeout of |
| 172 | + // 60ms will kick for all requests before the overall request RPC timeout is breached. |
| 173 | + builder |
| 174 | + .getSpannerStubSettingsBuilder() |
| 175 | + .batchCreateSessionsSettings() |
| 176 | + .setSimpleTimeoutNoRetries(Duration.ofMillis(1000)); |
| 177 | + |
| 178 | + try (Spanner spanner = builder.build().getService()) { |
| 179 | + DatabaseId databaseId = DatabaseId.of("my-project", "my-instance", "my-database"); |
| 180 | + DatabaseClient client = spanner.getDatabaseClient(databaseId); |
| 181 | + |
| 182 | + ListeningExecutorService service = |
| 183 | + MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1000)); |
| 184 | + List<ListenableFuture<Void>> futures = new ArrayList<>(5000); |
| 185 | + AtomicInteger counter = new AtomicInteger(); |
| 186 | + for (int i = 0; i < 5000; i++) { |
| 187 | + final int index = i; |
| 188 | + futures.add( |
| 189 | + service.submit( |
| 190 | + () -> { |
| 191 | + // The following call is non-blocking and will not generate an exception. |
| 192 | + ResultSet rs = client.singleUse().executeQuery(SELECT1); |
| 193 | + // Actually trying to get any results will cause an exception. |
| 194 | + // When number of requests > MAX_SESSIONS, post setAcquireSessionTimeout |
| 195 | + // a few requests will timeout with RESOURCE_EXHAUSTED error. |
| 196 | + SpannerException e = assertThrows(SpannerException.class, rs::next); |
| 197 | + assertEquals(ErrorCode.RESOURCE_EXHAUSTED, e.getErrorCode()); |
| 198 | + System.out.printf("finished test %d\n", counter.incrementAndGet()); |
| 199 | + |
| 200 | + return null; |
| 201 | + })); |
| 202 | + } |
| 203 | + service.shutdown(); |
| 204 | + assertEquals(5000, Futures.allAsList(futures).get().size()); |
| 205 | + } |
| 206 | + } |
| 207 | +} |
0 commit comments