Search in sources :

Example 71 with Metadata

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

the class NettyClientStream method start.

@Override
public void start(ClientStreamListener listener) {
    super.start(listener);
    // Convert the headers into Netty HTTP/2 headers.
    AsciiString defaultPath = (AsciiString) methodDescriptorAccessor.geRawMethodName(method);
    if (defaultPath == null) {
        defaultPath = new AsciiString("/" + method.getFullMethodName());
        methodDescriptorAccessor.setRawMethodName(method, defaultPath);
    }
    headers.discardAll(GrpcUtil.USER_AGENT_KEY);
    Http2Headers http2Headers = Utils.convertClientHeaders(headers, scheme, defaultPath, authority, userAgent);
    headers = null;
    ChannelFutureListener failureListener = new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                // Stream creation failed. Close the stream if not already closed.
                Status s = transportState().statusFromFailedFuture(future);
                transportState().transportReportStatus(s, true, new Metadata());
            }
        }
    };
    // Write the command requesting the creation of the stream.
    writeQueue.enqueue(new CreateStreamCommand(http2Headers, transportState()), !method.getType().clientSendsOneMessage()).addListener(failureListener);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Status(io.grpc.Status) Http2Headers(io.netty.handler.codec.http2.Http2Headers) AsciiString(io.netty.util.AsciiString) Metadata(io.grpc.Metadata) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 72 with Metadata

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

the class NettyServerHandler method onHeadersRead.

private void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers) throws Http2Exception {
    if (!teWarningLogged && !TE_TRAILERS.equals(headers.get(TE_HEADER))) {
        logger.warning(String.format("Expected header TE: %s, but %s is received. This means " + "some intermediate proxy may not support trailers", TE_TRAILERS, headers.get(TE_HEADER)));
        teWarningLogged = true;
    }
    try {
        // Verify that the Content-Type is correct in the request.
        verifyContentType(streamId, headers);
        String method = determineMethod(streamId, headers);
        // The Http2Stream object was put by AbstractHttp2ConnectionHandler before calling this
        // method.
        Http2Stream http2Stream = requireHttp2Stream(streamId);
        Metadata metadata = Utils.convertHeaders(headers);
        StatsTraceContext statsTraceCtx = checkNotNull(transportListener.methodDetermined(method, metadata), "statsTraceCtx");
        NettyServerStream.TransportState state = new NettyServerStream.TransportState(this, http2Stream, maxMessageSize, statsTraceCtx);
        String authority = getOrUpdateAuthority((AsciiString) headers.authority());
        NettyServerStream stream = new NettyServerStream(ctx.channel(), state, attributes, authority, statsTraceCtx);
        transportListener.streamCreated(stream, method, metadata);
        state.onStreamAllocated();
        http2Stream.setProperty(streamKey, state);
    } catch (Http2Exception e) {
        throw e;
    } catch (Throwable e) {
        logger.log(Level.WARNING, "Exception in onHeadersRead()", e);
        // Throw an exception that will get handled by onStreamError.
        throw newStreamException(streamId, e);
    }
}
Also used : Http2Exception(io.netty.handler.codec.http2.Http2Exception) StatsTraceContext(io.grpc.internal.StatsTraceContext) Metadata(io.grpc.Metadata) AsciiString(io.netty.util.AsciiString) Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Example 73 with Metadata

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

the class CascadingTest method startCallTreeServer.

/**
   * Create a tree of client to server calls where each received call on the server
   * fans out to two downstream calls. Uses SimpleRequest.response_size to limit the nodeCount
   * of the tree. One of the leaves will ABORT to trigger cancellation back up to tree.
   */
private void startCallTreeServer(int depthThreshold) throws IOException {
    final AtomicInteger nodeCount = new AtomicInteger((2 << depthThreshold) - 1);
    server = InProcessServerBuilder.forName("channel").executor(otherWork).addService(ServerInterceptors.intercept(service, new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            // Respond with the headers but nothing else.
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ReqT>() {

                @Override
                public void onMessage(final ReqT message) {
                    Messages.SimpleRequest req = (Messages.SimpleRequest) message;
                    if (nodeCount.decrementAndGet() == 0) {
                        // we are in the final leaf node so trigger an ABORT upwards
                        Context.currentContextExecutor(otherWork).execute(new Runnable() {

                            @Override
                            public void run() {
                                call.close(Status.ABORTED, new Metadata());
                            }
                        });
                    } else if (req.getResponseSize() != 0) {
                        // We are in a non leaf node so fire off two requests
                        req = req.toBuilder().setResponseSize(req.getResponseSize() - 1).build();
                        for (int i = 0; i < 2; i++) {
                            asyncStub.unaryCall(req, new StreamObserver<Messages.SimpleResponse>() {

                                @Override
                                public void onNext(Messages.SimpleResponse value) {
                                }

                                @Override
                                public void onError(Throwable t) {
                                    Status status = Status.fromThrowable(t);
                                    if (status.getCode() == Status.Code.CANCELLED) {
                                        observedCancellations.countDown();
                                    }
                                    // Propagate closure upwards.
                                    try {
                                        call.close(status, new Metadata());
                                    } catch (IllegalStateException t2) {
                                    // Ignore error if already closed.
                                    }
                                }

                                @Override
                                public void onCompleted() {
                                }
                            });
                        }
                    }
                }

                @Override
                public void onCancel() {
                    receivedCancellations.countDown();
                }
            };
        }
    })).build();
    server.start();
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Status(io.grpc.Status) ServerCallHandler(io.grpc.ServerCallHandler) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) Metadata(io.grpc.Metadata) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerCall(io.grpc.ServerCall) ServerInterceptor(io.grpc.ServerInterceptor) SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse)

Example 74 with Metadata

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

the class TransportCompressionTest method startServer.

/** Start server. */
@BeforeClass
public static void startServer() {
    compressors.register(FZIPPER);
    compressors.register(Codec.Identity.NONE);
    startStaticServer(NettyServerBuilder.forPort(0).maxMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE).compressorRegistry(compressors).decompressorRegistry(decompressors), new ServerInterceptor() {

        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            Listener<ReqT> listener = next.startCall(call, headers);
            // TODO(carl-mastrangelo): check that encoding was set.
            call.setMessageCompression(true);
            return listener;
        }
    });
}
Also used : ForwardingClientCallListener(io.grpc.ForwardingClientCallListener) Listener(io.grpc.ServerCall.Listener) ServerInterceptor(io.grpc.ServerInterceptor) Metadata(io.grpc.Metadata) BeforeClass(org.junit.BeforeClass)

Example 75 with Metadata

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

the class TransportCompressionTest method createChannel.

@Override
protected ManagedChannel createChannel() {
    NettyChannelBuilder builder = NettyChannelBuilder.forAddress("localhost", getPort()).maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE).decompressorRegistry(decompressors).compressorRegistry(compressors).intercept(new ClientInterceptor() {

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
            final ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
            return new ForwardingClientCall<ReqT, RespT>() {

                @Override
                protected ClientCall<ReqT, RespT> delegate() {
                    return call;
                }

                @Override
                public void start(final ClientCall.Listener<RespT> responseListener, Metadata headers) {
                    ClientCall.Listener<RespT> listener = new ForwardingClientCallListener<RespT>() {

                        @Override
                        protected io.grpc.ClientCall.Listener<RespT> delegate() {
                            return responseListener;
                        }

                        @Override
                        public void onHeaders(Metadata headers) {
                            super.onHeaders(headers);
                            if (expectFzip) {
                                String encoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY);
                                assertEquals(encoding, FZIPPER.getMessageEncoding());
                            }
                        }
                    };
                    super.start(listener, headers);
                    setMessageCompression(true);
                }
            };
        }
    }).usePlaintext(true);
    io.grpc.internal.TestingAccessor.setStatsContextFactory(builder, getClientStatsFactory());
    return builder.build();
}
Also used : ForwardingClientCallListener(io.grpc.ForwardingClientCallListener) Listener(io.grpc.ServerCall.Listener) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) ForwardingClientCall(io.grpc.ForwardingClientCall) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) ByteString(com.google.protobuf.ByteString) MethodDescriptor(io.grpc.MethodDescriptor) ClientCall(io.grpc.ClientCall) ForwardingClientCall(io.grpc.ForwardingClientCall) ClientInterceptor(io.grpc.ClientInterceptor) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) ForwardingClientCallListener(io.grpc.ForwardingClientCallListener)

Aggregations

Metadata (io.grpc.Metadata)283 Test (org.junit.Test)229 Status (io.grpc.Status)78 ByteArrayInputStream (java.io.ByteArrayInputStream)25 ClientStream (io.grpc.internal.ClientStream)20 InputStream (java.io.InputStream)19 Buffer (okio.Buffer)16 ClientCall (io.grpc.ClientCall)14 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)14 ServerStreamListener (io.grpc.internal.ServerStreamListener)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 ServerCall (io.grpc.ServerCall)12 StatsContext (com.google.instrumentation.stats.StatsContext)11 CallOptions (io.grpc.CallOptions)11 IOException (java.io.IOException)11 Context (io.grpc.Context)10 StatusRuntimeException (io.grpc.StatusRuntimeException)10 Matchers.anyString (org.mockito.Matchers.anyString)10 ServerStream (io.grpc.internal.ServerStream)9 ServiceDescriptor (io.grpc.ServiceDescriptor)8