|
14 | 14 |
|
15 | 15 | #include "google/cloud/internal/streaming_read_rpc.h" |
16 | 16 | #include "google/cloud/log.h" |
| 17 | +#include <grpc/compression.h> |
17 | 18 |
|
18 | 19 | namespace google { |
19 | 20 | namespace cloud { |
20 | 21 | inline namespace GOOGLE_CLOUD_CPP_NS { |
21 | 22 | namespace internal { |
| 23 | +namespace { |
| 24 | +// AFAICT there is no C++ API to get the name, but the C core API is public and |
| 25 | +// documented: |
| 26 | +// https://grpc.github.io/grpc/core/compression_8h.html |
| 27 | +std::string ToString(grpc_compression_algorithm algo) { |
| 28 | + char const* name; |
| 29 | + if (grpc_compression_algorithm_name(algo, &name) == 0) { |
| 30 | + return "unknown"; |
| 31 | + } |
| 32 | + return name; |
| 33 | +} |
| 34 | +} // namespace |
| 35 | + |
| 36 | +StreamingRpcMetadata GetRequestMetadataFromContext( |
| 37 | + grpc::ClientContext const& context) { |
| 38 | + StreamingRpcMetadata metadata{ |
| 39 | + // Use invalid header names (starting with ':') to store the |
| 40 | + // grpc::ClientContext metadata. |
| 41 | + {":grpc-context-peer", context.peer()}, |
| 42 | + {":grpc-context-compression-algorithm", |
| 43 | + ToString(context.compression_algorithm())}, |
| 44 | + }; |
| 45 | + auto hint = metadata.end(); |
| 46 | + for (auto const& kv : context.GetServerInitialMetadata()) { |
| 47 | + // gRPC metadata is stored in `grpc::string_ref`, a type inspired by |
| 48 | + // `std::string_view`. We need to explicitly convert these to `std::string`. |
| 49 | + // In addition, we use a prefix to distinguish initial vs. trailing headers. |
| 50 | + auto key = ":grpc-initial-" + std::string{kv.first.data(), kv.first.size()}; |
| 51 | + auto value = std::string{kv.second.data(), kv.second.size()}; |
| 52 | + hint = std::next( |
| 53 | + metadata.emplace_hint(hint, std::move(key), std::move(value))); |
| 54 | + } |
| 55 | + hint = metadata.end(); |
| 56 | + for (auto const& kv : context.GetServerTrailingMetadata()) { |
| 57 | + // Same as above, convert `grpc::string_ref` to `std::string`: |
| 58 | + auto key = |
| 59 | + ":grpc-trailing-" + std::string{kv.first.data(), kv.first.size()}; |
| 60 | + auto value = std::string{kv.second.data(), kv.second.size()}; |
| 61 | + hint = std::next( |
| 62 | + metadata.emplace_hint(hint, std::move(key), std::move(value))); |
| 63 | + } |
| 64 | + return metadata; |
| 65 | +} |
22 | 66 |
|
23 | 67 | void StreamingReadRpcReportUnhandledError(Status const& status, |
24 | 68 | char const* tname) { |
|
0 commit comments