3 * Copyright 2015 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
21 #include "grpc/support/log.h"
27 #include "channel_credentials.h"
28 #include "completion_queue.h"
29 #include "grpc/grpc.h"
30 #include "grpc/grpc_security.h"
38 using Nan::EscapableHandleScope;
39 using Nan::HandleScope;
41 using Nan::MaybeLocal;
42 using Nan::ObjectWrap;
43 using Nan::Persistent;
44 using Nan::Utf8String;
49 using v8::FunctionTemplate;
57 Callback *Channel::constructor;
58 Persistent<FunctionTemplate> Channel::fun_tpl;
60 static const char grpc_node_user_agent[] = "grpc-node/" GRPC_NODE_VERSION;
62 void PopulateUserAgentChannelArg(grpc_arg *arg) {
63 size_t key_len = sizeof(GRPC_ARG_PRIMARY_USER_AGENT_STRING);
64 size_t val_len = sizeof(grpc_node_user_agent);
65 arg->key = reinterpret_cast<char *>(calloc(key_len, sizeof(char)));
66 memcpy(arg->key, GRPC_ARG_PRIMARY_USER_AGENT_STRING, key_len);
67 arg->type = GRPC_ARG_STRING;
68 arg->value.string = reinterpret_cast<char *>(calloc(val_len, sizeof(char)));
69 memcpy(arg->value.string, grpc_node_user_agent, val_len);
73 bool ParseChannelArgs(Local<Value> args_val,
74 grpc_channel_args **channel_args_ptr) {
75 if (args_val->IsUndefined() || args_val->IsNull()) {
76 // Treat null and undefined the same as an empty object
77 args_val = Nan::New<Object>();
79 if (!args_val->IsObject()) {
80 *channel_args_ptr = NULL;
83 grpc_channel_args *channel_args =
84 reinterpret_cast<grpc_channel_args *>(malloc(sizeof(grpc_channel_args)));
85 *channel_args_ptr = channel_args;
86 Local<Object> args_hash = Nan::To<Object>(args_val).ToLocalChecked();
87 Local<Array> keys = Nan::GetOwnPropertyNames(args_hash).ToLocalChecked();
88 channel_args->num_args = keys->Length();
89 /* This is an ugly hack to add in the user agent string argument if it wasn't
90 * passed by the user */
91 bool has_user_agent_arg = Nan::HasOwnProperty(
92 args_hash, Nan::New(GRPC_ARG_PRIMARY_USER_AGENT_STRING).ToLocalChecked()
94 if (!has_user_agent_arg) {
95 channel_args->num_args += 1;
97 channel_args->args = reinterpret_cast<grpc_arg *>(
98 calloc(channel_args->num_args, sizeof(grpc_arg)));
99 for (unsigned int i = 0; i < keys->Length(); i++) {
100 Local<Value> key = Nan::Get(keys, i).ToLocalChecked();
101 Utf8String key_str(key);
102 if (*key_str == NULL) {
103 // Key string conversion failed
106 Local<Value> value = Nan::Get(args_hash, key).ToLocalChecked();
107 if (value->IsInt32()) {
108 channel_args->args[i].type = GRPC_ARG_INTEGER;
109 channel_args->args[i].value.integer = Nan::To<int32_t>(value).FromJust();
110 } else if (value->IsString()) {
111 Utf8String val_str(value);
112 channel_args->args[i].type = GRPC_ARG_STRING;
113 /* Append the grpc-node user agent string after the application user agent
114 * string, and put the combination at the beginning of the user agent string
116 if (strcmp(*key_str, GRPC_ARG_PRIMARY_USER_AGENT_STRING) == 0) {
117 /* val_str.length() is the string length and does not include the
118 * trailing 0 byte. sizeof(grpc_node_user_agent) is the array length,
119 * so it does include the trailing 0 byte. */
120 size_t val_str_len = val_str.length();
121 size_t user_agent_len = sizeof(grpc_node_user_agent);
122 /* This is the length of the two parts of the string, plus the space in
123 * between, plus the 0 at the end, which is included in user_agent_len.
125 channel_args->args[i].value.string =
126 reinterpret_cast<char *>(calloc(val_str_len + user_agent_len + 1, sizeof(char)));
127 memcpy(channel_args->args[i].value.string, *val_str,
129 channel_args->args[i].value.string[val_str_len] = ' ';
130 memcpy(channel_args->args[i].value.string + val_str_len + 1,
131 grpc_node_user_agent, user_agent_len);
133 channel_args->args[i].value.string =
134 reinterpret_cast<char *>(calloc(val_str.length() + 1, sizeof(char)));
135 memcpy(channel_args->args[i].value.string, *val_str,
136 val_str.length() + 1);
139 // The value does not match either of the accepted types
142 channel_args->args[i].key =
143 reinterpret_cast<char *>(calloc(key_str.length() + 1, sizeof(char)));
144 memcpy(channel_args->args[i].key, *key_str, key_str.length() + 1);
146 /* Add a standard user agent string argument if none was provided */
147 if (!has_user_agent_arg) {
148 size_t index = channel_args->num_args - 1;
149 PopulateUserAgentChannelArg(&channel_args->args[index]);
154 void DeallocateChannelArgs(grpc_channel_args *channel_args) {
155 if (channel_args == NULL) {
158 for (size_t i = 0; i < channel_args->num_args; i++) {
159 if (channel_args->args[i].key == NULL) {
160 /* NULL key implies that this argument and all subsequent arguments failed
164 free(channel_args->args[i].key);
165 if (channel_args->args[i].type == GRPC_ARG_STRING) {
166 free(channel_args->args[i].value.string);
169 free(channel_args->args);
173 Channel::Channel(grpc_channel *channel) : wrapped_channel(channel) {}
175 Channel::~Channel() {
176 gpr_log(GPR_DEBUG, "Destroying channel");
177 if (wrapped_channel != NULL) {
178 grpc_channel_destroy(wrapped_channel);
182 void Channel::Init(Local<Object> exports) {
183 Nan::HandleScope scope;
184 Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
185 tpl->SetClassName(Nan::New("Channel").ToLocalChecked());
186 tpl->InstanceTemplate()->SetInternalFieldCount(1);
187 Nan::SetPrototypeMethod(tpl, "close", Close);
188 Nan::SetPrototypeMethod(tpl, "getTarget", GetTarget);
189 Nan::SetPrototypeMethod(tpl, "getConnectivityState", GetConnectivityState);
190 Nan::SetPrototypeMethod(tpl, "watchConnectivityState",
191 WatchConnectivityState);
192 Nan::SetPrototypeMethod(tpl, "createCall", CreateCall);
194 Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked();
195 Nan::Set(exports, Nan::New("Channel").ToLocalChecked(), ctr);
196 constructor = new Callback(ctr);
199 bool Channel::HasInstance(Local<Value> val) {
201 return Nan::New(fun_tpl)->HasInstance(val);
204 grpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; }
206 NAN_METHOD(Channel::New) {
207 if (info.IsConstructCall()) {
208 if (!info[0]->IsString()) {
209 return Nan::ThrowTypeError(
210 "Channel's first argument (address) must be a string");
212 grpc_channel *wrapped_channel;
213 // Owned by the Channel object
214 Utf8String host(info[0]);
215 grpc_channel_credentials *creds;
216 if (!ChannelCredentials::HasInstance(info[1])) {
217 return Nan::ThrowTypeError(
218 "Channel's second argument (credentials) must be a ChannelCredentials");
220 ChannelCredentials *creds_object = ObjectWrap::Unwrap<ChannelCredentials>(
221 Nan::To<Object>(info[1]).ToLocalChecked());
222 creds = creds_object->GetWrappedCredentials();
223 grpc_channel_args *channel_args_ptr = NULL;
224 if (!ParseChannelArgs(info[2], &channel_args_ptr)) {
225 DeallocateChannelArgs(channel_args_ptr);
226 return Nan::ThrowTypeError(
227 "Channel third argument (options) must be an object with "
228 "string keys and integer or string values");
232 grpc_insecure_channel_create(*host, channel_args_ptr, NULL);
235 grpc_secure_channel_create(creds, *host, channel_args_ptr, NULL);
237 DeallocateChannelArgs(channel_args_ptr);
238 Channel *channel = new Channel(wrapped_channel);
239 channel->Wrap(info.This());
240 info.GetReturnValue().Set(info.This());
244 Local<Value> argv[argc] = {info[0], info[1], info[2]};
245 MaybeLocal<Object> maybe_instance =
246 Nan::NewInstance(constructor->GetFunction(), argc, argv);
247 if (maybe_instance.IsEmpty()) {
248 // There's probably a pending exception
251 info.GetReturnValue().Set(maybe_instance.ToLocalChecked());
256 NAN_METHOD(Channel::Close) {
257 if (!HasInstance(info.This())) {
258 return Nan::ThrowTypeError("close can only be called on Channel objects");
260 Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
261 if (channel->wrapped_channel != NULL) {
262 grpc_channel_destroy(channel->wrapped_channel);
263 channel->wrapped_channel = NULL;
267 NAN_METHOD(Channel::GetTarget) {
268 if (!HasInstance(info.This())) {
269 return Nan::ThrowTypeError(
270 "getTarget can only be called on Channel objects");
272 Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
273 if (channel->wrapped_channel == NULL) {
274 return Nan::ThrowError(
275 "Cannot call getTarget on a closed Channel");
277 info.GetReturnValue().Set(
278 Nan::New(grpc_channel_get_target(channel->wrapped_channel))
282 NAN_METHOD(Channel::GetConnectivityState) {
283 if (!HasInstance(info.This())) {
284 return Nan::ThrowTypeError(
285 "getConnectivityState can only be called on Channel objects");
287 Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
288 if (channel->wrapped_channel == NULL) {
289 return Nan::ThrowError(
290 "Cannot call getConnectivityState on a closed Channel");
292 int try_to_connect = (int)info[0]->StrictEquals(Nan::True());
293 info.GetReturnValue().Set(grpc_channel_check_connectivity_state(
294 channel->wrapped_channel, try_to_connect));
297 NAN_METHOD(Channel::WatchConnectivityState) {
298 if (!HasInstance(info.This())) {
299 return Nan::ThrowTypeError(
300 "watchConnectivityState can only be called on Channel objects");
302 if (!info[0]->IsUint32()) {
303 return Nan::ThrowTypeError(
304 "watchConnectivityState's first argument must be a channel state");
306 if (!(info[1]->IsNumber() || info[1]->IsDate())) {
307 return Nan::ThrowTypeError(
308 "watchConnectivityState's second argument must be a date or a number");
310 if (!info[2]->IsFunction()) {
311 return Nan::ThrowTypeError(
312 "watchConnectivityState's third argument must be a callback");
314 Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
315 if (channel->wrapped_channel == NULL) {
316 return Nan::ThrowError(
317 "Cannot call watchConnectivityState on a closed Channel");
319 grpc_connectivity_state last_state = static_cast<grpc_connectivity_state>(
320 Nan::To<uint32_t>(info[0]).FromJust());
321 double deadline = Nan::To<double>(info[1]).FromJust();
322 Local<Function> callback_func = info[2].As<Function>();
323 Nan::Callback *callback = new Callback(callback_func);
324 unique_ptr<OpVec> ops(new OpVec());
325 grpc_channel_watch_connectivity_state(
326 channel->wrapped_channel, last_state, MillisecondsToTimespec(deadline),
327 GetCompletionQueue(),
328 new struct tag(callback, ops.release(), NULL, Nan::Null()));
329 CompletionQueueNext();
332 NAN_METHOD(Channel::CreateCall) {
338 * 4: propagation flags
340 if (!HasInstance(info.This())) {
341 return Nan::ThrowTypeError(
342 "createCall can only be called on Channel objects");
344 if (!info[0]->IsString()){
345 return Nan::ThrowTypeError("createCall's first argument must be a string");
347 if (!(info[1]->IsNumber() || info[1]->IsDate())) {
348 return Nan::ThrowTypeError(
349 "createcall's second argument must be a date or a number");
351 // These arguments are at the end because they are optional
352 grpc_call *parent_call = NULL;
353 if (Call::HasInstance(info[3])) {
355 ObjectWrap::Unwrap<Call>(Nan::To<Object>(info[3]).ToLocalChecked());
356 parent_call = parent_obj->GetWrappedCall();
357 } else if (!(info[3]->IsUndefined() || info[3]->IsNull())) {
358 return Nan::ThrowTypeError(
359 "createCall's fourth argument must be another call, if provided");
361 uint32_t propagate_flags = GRPC_PROPAGATE_DEFAULTS;
362 if (info[4]->IsUint32()) {
363 propagate_flags = Nan::To<uint32_t>(info[4]).FromJust();
364 } else if (!(info[4]->IsUndefined() || info[4]->IsNull())) {
365 return Nan::ThrowTypeError(
366 "createCall's fifth argument must be propagate flags, if provided");
368 Channel *channel = ObjectWrap::Unwrap<Channel>(info.This());
369 grpc_channel *wrapped_channel = channel->GetWrappedChannel();
370 if (wrapped_channel == NULL) {
371 return Nan::ThrowError("Cannot createCall with a closed Channel");
374 CreateSliceFromString(Nan::To<String>(info[0]).ToLocalChecked());
375 double deadline = Nan::To<double>(info[1]).FromJust();
376 grpc_call *wrapped_call = NULL;
377 if (info[2]->IsString()) {
378 grpc_slice *host = new grpc_slice;
380 CreateSliceFromString(Nan::To<String>(info[2]).ToLocalChecked());
381 wrapped_call = grpc_channel_create_call(
382 wrapped_channel, parent_call, propagate_flags, GetCompletionQueue(),
383 method, host, MillisecondsToTimespec(deadline), NULL);
385 } else if (info[2]->IsUndefined() || info[2]->IsNull()) {
386 wrapped_call = grpc_channel_create_call(
387 wrapped_channel, parent_call, propagate_flags, GetCompletionQueue(),
388 method, NULL, MillisecondsToTimespec(deadline), NULL);
390 return Nan::ThrowTypeError("createCall's third argument must be a string");
392 grpc_slice_unref(method);
393 info.GetReturnValue().Set(Call::WrapStruct(wrapped_call));