• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <thread>
18 
19 #include <grpc++/grpc++.h>
20 
21 #include "monster_test.grpc.fb.h"
22 #include "monster_test_generated.h"
23 #include "test_assert.h"
24 
25 using namespace MyGame::Example;
26 using flatbuffers::grpc::MessageBuilder;
27 using flatbuffers::FlatBufferBuilder;
28 
29 void message_builder_tests();
30 
31 // The callback implementation of our server, that derives from the generated
32 // code. It implements all rpcs specified in the FlatBuffers schema.
33 class ServiceImpl final : public MyGame::Example::MonsterStorage::Service {
Store(::grpc::ServerContext * context,const flatbuffers::grpc::Message<Monster> * request,flatbuffers::grpc::Message<Stat> * response)34   virtual ::grpc::Status Store(
35       ::grpc::ServerContext *context,
36       const flatbuffers::grpc::Message<Monster> *request,
37       flatbuffers::grpc::Message<Stat> *response) override {
38     // Create a response from the incoming request name.
39     fbb_.Clear();
40     auto stat_offset = CreateStat(
41         fbb_, fbb_.CreateString("Hello, " + request->GetRoot()->name()->str()));
42     fbb_.Finish(stat_offset);
43     // Transfer ownership of the message to gRPC
44     *response = fbb_.ReleaseMessage<Stat>();
45     return grpc::Status::OK;
46   }
Retrieve(::grpc::ServerContext * context,const flatbuffers::grpc::Message<Stat> * request,::grpc::ServerWriter<flatbuffers::grpc::Message<Monster>> * writer)47   virtual ::grpc::Status Retrieve(
48       ::grpc::ServerContext *context,
49       const flatbuffers::grpc::Message<Stat> *request,
50       ::grpc::ServerWriter<flatbuffers::grpc::Message<Monster>> *writer)
51       override {
52     for (int i = 0; i < 5; i++) {
53       fbb_.Clear();
54       // Create 5 monsters for resposne.
55       auto monster_offset =
56           CreateMonster(fbb_, 0, 0, 0,
57                         fbb_.CreateString(request->GetRoot()->id()->str() +
58                                           " No." + std::to_string(i)));
59       fbb_.Finish(monster_offset);
60 
61       flatbuffers::grpc::Message<Monster> monster =
62           fbb_.ReleaseMessage<Monster>();
63 
64       // Send monster to client using streaming.
65       writer->Write(monster);
66     }
67     return grpc::Status::OK;
68   }
69 
70  private:
71   flatbuffers::grpc::MessageBuilder fbb_;
72 };
73 
74 // Track the server instance, so we can terminate it later.
75 grpc::Server *server_instance = nullptr;
76 // Mutex to protec this variable.
77 std::mutex wait_for_server;
78 std::condition_variable server_instance_cv;
79 
80 // This function implements the server thread.
RunServer()81 void RunServer() {
82   auto server_address = "0.0.0.0:50051";
83   // Callback interface we implemented above.
84   ServiceImpl service;
85   grpc::ServerBuilder builder;
86   builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
87   builder.RegisterService(&service);
88 
89   // Start the server. Lock to change the variable we're changing.
90   wait_for_server.lock();
91   server_instance = builder.BuildAndStart().release();
92   wait_for_server.unlock();
93   server_instance_cv.notify_one();
94 
95   std::cout << "Server listening on " << server_address << std::endl;
96   // This will block the thread and serve requests.
97   server_instance->Wait();
98 }
99 
100 template <class Builder>
StoreRPC(MonsterStorage::Stub * stub)101 void StoreRPC(MonsterStorage::Stub *stub) {
102   Builder fbb;
103   grpc::ClientContext context;
104   // Build a request with the name set.
105   auto monster_offset = CreateMonster(fbb, 0, 0, 0, fbb.CreateString("Fred"));
106   MessageBuilder mb(std::move(fbb));
107   mb.Finish(monster_offset);
108   auto request = mb.ReleaseMessage<Monster>();
109   flatbuffers::grpc::Message<Stat> response;
110 
111   // The actual RPC.
112   auto status = stub->Store(&context, request, &response);
113 
114   if (status.ok()) {
115     auto resp = response.GetRoot()->id();
116     std::cout << "RPC response: " << resp->str() << std::endl;
117   } else {
118     std::cout << "RPC failed" << std::endl;
119   }
120 }
121 
122 template <class Builder>
RetrieveRPC(MonsterStorage::Stub * stub)123 void RetrieveRPC(MonsterStorage::Stub *stub) {
124   Builder fbb;
125   grpc::ClientContext context;
126   fbb.Clear();
127   auto stat_offset = CreateStat(fbb, fbb.CreateString("Fred"));
128   fbb.Finish(stat_offset);
129   auto request = MessageBuilder(std::move(fbb)).ReleaseMessage<Stat>();
130 
131   flatbuffers::grpc::Message<Monster> response;
132   auto stream = stub->Retrieve(&context, request);
133   while (stream->Read(&response)) {
134     auto resp = response.GetRoot()->name();
135     std::cout << "RPC Streaming response: " << resp->str() << std::endl;
136   }
137 }
138 
grpc_server_test()139 int grpc_server_test() {
140   // Launch server.
141   std::thread server_thread(RunServer);
142 
143   // wait for server to spin up.
144   std::unique_lock<std::mutex> lock(wait_for_server);
145   while (!server_instance) server_instance_cv.wait(lock);
146 
147   // Now connect the client.
148   auto channel = grpc::CreateChannel("localhost:50051",
149                                      grpc::InsecureChannelCredentials());
150   auto stub = MyGame::Example::MonsterStorage::NewStub(channel);
151 
152   StoreRPC<MessageBuilder>(stub.get());
153   StoreRPC<FlatBufferBuilder>(stub.get());
154 
155   RetrieveRPC<MessageBuilder>(stub.get());
156   RetrieveRPC<FlatBufferBuilder>(stub.get());
157 
158 
159 #if !FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
160   {
161     // Test that an invalid request errors out correctly
162     grpc::ClientContext context;
163     flatbuffers::grpc::Message<Monster> request;  // simulate invalid message
164     flatbuffers::grpc::Message<Stat> response;
165     auto status = stub->Store(&context, request, &response);
166     // The rpc status should be INTERNAL to indicate a verification error. This
167     // matches the protobuf gRPC status code for an unparseable message.
168     assert(!status.ok());
169     assert(status.error_code() == ::grpc::StatusCode::INTERNAL);
170     assert(strcmp(status.error_message().c_str(),
171                   "Message verification failed") == 0);
172   }
173 #endif
174 
175   server_instance->Shutdown();
176 
177   server_thread.join();
178 
179   delete server_instance;
180 
181   return 0;
182 }
183 
main(int,const char * [])184 int main(int /*argc*/, const char * /*argv*/ []) {
185   message_builder_tests();
186   grpc_server_test();
187 
188   if (!testing_fails) {
189     TEST_OUTPUT_LINE("ALL TESTS PASSED");
190     return 0;
191   } else {
192     TEST_OUTPUT_LINE("%d FAILED TESTS", testing_fails);
193     return 1;
194   }
195 }
196 
197