TensorFlow Serving C++ API Documentation
prediction_service_grpc.cc
1 /* Copyright 2020 Google Inc. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7  http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #include "tensorflow_serving/experimental/tensorflow/ops/remote_predict/kernels/prediction_service_grpc.h"
16 
17 #include <functional>
18 #include <string>
19 
20 #include "grpcpp/create_channel.h"
21 #include "grpcpp/security/credentials.h"
22 #include "absl/time/clock.h"
23 
24 using namespace tensorflow; // NOLINT(build/namespaces)
25 namespace tensorflow {
26 namespace serving {
27 namespace {
28 
29 absl::Status FromGrpcStatus(const ::grpc::Status& s) {
30  if (s.ok()) {
31  return absl::Status();
32  }
33  return absl::Status(static_cast<absl::StatusCode>(s.error_code()),
34  s.error_message());
35 }
36 
37 } // namespace
38 
39 PredictionServiceGrpc::PredictionServiceGrpc(
40  const std::string& target_address) {
41  // TODO(b/159739577): Set security channel from incoming rpc request.
42  auto channel = ::grpc::CreateChannel(target_address,
43  ::grpc::InsecureChannelCredentials());
44  stub_ = tensorflow::serving::PredictionService::NewStub(channel);
45 }
46 
47 absl::StatusOr< ::grpc::ClientContext*> PredictionServiceGrpc::CreateRpc(
48  absl::Duration max_rpc_deadline) {
49  ::grpc::ClientContext* rpc = new ::grpc::ClientContext();
50  // TODO(b/300069508): Set deadline as the min value between
51  // the incoming rpc deadline and max_rpc_deadline_millis.
52  rpc->set_deadline(std::chrono::system_clock::now() +
53  absl::ToChronoSeconds(max_rpc_deadline));
54  return rpc;
55 }
56 
57 void PredictionServiceGrpc::Predict(
58  ::grpc::ClientContext* rpc, PredictRequest* request,
59  PredictResponse* response,
60  std::function<void(absl::Status status)> callback) {
61  std::function<void(::grpc::Status)> wrapped_callback =
62  [callback](::grpc::Status status) { callback(FromGrpcStatus(status)); };
63 
64  stub_->experimental_async()->Predict(rpc, request, response,
65  wrapped_callback);
66 }
67 
68 } // namespace serving
69 } // namespace tensorflow