server.cc 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 <node.h>
  36. #include <nan.h>
  37. #include <vector>
  38. #include "grpc/grpc.h"
  39. #include "grpc/grpc_security.h"
  40. #include "grpc/support/log.h"
  41. #include "call.h"
  42. #include "completion_queue_async_worker.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>(
  93. TimespecToMilliseconds(details.deadline)).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 {
  107. return "new_call";
  108. }
  109. };
  110. Server::Server(grpc_server *server) : wrapped_server(server) {
  111. shutdown_queue = grpc_completion_queue_create(NULL);
  112. grpc_server_register_completion_queue(server, shutdown_queue, NULL);
  113. }
  114. Server::~Server() {
  115. this->ShutdownServer();
  116. grpc_completion_queue_shutdown(this->shutdown_queue);
  117. grpc_server_destroy(this->wrapped_server);
  118. grpc_completion_queue_destroy(this->shutdown_queue);
  119. }
  120. void Server::Init(Local<Object> exports) {
  121. HandleScope scope;
  122. Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
  123. tpl->SetClassName(Nan::New("Server").ToLocalChecked());
  124. tpl->InstanceTemplate()->SetInternalFieldCount(1);
  125. Nan::SetPrototypeMethod(tpl, "requestCall", RequestCall);
  126. Nan::SetPrototypeMethod(tpl, "addHttp2Port", AddHttp2Port);
  127. Nan::SetPrototypeMethod(tpl, "start", Start);
  128. Nan::SetPrototypeMethod(tpl, "tryShutdown", TryShutdown);
  129. Nan::SetPrototypeMethod(tpl, "forceShutdown", ForceShutdown);
  130. fun_tpl.Reset(tpl);
  131. Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked();
  132. Nan::Set(exports, Nan::New("Server").ToLocalChecked(), ctr);
  133. constructor = new Callback(ctr);
  134. }
  135. bool Server::HasInstance(Local<Value> val) {
  136. HandleScope scope;
  137. return Nan::New(fun_tpl)->HasInstance(val);
  138. }
  139. void Server::ShutdownServer() {
  140. grpc_server_shutdown_and_notify(this->wrapped_server,
  141. this->shutdown_queue,
  142. NULL);
  143. grpc_server_cancel_all_calls(this->wrapped_server);
  144. grpc_completion_queue_pluck(this->shutdown_queue, NULL,
  145. gpr_inf_future(GPR_CLOCK_REALTIME), NULL);
  146. }
  147. NAN_METHOD(Server::New) {
  148. /* If this is not a constructor call, make a constructor call and return
  149. the result */
  150. if (!info.IsConstructCall()) {
  151. const int argc = 1;
  152. Local<Value> argv[argc] = {info[0]};
  153. MaybeLocal<Object> maybe_instance = constructor->GetFunction()->NewInstance(
  154. argc, argv);
  155. if (maybe_instance.IsEmpty()) {
  156. // There's probably a pending exception
  157. return;
  158. } else {
  159. info.GetReturnValue().Set(maybe_instance.ToLocalChecked());
  160. return;
  161. }
  162. }
  163. grpc_server *wrapped_server;
  164. grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue();
  165. grpc_channel_args *channel_args;
  166. if (!ParseChannelArgs(info[0], &channel_args)) {
  167. DeallocateChannelArgs(channel_args);
  168. return Nan::ThrowTypeError("Server options must be an object with "
  169. "string keys and integer or string values");
  170. }
  171. wrapped_server = grpc_server_create(channel_args, NULL);
  172. DeallocateChannelArgs(channel_args);
  173. grpc_server_register_completion_queue(wrapped_server, queue, NULL);
  174. Server *server = new Server(wrapped_server);
  175. server->Wrap(info.This());
  176. info.GetReturnValue().Set(info.This());
  177. }
  178. NAN_METHOD(Server::RequestCall) {
  179. if (!HasInstance(info.This())) {
  180. return Nan::ThrowTypeError("requestCall can only be called on a Server");
  181. }
  182. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  183. NewCallOp *op = new NewCallOp();
  184. unique_ptr<OpVec> ops(new OpVec());
  185. ops->push_back(unique_ptr<Op>(op));
  186. grpc_call_error error = grpc_server_request_call(
  187. server->wrapped_server, &op->call, &op->details, &op->request_metadata,
  188. CompletionQueueAsyncWorker::GetQueue(),
  189. CompletionQueueAsyncWorker::GetQueue(),
  190. new struct tag(new Callback(info[0].As<Function>()), ops.release(),
  191. shared_ptr<Resources>(nullptr)));
  192. if (error != GRPC_CALL_OK) {
  193. return Nan::ThrowError(nanErrorWithCode("requestCall failed", error));
  194. }
  195. CompletionQueueAsyncWorker::Next();
  196. }
  197. NAN_METHOD(Server::AddHttp2Port) {
  198. if (!HasInstance(info.This())) {
  199. return Nan::ThrowTypeError(
  200. "addHttp2Port can only be called on a Server");
  201. }
  202. if (!info[0]->IsString()) {
  203. return Nan::ThrowTypeError(
  204. "addHttp2Port's first argument must be a String");
  205. }
  206. if (!ServerCredentials::HasInstance(info[1])) {
  207. return Nan::ThrowTypeError(
  208. "addHttp2Port's second argument must be ServerCredentials");
  209. }
  210. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  211. ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(
  212. Nan::To<Object>(info[1]).ToLocalChecked());
  213. grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();
  214. int port;
  215. if (creds == NULL) {
  216. port = grpc_server_add_insecure_http2_port(server->wrapped_server,
  217. *Utf8String(info[0]));
  218. } else {
  219. port = grpc_server_add_secure_http2_port(server->wrapped_server,
  220. *Utf8String(info[0]),
  221. creds);
  222. }
  223. info.GetReturnValue().Set(Nan::New<Number>(port));
  224. }
  225. NAN_METHOD(Server::Start) {
  226. Nan::HandleScope scope;
  227. if (!HasInstance(info.This())) {
  228. return Nan::ThrowTypeError("start can only be called on a Server");
  229. }
  230. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  231. grpc_server_start(server->wrapped_server);
  232. }
  233. NAN_METHOD(Server::TryShutdown) {
  234. Nan::HandleScope scope;
  235. if (!HasInstance(info.This())) {
  236. return Nan::ThrowTypeError("tryShutdown can only be called on a Server");
  237. }
  238. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  239. unique_ptr<OpVec> ops(new OpVec());
  240. grpc_server_shutdown_and_notify(
  241. server->wrapped_server,
  242. CompletionQueueAsyncWorker::GetQueue(),
  243. new struct tag(new Nan::Callback(info[0].As<Function>()), ops.release(),
  244. shared_ptr<Resources>(nullptr)));
  245. CompletionQueueAsyncWorker::Next();
  246. }
  247. NAN_METHOD(Server::ForceShutdown) {
  248. Nan::HandleScope scope;
  249. if (!HasInstance(info.This())) {
  250. return Nan::ThrowTypeError("forceShutdown can only be called on a Server");
  251. }
  252. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  253. server->ShutdownServer();
  254. }
  255. } // namespace node
  256. } // namespace grpc