xref: /aosp_15_r20/external/grpc-grpc/src/cpp/server/load_reporter/util.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2018 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include <grpc/support/port_platform.h>
20 
21 #include <string.h>
22 
23 #include <cmath>
24 #include <string>
25 
26 #include <grpc/load_reporting.h>
27 #include <grpc/support/log.h>
28 #include <grpcpp/ext/server_load_reporting.h>
29 #include <grpcpp/server_context.h>
30 
31 namespace grpc {
32 namespace load_reporter {
33 namespace experimental {
34 
AddLoadReportingCost(grpc::ServerContext * ctx,const std::string & cost_name,double cost_value)35 void AddLoadReportingCost(grpc::ServerContext* ctx,
36                           const std::string& cost_name, double cost_value) {
37   if (std::isnormal(cost_value)) {
38     std::string buf;
39     buf.resize(sizeof(cost_value) + cost_name.size());
40     memcpy(&(*buf.begin()), &cost_value, sizeof(cost_value));
41     memcpy(&(*buf.begin()) + sizeof(cost_value), cost_name.data(),
42            cost_name.size());
43     ctx->AddTrailingMetadata(GRPC_LB_COST_MD_KEY, buf);
44   } else {
45     gpr_log(GPR_ERROR, "Call metric value is not normal.");
46   }
47 }
48 
49 }  // namespace experimental
50 }  // namespace load_reporter
51 }  // namespace grpc
52