rpc_service.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. Copyright (c) 2020 Sogou, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #ifndef __RPC_SERVICE_H__
  14. #define __RPC_SERVICE_H__
  15. #include <string>
  16. #include <unordered_map>
  17. #include <functional>
  18. #include "rpc_context.h"
  19. #include "rpc_options.h"
  20. namespace srpc
  21. {
  22. class RPCService
  23. {
  24. protected:
  25. using rpc_method_t = std::function<int (RPCWorker&)>;
  26. public:
  27. RPCService(const std::string& name) : name_(name) { }
  28. RPCService(RPCService&& move) = delete;
  29. RPCService& operator=(RPCService&& move) = delete;
  30. RPCService(const RPCService& copy) = delete;
  31. RPCService& operator=(const RPCService& copy) = delete;
  32. virtual ~RPCService() { };
  33. const std::string& get_name() const { return name_; }
  34. const rpc_method_t *find_method(const std::string& method_name) const;
  35. protected:
  36. void add_method(const std::string& method_name, rpc_method_t&& method);
  37. private:
  38. std::unordered_map<std::string, rpc_method_t> methods_;
  39. std::string name_;
  40. };
  41. ////////
  42. // inl
  43. template<class INPUT, class OUTPUT, class SERVICE>
  44. static inline int
  45. ServiceRPCCallImpl(SERVICE *service,
  46. RPCWorker& worker,
  47. void (SERVICE::*rpc)(INPUT *, OUTPUT *, RPCContext *))
  48. {
  49. auto *in = new INPUT;
  50. worker.set_server_input(in);
  51. int status_code = worker.req->deserialize(in);
  52. if (status_code == RPCStatusOK)
  53. {
  54. auto *out = new OUTPUT;
  55. worker.set_server_output(out);
  56. (service->*rpc)(in, out, worker.ctx);
  57. }
  58. return status_code;
  59. }
  60. inline void RPCService::add_method(const std::string& method_name, rpc_method_t&& method)
  61. {
  62. methods_.emplace(method_name, std::move(method));
  63. }
  64. inline const RPCService::rpc_method_t *RPCService::find_method(const std::string& method_name) const
  65. {
  66. const auto it = methods_.find(method_name);
  67. if (it != methods_.cend())
  68. return &it->second;
  69. return NULL;
  70. }
  71. } // namespace srpc
  72. #endif