channel.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 <vector>
  34. #include "grpc/support/log.h"
  35. #include <node.h>
  36. #include <nan.h>
  37. #include "grpc/grpc.h"
  38. #include "grpc/grpc_security.h"
  39. #include "call.h"
  40. #include "channel.h"
  41. #include "completion_queue_async_worker.h"
  42. #include "channel_credentials.h"
  43. #include "timeval.h"
  44. namespace grpc {
  45. namespace node {
  46. using Nan::Callback;
  47. using Nan::EscapableHandleScope;
  48. using Nan::HandleScope;
  49. using Nan::Maybe;
  50. using Nan::MaybeLocal;
  51. using Nan::ObjectWrap;
  52. using Nan::Persistent;
  53. using Nan::Utf8String;
  54. using v8::Array;
  55. using v8::Exception;
  56. using v8::Function;
  57. using v8::FunctionTemplate;
  58. using v8::Integer;
  59. using v8::Local;
  60. using v8::Number;
  61. using v8::Object;
  62. using v8::String;
  63. using v8::Value;
  64. Callback *Channel::constructor;
  65. Persistent<FunctionTemplate> Channel::fun_tpl;
  66. bool ParseChannelArgs(Local<Value> args_val,
  67. grpc_channel_args **channel_args_ptr) {
  68. if (args_val->IsUndefined() || args_val->IsNull()) {
  69. *channel_args_ptr = NULL;
  70. return true;
  71. }
  72. if (!args_val->IsObject()) {
  73. *channel_args_ptr = NULL;
  74. return false;
  75. }
  76. grpc_channel_args *channel_args = reinterpret_cast<grpc_channel_args*>(
  77. malloc(sizeof(grpc_channel_args)));
  78. *channel_args_ptr = channel_args;
  79. Local<Object> args_hash = Nan::To<Object>(args_val).ToLocalChecked();
  80. Local<Array> keys = Nan::GetOwnPropertyNames(args_hash).ToLocalChecked();
  81. channel_args->num_args = keys->Length();
  82. channel_args->args = reinterpret_cast<grpc_arg *>(
  83. calloc(channel_args->num_args, sizeof(grpc_arg)));
  84. for (unsigned int i = 0; i < channel_args->num_args; i++) {
  85. Local<Value> key = Nan::Get(keys, i).ToLocalChecked();
  86. Utf8String key_str(key);
  87. if (*key_str == NULL) {
  88. // Key string onversion failed
  89. return false;
  90. }
  91. Local<Value> value = Nan::Get(args_hash, key).ToLocalChecked();
  92. if (value->IsInt32()) {
  93. channel_args->args[i].type = GRPC_ARG_INTEGER;
  94. channel_args->args[i].value.integer = Nan::To<int32_t>(value).FromJust();
  95. } else if (value->IsString()) {
  96. Utf8String val_str(value);
  97. channel_args->args[i].type = GRPC_ARG_STRING;
  98. channel_args->args[i].value.string = reinterpret_cast<char*>(
  99. calloc(val_str.length() + 1,sizeof(char)));
  100. memcpy(channel_args->args[i].value.string,
  101. *val_str, val_str.length() + 1);
  102. } else {
  103. // The value does not match either of the accepted types
  104. return false;
  105. }
  106. channel_args->args[i].key = reinterpret_cast<char*>(
  107. calloc(key_str.length() + 1, sizeof(char)));
  108. memcpy(channel_args->args[i].key, *key_str, key_str.length() + 1);
  109. }
  110. return true;
  111. }
  112. void DeallocateChannelArgs(grpc_channel_args *channel_args) {
  113. if (channel_args == NULL) {
  114. return;
  115. }
  116. for (size_t i = 0; i < channel_args->num_args; i++) {
  117. if (channel_args->args[i].key == NULL) {
  118. /* NULL key implies that this argument and all subsequent arguments failed
  119. * to parse */
  120. break;
  121. }
  122. free(channel_args->args[i].key);
  123. if (channel_args->args[i].type == GRPC_ARG_STRING) {
  124. free(channel_args->args[i].value.string);
  125. }
  126. }
  127. free(channel_args->args);
  128. free(channel_args);
  129. }
  130. Channel::Channel(grpc_channel *channel) : wrapped_channel(channel) {}
  131. Channel::~Channel() {
  132. if (wrapped_channel != NULL) {
  133. grpc_channel_destroy(wrapped_channel);
  134. }
  135. }
  136. void Channel::Init(Local<Object> exports) {
  137. Nan::HandleScope scope;
  138. Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
  139. tpl->SetClassName(Nan::New("Channel").ToLocalChecked());
  140. tpl->InstanceTemplate()->SetInternalFieldCount(1);
  141. Nan::SetPrototypeMethod(tpl, "close", Close);
  142. Nan::SetPrototypeMethod(tpl, "getTarget", GetTarget);
  143. Nan::SetPrototypeMethod(tpl, "getConnectivityState", GetConnectivityState);
  144. Nan::SetPrototypeMethod(tpl, "watchConnectivityState",
  145. WatchConnectivityState);
  146. fun_tpl.Reset(tpl);
  147. Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked();
  148. Nan::Set(exports, Nan::New("Channel").ToLocalChecked(), ctr);
  149. constructor = new Callback(ctr);
  150. }
  151. bool Channel::HasInstance(Local<Value> val) {
  152. HandleScope scope;
  153. return Nan::New(fun_tpl)->HasInstance(val);
  154. }
  155. grpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; }
  156. NAN_METHOD(Channel::New) {
  157. if (info.IsConstructCall()) {
  158. if (!info[0]->IsString()) {
  159. return Nan::ThrowTypeError(
  160. "Channel expects a string, a credential and an object");
  161. }
  162. grpc_channel *wrapped_channel;
  163. // Owned by the Channel object
  164. Utf8String host(info[0]);
  165. grpc_channel_credentials *creds;
  166. if (!ChannelCredentials::HasInstance(info[1])) {
  167. return Nan::ThrowTypeError(
  168. "Channel's second argument must be a ChannelCredentials");
  169. }
  170. ChannelCredentials *creds_object = ObjectWrap::Unwrap<ChannelCredentials>(
  171. Nan::To<Object>(info[1]).ToLocalChecked());
  172. creds = creds_object->GetWrappedCredentials();
  173. grpc_channel_args *channel_args_ptr = NULL;
  174. if (!ParseChannelArgs(info[2], &channel_args_ptr)) {
  175. DeallocateChannelArgs(channel_args_ptr);
  176. return Nan::ThrowTypeError("Channel options must be an object with "
  177. "string keys and integer or string values");
  178. }
  179. if (creds == NULL) {
  180. wrapped_channel = grpc_insecure_channel_create(*host, channel_args_ptr,
  181. NULL);
  182. } else {
  183. wrapped_channel =
  184. grpc_secure_channel_create(creds, *host, channel_args_ptr, NULL);
  185. }
  186. DeallocateChannelArgs(channel_args_ptr);
  187. Channel *channel = new Channel(wrapped_channel);
  188. channel->Wrap(info.This());
  189. info.GetReturnValue().Set(info.This());
  190. return;
  191. } else {
  192. const int argc = 3;
  193. Local<Value> argv[argc] = {info[0], info[1], info[2]};
  194. MaybeLocal<Object> maybe_instance = constructor->GetFunction()->NewInstance(
  195. argc, argv);
  196. if (maybe_instance.IsEmpty()) {
  197. // There's probably a pending exception
  198. return;
  199. } else {
  200. info.GetReturnValue().Set(maybe_instance.ToLocalChecked());
  201. }
  202. }
  203. }
  204. NAN_METHOD(Channel::Close) {
  205. if (!HasInstance(info.This())) {
  206. return Nan::ThrowTypeError("close can only be called on Channel objects");
  207. }
  208. Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
  209. if (channel->wrapped_channel != NULL) {
  210. grpc_channel_destroy(channel->wrapped_channel);
  211. channel->wrapped_channel = NULL;
  212. }
  213. }
  214. NAN_METHOD(Channel::GetTarget) {
  215. if (!HasInstance(info.This())) {
  216. return Nan::ThrowTypeError("getTarget can only be called on Channel objects");
  217. }
  218. Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
  219. info.GetReturnValue().Set(Nan::New(
  220. grpc_channel_get_target(channel->wrapped_channel)).ToLocalChecked());
  221. }
  222. NAN_METHOD(Channel::GetConnectivityState) {
  223. if (!HasInstance(info.This())) {
  224. return Nan::ThrowTypeError(
  225. "getConnectivityState can only be called on Channel objects");
  226. }
  227. Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
  228. int try_to_connect = (int)info[0]->Equals(Nan::True());
  229. info.GetReturnValue().Set(
  230. grpc_channel_check_connectivity_state(channel->wrapped_channel,
  231. try_to_connect));
  232. }
  233. NAN_METHOD(Channel::WatchConnectivityState) {
  234. if (!HasInstance(info.This())) {
  235. return Nan::ThrowTypeError(
  236. "watchConnectivityState can only be called on Channel objects");
  237. }
  238. if (!info[0]->IsUint32()) {
  239. return Nan::ThrowTypeError(
  240. "watchConnectivityState's first argument must be a channel state");
  241. }
  242. if (!(info[1]->IsNumber() || info[1]->IsDate())) {
  243. return Nan::ThrowTypeError(
  244. "watchConnectivityState's second argument must be a date or a number");
  245. }
  246. if (!info[2]->IsFunction()) {
  247. return Nan::ThrowTypeError(
  248. "watchConnectivityState's third argument must be a callback");
  249. }
  250. grpc_connectivity_state last_state =
  251. static_cast<grpc_connectivity_state>(
  252. Nan::To<uint32_t>(info[0]).FromJust());
  253. double deadline = Nan::To<double>(info[1]).FromJust();
  254. Local<Function> callback_func = info[2].As<Function>();
  255. Nan::Callback *callback = new Callback(callback_func);
  256. Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
  257. unique_ptr<OpVec> ops(new OpVec());
  258. grpc_channel_watch_connectivity_state(
  259. channel->wrapped_channel, last_state, MillisecondsToTimespec(deadline),
  260. CompletionQueueAsyncWorker::GetQueue(),
  261. new struct tag(callback,
  262. ops.release(),
  263. shared_ptr<Resources>(nullptr)));
  264. CompletionQueueAsyncWorker::Next();
  265. }
  266. } // namespace node
  267. } // namespace grpc