server.cc 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*
  2. *
  3. * Copyright 2015, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #include <memory>
  34. #include "server.h"
  35. #include <nan.h>
  36. #include <node.h>
  37. #include <vector>
  38. #include "call.h"
  39. #include "completion_queue_async_worker.h"
  40. #include "grpc/grpc.h"
  41. #include "grpc/grpc_security.h"
  42. #include "grpc/support/log.h"
  43. #include "server_credentials.h"
  44. #include "timeval.h"
  45. namespace grpc {
  46. namespace node {
  47. using Nan::Callback;
  48. using Nan::EscapableHandleScope;
  49. using Nan::HandleScope;
  50. using Nan::Maybe;
  51. using Nan::MaybeLocal;
  52. using Nan::ObjectWrap;
  53. using Nan::Persistent;
  54. using Nan::Utf8String;
  55. using std::unique_ptr;
  56. using v8::Array;
  57. using v8::Boolean;
  58. using v8::Date;
  59. using v8::Exception;
  60. using v8::Function;
  61. using v8::FunctionTemplate;
  62. using v8::Local;
  63. using v8::Number;
  64. using v8::Object;
  65. using v8::String;
  66. using v8::Value;
  67. Nan::Callback *Server::constructor;
  68. Persistent<FunctionTemplate> Server::fun_tpl;
  69. class NewCallOp : public Op {
  70. public:
  71. NewCallOp() {
  72. call = NULL;
  73. grpc_call_details_init(&details);
  74. grpc_metadata_array_init(&request_metadata);
  75. }
  76. ~NewCallOp() {
  77. grpc_call_details_destroy(&details);
  78. grpc_metadata_array_destroy(&request_metadata);
  79. }
  80. Local<Value> GetNodeValue() const {
  81. Nan::EscapableHandleScope scope;
  82. if (call == NULL) {
  83. return scope.Escape(Nan::Null());
  84. }
  85. Local<Object> obj = Nan::New<Object>();
  86. Nan::Set(obj, Nan::New("call").ToLocalChecked(), Call::WrapStruct(call));
  87. Nan::Set(obj, Nan::New("method").ToLocalChecked(),
  88. Nan::New(details.method).ToLocalChecked());
  89. Nan::Set(obj, Nan::New("host").ToLocalChecked(),
  90. Nan::New(details.host).ToLocalChecked());
  91. Nan::Set(obj, Nan::New("deadline").ToLocalChecked(),
  92. Nan::New<Date>(TimespecToMilliseconds(details.deadline))
  93. .ToLocalChecked());
  94. Nan::Set(obj, Nan::New("metadata").ToLocalChecked(),
  95. ParseMetadata(&request_metadata));
  96. return scope.Escape(obj);
  97. }
  98. bool ParseOp(Local<Value> value, grpc_op *out,
  99. shared_ptr<Resources> resources) {
  100. return true;
  101. }
  102. grpc_call *call;
  103. grpc_call_details details;
  104. grpc_metadata_array request_metadata;
  105. protected:
  106. std::string GetTypeString() const { return "new_call"; }
  107. };
  108. Server::Server(grpc_server *server) : wrapped_server(server) {
  109. shutdown_queue = grpc_completion_queue_create(NULL);
  110. grpc_server_register_non_listening_completion_queue(server, shutdown_queue,
  111. NULL);
  112. }
  113. Server::~Server() {
  114. this->ShutdownServer();
  115. grpc_completion_queue_shutdown(this->shutdown_queue);
  116. grpc_server_destroy(this->wrapped_server);
  117. grpc_completion_queue_destroy(this->shutdown_queue);
  118. }
  119. void Server::Init(Local<Object> exports) {
  120. HandleScope scope;
  121. Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
  122. tpl->SetClassName(Nan::New("Server").ToLocalChecked());
  123. tpl->InstanceTemplate()->SetInternalFieldCount(1);
  124. Nan::SetPrototypeMethod(tpl, "requestCall", RequestCall);
  125. Nan::SetPrototypeMethod(tpl, "addHttp2Port", AddHttp2Port);
  126. Nan::SetPrototypeMethod(tpl, "start", Start);
  127. Nan::SetPrototypeMethod(tpl, "tryShutdown", TryShutdown);
  128. Nan::SetPrototypeMethod(tpl, "forceShutdown", ForceShutdown);
  129. fun_tpl.Reset(tpl);
  130. Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked();
  131. Nan::Set(exports, Nan::New("Server").ToLocalChecked(), ctr);
  132. constructor = new Callback(ctr);
  133. }
  134. bool Server::HasInstance(Local<Value> val) {
  135. HandleScope scope;
  136. return Nan::New(fun_tpl)->HasInstance(val);
  137. }
  138. void Server::ShutdownServer() {
  139. grpc_server_shutdown_and_notify(this->wrapped_server, this->shutdown_queue,
  140. NULL);
  141. grpc_server_cancel_all_calls(this->wrapped_server);
  142. grpc_completion_queue_pluck(this->shutdown_queue, NULL,
  143. gpr_inf_future(GPR_CLOCK_REALTIME), NULL);
  144. }
  145. NAN_METHOD(Server::New) {
  146. /* If this is not a constructor call, make a constructor call and return
  147. the result */
  148. if (!info.IsConstructCall()) {
  149. const int argc = 1;
  150. Local<Value> argv[argc] = {info[0]};
  151. MaybeLocal<Object> maybe_instance =
  152. constructor->GetFunction()->NewInstance(argc, argv);
  153. if (maybe_instance.IsEmpty()) {
  154. // There's probably a pending exception
  155. return;
  156. } else {
  157. info.GetReturnValue().Set(maybe_instance.ToLocalChecked());
  158. return;
  159. }
  160. }
  161. grpc_server *wrapped_server;
  162. grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue();
  163. grpc_channel_args *channel_args;
  164. if (!ParseChannelArgs(info[0], &channel_args)) {
  165. DeallocateChannelArgs(channel_args);
  166. return Nan::ThrowTypeError(
  167. "Server options must be an object with "
  168. "string keys and integer or string values");
  169. }
  170. wrapped_server = grpc_server_create(channel_args, NULL);
  171. DeallocateChannelArgs(channel_args);
  172. grpc_server_register_completion_queue(wrapped_server, queue, NULL);
  173. Server *server = new Server(wrapped_server);
  174. server->Wrap(info.This());
  175. info.GetReturnValue().Set(info.This());
  176. }
  177. NAN_METHOD(Server::RequestCall) {
  178. if (!HasInstance(info.This())) {
  179. return Nan::ThrowTypeError("requestCall can only be called on a Server");
  180. }
  181. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  182. NewCallOp *op = new NewCallOp();
  183. unique_ptr<OpVec> ops(new OpVec());
  184. ops->push_back(unique_ptr<Op>(op));
  185. grpc_call_error error = grpc_server_request_call(
  186. server->wrapped_server, &op->call, &op->details, &op->request_metadata,
  187. CompletionQueueAsyncWorker::GetQueue(),
  188. CompletionQueueAsyncWorker::GetQueue(),
  189. new struct tag(new Callback(info[0].As<Function>()), ops.release(),
  190. shared_ptr<Resources>(nullptr)));
  191. if (error != GRPC_CALL_OK) {
  192. return Nan::ThrowError(nanErrorWithCode("requestCall failed", error));
  193. }
  194. CompletionQueueAsyncWorker::Next();
  195. }
  196. NAN_METHOD(Server::AddHttp2Port) {
  197. if (!HasInstance(info.This())) {
  198. return Nan::ThrowTypeError("addHttp2Port can only be called on a Server");
  199. }
  200. if (!info[0]->IsString()) {
  201. return Nan::ThrowTypeError(
  202. "addHttp2Port's first argument must be a String");
  203. }
  204. if (!ServerCredentials::HasInstance(info[1])) {
  205. return Nan::ThrowTypeError(
  206. "addHttp2Port's second argument must be ServerCredentials");
  207. }
  208. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  209. ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(
  210. Nan::To<Object>(info[1]).ToLocalChecked());
  211. grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();
  212. int port;
  213. if (creds == NULL) {
  214. port = grpc_server_add_insecure_http2_port(server->wrapped_server,
  215. *Utf8String(info[0]));
  216. } else {
  217. port = grpc_server_add_secure_http2_port(server->wrapped_server,
  218. *Utf8String(info[0]), creds);
  219. }
  220. info.GetReturnValue().Set(Nan::New<Number>(port));
  221. }
  222. NAN_METHOD(Server::Start) {
  223. Nan::HandleScope scope;
  224. if (!HasInstance(info.This())) {
  225. return Nan::ThrowTypeError("start can only be called on a Server");
  226. }
  227. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  228. grpc_server_start(server->wrapped_server);
  229. }
  230. NAN_METHOD(Server::TryShutdown) {
  231. Nan::HandleScope scope;
  232. if (!HasInstance(info.This())) {
  233. return Nan::ThrowTypeError("tryShutdown can only be called on a Server");
  234. }
  235. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  236. unique_ptr<OpVec> ops(new OpVec());
  237. grpc_server_shutdown_and_notify(
  238. server->wrapped_server, CompletionQueueAsyncWorker::GetQueue(),
  239. new struct tag(new Nan::Callback(info[0].As<Function>()), ops.release(),
  240. shared_ptr<Resources>(nullptr)));
  241. CompletionQueueAsyncWorker::Next();
  242. }
  243. NAN_METHOD(Server::ForceShutdown) {
  244. Nan::HandleScope scope;
  245. if (!HasInstance(info.This())) {
  246. return Nan::ThrowTypeError("forceShutdown can only be called on a Server");
  247. }
  248. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  249. server->ShutdownServer();
  250. }
  251. } // namespace node
  252. } // namespace grpc