如何读取/记录 gRPC HTTP 标头(不是自定义元数据)?

net*_*ica 3 c++ protocol-buffers grpc grpc-js

我正在使用 gRPC 和 Protobuf,使用 C++ 服务器和 C++ 客户端,以及 grpc-js 客户端。有没有办法从 gRPC 的传输层读取所有 HTTP 请求/响应标头?我正在寻找一种典型的客户端/服务器 HTTP 标头 - 特别是,我想查看正在使用的协议版本(是否是 HTTP1.1/2)。我知道 gRPC 应该使用 HTTP2,但我试图在较低级别上确认它。

在典型的 gRPC 客户端实现中,您有这样的内容:

class PingPongClient {
 public:
  PingPongClient(std::shared_ptr<Channel> channel)
      : stub_(PingPong::NewStub(channel)) {}

  // Assembles the client's payload, sends it and presents the response back
  // from the server.
  PingPongReply PingPong(PingPongRequest request) {
    // Container for the data we expect from the server.
    PingPongReply reply;

    // Context for the client. It could be used to convey extra information to
    // the server and/or tweak certain RPC behaviors.
    ClientContext context;

    // The actual RPC.
    Status status = stub_->Ping(&context, request, &reply);

    // Act upon its status.
    if (status.ok()) {
        return reply;
    } else {
      auto errorMsg = status.error_code() + ": " + status.error_message();
      std::cout << errorMsg << std::endl;
      throw std::runtime_error(errorMsg);
    }
  }

 private:
  std::unique_ptr<PingPong::Stub> stub_;
};
Run Code Online (Sandbox Code Playgroud)

在服务器端,类似:

class PingPongServiceImpl final : public PingPong::Service {
  Status Ping(
    ServerContext* context,
    const PingPongRequest* request,
    PingPongReply* reply
  ) override {
    std::cout << "PingPong" << std::endl;
    printContextClientMetadata(context->client_metadata());

    if (request->input_msg() == "hello") {
      reply->set_output_msg("world");
    } else {
      reply->set_output_msg("I can't pong unless you ping me 'hello'!");
    }

    std::cout << "Replying with " << reply->output_msg() << std::endl;

    return Status::OK;
  }
};
Run Code Online (Sandbox Code Playgroud)

我认为 ServerContext 或请求对象可能有权访问此信息,但上下文似乎只提供元数据的接口,这是自定义的。

gRPC C++ 示例都没有给出任何迹象表明存在这样的 API,gRPC 源代码中也没有任何相关的源/头文件。我已经在教程、博客文章、视频和文档方面用尽了我的选择 - 我在 grpc-io 论坛上提出了类似的问题,但没有人接受。希望SO团队对此有一些见解!

我还应该注意到,我尝试将各种环境变量作为标志传递给正在运行的进程,以查看是否可以获得有关 HTTP 标头的详细信息,但即使启用了这些标志(与 HTTP 相关的标志),我也看不到基本的HTTP 标头。

mur*_*d99 5

首先,gRPC 库绝对使用 HTTP/2。该协议是根据 HTTP/2 明确定义的

gRPC 库不会直接向应用程序公开原始 HTTP 标头。但是,它们确实具有跟踪日志记录选项,可以记录各种信息以用于调试目的,包括标头。可以通过设置环境变量来启用跟踪器GRPC_TRACE。还应设置环境变量GRPC_VERBOSITY=DEBUG以确保输出所有日志。可以在本文档中找到更多信息,描述库如何使用环境变量。

在 C++ 库中,http跟踪器应记录原始标头。grpc-js 库具有不同的内部结构和不同的跟踪器定义,因此您应该使用call_stream该库的跟踪器。这些还将记录其他请求信息,但挑选标头应该很容易。