Search in sources :

Example 16 with Context

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

the class ClientCallImpl method start.

@Override
public void start(final Listener<RespT> observer, Metadata headers) {
    checkState(stream == null, "Already started");
    checkNotNull(observer, "observer");
    checkNotNull(headers, "headers");
    if (context.isCancelled()) {
        // Context is already cancelled so no need to create a real stream, just notify the observer
        // of cancellation via callback on the executor
        stream = NoopClientStream.INSTANCE;
        class ClosedByContext extends ContextRunnable {

            ClosedByContext() {
                super(context);
            }

            @Override
            public void runInContext() {
                closeObserver(observer, statusFromCancelled(context), new Metadata());
            }
        }
        callExecutor.execute(new ClosedByContext());
        return;
    }
    final String compressorName = callOptions.getCompressor();
    Compressor compressor = null;
    if (compressorName != null) {
        compressor = compressorRegistry.lookupCompressor(compressorName);
        if (compressor == null) {
            stream = NoopClientStream.INSTANCE;
            class ClosedByNotFoundCompressor extends ContextRunnable {

                ClosedByNotFoundCompressor() {
                    super(context);
                }

                @Override
                public void runInContext() {
                    closeObserver(observer, Status.INTERNAL.withDescription(String.format("Unable to find compressor by name %s", compressorName)), new Metadata());
                }
            }
            callExecutor.execute(new ClosedByNotFoundCompressor());
            return;
        }
    } else {
        compressor = Codec.Identity.NONE;
    }
    prepareHeaders(headers, decompressorRegistry, compressor, statsTraceCtx);
    Deadline effectiveDeadline = effectiveDeadline();
    boolean deadlineExceeded = effectiveDeadline != null && effectiveDeadline.isExpired();
    if (!deadlineExceeded) {
        updateTimeoutHeaders(effectiveDeadline, callOptions.getDeadline(), context.getDeadline(), headers);
        ClientTransport transport = clientTransportProvider.get(new PickSubchannelArgsImpl(method, headers, callOptions));
        Context origContext = context.attach();
        try {
            stream = transport.newStream(method, headers, callOptions, statsTraceCtx);
        } finally {
            context.detach(origContext);
        }
    } else {
        stream = new FailingClientStream(DEADLINE_EXCEEDED);
    }
    if (callOptions.getAuthority() != null) {
        stream.setAuthority(callOptions.getAuthority());
    }
    if (callOptions.getMaxInboundMessageSize() != null) {
        stream.setMaxInboundMessageSize(callOptions.getMaxInboundMessageSize());
    }
    if (callOptions.getMaxOutboundMessageSize() != null) {
        stream.setMaxOutboundMessageSize(callOptions.getMaxOutboundMessageSize());
    }
    stream.setCompressor(compressor);
    stream.start(new ClientStreamListenerImpl(observer));
    // Delay any sources of cancellation after start(), because most of the transports are broken if
    // they receive cancel before start. Issue #1343 has more details
    // Propagate later Context cancellation to the remote side.
    context.addListener(this, directExecutor());
    if (effectiveDeadline != null && // If the context has the effective deadline, we don't need to schedule an extra task.
    context.getDeadline() != effectiveDeadline) {
        deadlineCancellationFuture = startDeadlineTimer(effectiveDeadline);
    }
    if (cancelListenersShouldBeRemoved) {
        // Race detected! ClientStreamListener.closed may have been called before
        // deadlineCancellationFuture was set / context listener added, thereby preventing the future
        // and listener from being cancelled. Go ahead and cancel again, just to be sure it
        // was cancelled.
        removeContextListenerAndCancelDeadlineFuture();
    }
}
Also used : Context(io.grpc.Context) Deadline(io.grpc.Deadline) Metadata(io.grpc.Metadata) Compressor(io.grpc.Compressor)

Example 17 with Context

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

the class ClientCallImplTest method contextDeadlineShouldOverrideLargerMetadataTimeout.

@Test
public void contextDeadlineShouldOverrideLargerMetadataTimeout() {
    long deadlineNanos = TimeUnit.SECONDS.toNanos(1);
    Context context = Context.current().withDeadlineAfter(deadlineNanos, TimeUnit.NANOSECONDS, deadlineCancellationExecutor);
    context.attach();
    CallOptions callOpts = CallOptions.DEFAULT.withDeadlineAfter(2, 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 deltaNanos = TimeUnit.MILLISECONDS.toNanos(400);
    assertTimeoutBetween(timeout, deadlineNanos - deltaNanos, deadlineNanos);
}
Also used : Context(io.grpc.Context) StatsContext(com.google.instrumentation.stats.StatsContext) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Test(org.junit.Test)

Example 18 with Context

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

the class MetadataApplierImpl method apply.

@Override
public void apply(Metadata headers) {
    checkState(!finalized, "apply() or fail() already called");
    checkNotNull(headers, "headers");
    origHeaders.merge(headers);
    ClientStream realStream;
    Context origCtx = ctx.attach();
    try {
        realStream = transport.newStream(method, origHeaders, callOptions, statsTraceCtx);
    } finally {
        ctx.detach(origCtx);
    }
    finalizeWith(realStream);
}
Also used : Context(io.grpc.Context)

Example 19 with Context

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

the class GrpcSpannerRpc method doStreamingCall.

private <T> StreamingCall doStreamingCall(MethodDescriptor<T, PartialResultSet> method, T request, ResultStreamConsumer consumer, @Nullable String resource, @Nullable Long channelHint) {
    final Context context = Context.current();
    // TODO: Add deadline based on context.
    CallOptions callOptions = credentials == null ? CallOptions.DEFAULT : CallOptions.DEFAULT.withCallCredentials(credentials);
    final ClientCall<T, PartialResultSet> call = new MetadataClientCall<>(pick(channelHint, channels).newCall(method, callOptions), newMetadata(resource));
    ResultSetStreamObserver<T> observer = new ResultSetStreamObserver<T>(consumer, context, call);
    ClientCalls.asyncServerStreamingCall(call, request, observer);
    return observer;
}
Also used : Context(io.grpc.Context) CallOptions(io.grpc.CallOptions) PartialResultSet(com.google.spanner.v1.PartialResultSet)

Example 20 with Context

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

the class ContextUtilsTest method getCurrentSpan.

@Test
public void getCurrentSpan() {
    assertThat(ContextUtils.getCurrentSpan()).isNull();
    Context origContext = Context.current().withValue(ContextUtils.CONTEXT_SPAN_KEY, span).attach();
    // Make sure context is detached even if test fails.
    try {
        assertThat(ContextUtils.getCurrentSpan()).isSameAs(span);
    } finally {
        Context.current().detach(origContext);
    }
    assertThat(ContextUtils.getCurrentSpan()).isNull();
}
Also used : Context(io.grpc.Context) 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