Search in sources :

Example 11 with Context

use of io.grpc.Context in project google-cloud-java by GoogleCloudPlatform.

the class ITReadTest method deadline.

@Test
public void deadline() {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    Context.CancellableContext context = Context.current().withDeadlineAfter(10, TimeUnit.NANOSECONDS, executor);
    Runnable work = context.wrap(new Runnable() {

        @Override
        public void run() {
            client.singleUse(TimestampBound.strong()).readRow(TABLE_NAME, Key.of("k1"), ALL_COLUMNS);
        }
    });
    try {
        work.run();
    } catch (SpannerException e) {
        MatcherAssert.assertThat(e, isSpannerException(ErrorCode.DEADLINE_EXCEEDED));
    } finally {
        executor.shutdown();
    }
}
Also used : Context(io.grpc.Context) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SpannerMatchers.isSpannerException(com.google.cloud.spanner.SpannerMatchers.isSpannerException) SpannerException(com.google.cloud.spanner.SpannerException) IntegrationTest(com.google.cloud.spanner.IntegrationTest) Test(org.junit.Test)

Example 12 with Context

use of io.grpc.Context in project instrumentation-java by census-instrumentation.

the class StatsContextFactoryTest method testGetCurrentStatsContext.

@Test
public void testGetCurrentStatsContext() {
    assertThat(factory.getCurrentStatsContext()).isEqualTo(defaultCtx);
    Context origContext = Context.current().withValue(ContextUtils.STATS_CONTEXT_KEY, statsContext).attach();
    // Make sure context is detached even if test fails.
    try {
        assertThat(factory.getCurrentStatsContext()).isSameAs(statsContext);
    } finally {
        Context.current().detach(origContext);
    }
    assertThat(factory.getCurrentStatsContext()).isEqualTo(defaultCtx);
}
Also used : Context(io.grpc.Context) Test(org.junit.Test)

Example 13 with Context

use of io.grpc.Context in project grpc-java by grpc.

the class ServerImplTest method testCallContextIsBoundInListenerCallbacks.

@Test
public void testCallContextIsBoundInListenerCallbacks() throws Exception {
    createAndStartServer(NO_FILTERS);
    MethodDescriptor<String, Integer> method = MethodDescriptor.<String, Integer>newBuilder().setType(MethodDescriptor.MethodType.UNKNOWN).setFullMethodName("Waiter/serve").setRequestMarshaller(STRING_MARSHALLER).setResponseMarshaller(INTEGER_MARSHALLER).build();
    final AtomicBoolean onReadyCalled = new AtomicBoolean(false);
    final AtomicBoolean onMessageCalled = new AtomicBoolean(false);
    final AtomicBoolean onHalfCloseCalled = new AtomicBoolean(false);
    final AtomicBoolean onCancelCalled = new AtomicBoolean(false);
    mutableFallbackRegistry.addService(ServerServiceDefinition.builder(new ServiceDescriptor("Waiter", method)).addMethod(method, new ServerCallHandler<String, Integer>() {

        @Override
        public ServerCall.Listener<String> startCall(ServerCall<String, Integer> call, Metadata headers) {
            // Check that the current context is a descendant of SERVER_CONTEXT
            final Context initial = Context.current();
            assertEquals("yes", SERVER_ONLY.get(initial));
            assertNotSame(SERVER_CONTEXT, initial);
            assertFalse(initial.isCancelled());
            return new ServerCall.Listener<String>() {

                @Override
                public void onReady() {
                    checkContext();
                    onReadyCalled.set(true);
                }

                @Override
                public void onMessage(String message) {
                    checkContext();
                    onMessageCalled.set(true);
                }

                @Override
                public void onHalfClose() {
                    checkContext();
                    onHalfCloseCalled.set(true);
                }

                @Override
                public void onCancel() {
                    checkContext();
                    onCancelCalled.set(true);
                }

                @Override
                public void onComplete() {
                    checkContext();
                }

                private void checkContext() {
                    // Check that the bound context is the same as the initial one.
                    assertSame(initial, Context.current());
                }
            };
        }
    }).build());
    ServerTransportListener transportListener = transportServer.registerNewServerTransport(new SimpleServerTransport());
    Metadata requestHeaders = new Metadata();
    StatsTraceContext statsTraceCtx = transportListener.methodDetermined("Waiter/serve", requestHeaders);
    assertNotNull(statsTraceCtx);
    when(stream.statsTraceContext()).thenReturn(statsTraceCtx);
    transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
    verify(stream).setListener(streamListenerCaptor.capture());
    ServerStreamListener streamListener = streamListenerCaptor.getValue();
    assertNotNull(streamListener);
    streamListener.onReady();
    assertEquals(1, executor.runDueTasks());
    assertTrue(onReadyCalled.get());
    streamListener.messageRead(new ByteArrayInputStream(new byte[0]));
    assertEquals(1, executor.runDueTasks());
    assertTrue(onMessageCalled.get());
    streamListener.halfClosed();
    assertEquals(1, executor.runDueTasks());
    assertTrue(onHalfCloseCalled.get());
    streamListener.closed(Status.CANCELLED);
    assertEquals(1, executor.runDueTasks());
    assertTrue(onCancelCalled.get());
    // Close should never be called if asserts in listener pass.
    verify(stream, times(0)).close(isA(Status.class), isNotNull(Metadata.class));
}
Also used : Context(io.grpc.Context) StatsContext(com.google.instrumentation.stats.StatsContext) Status(io.grpc.Status) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Metadata(io.grpc.Metadata) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServiceDescriptor(io.grpc.ServiceDescriptor) ServerCall(io.grpc.ServerCall) ByteArrayInputStream(java.io.ByteArrayInputStream) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Test(org.junit.Test)

Example 14 with Context

use of io.grpc.Context in project grpc-java by grpc.

the class ServerImplTest method testClientCancelTriggersContextCancellation.

@Test
public void testClientCancelTriggersContextCancellation() throws Exception {
    createAndStartServer(NO_FILTERS);
    final AtomicBoolean contextCancelled = new AtomicBoolean(false);
    callListener = new ServerCall.Listener<String>() {

        @Override
        public void onReady() {
            Context.current().addListener(new Context.CancellationListener() {

                @Override
                public void cancelled(Context context) {
                    contextCancelled.set(true);
                }
            }, MoreExecutors.directExecutor());
        }
    };
    final AtomicReference<ServerCall<String, Integer>> callReference = new AtomicReference<ServerCall<String, Integer>>();
    MethodDescriptor<String, Integer> method = MethodDescriptor.<String, Integer>newBuilder().setType(MethodDescriptor.MethodType.UNKNOWN).setFullMethodName("Waiter/serve").setRequestMarshaller(STRING_MARSHALLER).setResponseMarshaller(INTEGER_MARSHALLER).build();
    mutableFallbackRegistry.addService(ServerServiceDefinition.builder(new ServiceDescriptor("Waiter", method)).addMethod(method, new ServerCallHandler<String, Integer>() {

        @Override
        public ServerCall.Listener<String> startCall(ServerCall<String, Integer> call, Metadata headers) {
            callReference.set(call);
            return callListener;
        }
    }).build());
    ServerTransportListener transportListener = transportServer.registerNewServerTransport(new SimpleServerTransport());
    Metadata requestHeaders = new Metadata();
    StatsTraceContext statsTraceCtx = transportListener.methodDetermined("Waiter/serve", requestHeaders);
    assertNotNull(statsTraceCtx);
    when(stream.statsTraceContext()).thenReturn(statsTraceCtx);
    transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
    verify(stream).setListener(streamListenerCaptor.capture());
    ServerStreamListener streamListener = streamListenerCaptor.getValue();
    assertNotNull(streamListener);
    streamListener.onReady();
    streamListener.closed(Status.CANCELLED);
    assertEquals(1, executor.runDueTasks());
    assertTrue(contextCancelled.get());
}
Also used : Context(io.grpc.Context) StatsContext(com.google.instrumentation.stats.StatsContext) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Metadata(io.grpc.Metadata) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServerCall(io.grpc.ServerCall) ServiceDescriptor(io.grpc.ServiceDescriptor) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Test(org.junit.Test)

Example 15 with Context

use of io.grpc.Context in project grpc-java by grpc.

the class ClientCallImplTest method contextDeadlineShouldNotOverrideSmallerMetadataTimeout.

@Test
public void contextDeadlineShouldNotOverrideSmallerMetadataTimeout() {
    long deadlineNanos = TimeUnit.SECONDS.toNanos(2);
    Context context = Context.current().withDeadlineAfter(deadlineNanos, TimeUnit.NANOSECONDS, deadlineCancellationExecutor);
    context.attach();
    CallOptions callOpts = CallOptions.DEFAULT.withDeadlineAfter(1, TimeUnit.SECONDS);
    ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(method, MoreExecutors.directExecutor(), callOpts, statsTraceCtx, provider, deadlineCancellationExecutor);
    Metadata headers = new Metadata();
    call.start(callListener, headers);
    assertTrue(headers.containsKey(GrpcUtil.TIMEOUT_KEY));
    Long timeout = headers.get(GrpcUtil.TIMEOUT_KEY);
    assertNotNull(timeout);
    long callOptsNanos = TimeUnit.SECONDS.toNanos(1);
    long deltaNanos = TimeUnit.MILLISECONDS.toNanos(400);
    assertTimeoutBetween(timeout, callOptsNanos - deltaNanos, callOptsNanos);
}
Also used : Context(io.grpc.Context) StatsContext(com.google.instrumentation.stats.StatsContext) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Test(org.junit.Test)

Aggregations

Context (io.grpc.Context)20 Test (org.junit.Test)15 Metadata (io.grpc.Metadata)10 StatsContext (com.google.instrumentation.stats.StatsContext)8 CallOptions (io.grpc.CallOptions)4 Status (io.grpc.Status)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 IntegrationTest (com.google.cloud.spanner.IntegrationTest)2 SpannerException (com.google.cloud.spanner.SpannerException)2 SpannerMatchers.isSpannerException (com.google.cloud.spanner.SpannerMatchers.isSpannerException)2 ClientCall (io.grpc.ClientCall)2 ServerCall (io.grpc.ServerCall)2 ServiceDescriptor (io.grpc.ServiceDescriptor)2 JumpToApplicationThreadServerStreamListener (io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ExecutionException (java.util.concurrent.ExecutionException)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 ExponentialBackOff (com.google.api.client.util.ExponentialBackOff)1