Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc / ext / channel.cc
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
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
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  */
18
19 #include <vector>
20
21 #include "grpc/support/log.h"
22
23 #include <nan.h>
24 #include <node.h>
25 #include "call.h"
26 #include "channel.h"
27 #include "channel_credentials.h"
28 #include "completion_queue.h"
29 #include "grpc/grpc.h"
30 #include "grpc/grpc_security.h"
31 #include "slice.h"
32 #include "timeval.h"
33
34 namespace grpc {
35 namespace node {
36
37 using Nan::Callback;
38 using Nan::EscapableHandleScope;
39 using Nan::HandleScope;
40 using Nan::Maybe;
41 using Nan::MaybeLocal;
42 using Nan::ObjectWrap;
43 using Nan::Persistent;
44 using Nan::Utf8String;
45
46 using v8::Array;
47 using v8::Exception;
48 using v8::Function;
49 using v8::FunctionTemplate;
50 using v8::Integer;
51 using v8::Local;
52 using v8::Number;
53 using v8::Object;
54 using v8::String;
55 using v8::Value;
56
57 Callback *Channel::constructor;
58 Persistent<FunctionTemplate> Channel::fun_tpl;
59
60 static const char grpc_node_user_agent[] = "grpc-node/" GRPC_NODE_VERSION;
61
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);
70
71 }
72
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>();
78   }
79   if (!args_val->IsObject()) {
80     *channel_args_ptr = NULL;
81     return false;
82   }
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()
93   ).FromJust();
94   if (!has_user_agent_arg) {
95     channel_args->num_args += 1;
96   }
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
104       return false;
105     }
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
115        */
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.
124          */
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,
128                val_str.length());
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);
132       } else {
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);
137       }
138     } else {
139       // The value does not match either of the accepted types
140       return false;
141     }
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);
145   }
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]);
150   }
151   return true;
152 }
153
154 void DeallocateChannelArgs(grpc_channel_args *channel_args) {
155   if (channel_args == NULL) {
156     return;
157   }
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
161        * to parse */
162       break;
163     }
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);
167     }
168   }
169   free(channel_args->args);
170   free(channel_args);
171 }
172
173 Channel::Channel(grpc_channel *channel) : wrapped_channel(channel) {}
174
175 Channel::~Channel() {
176   gpr_log(GPR_DEBUG, "Destroying channel");
177   if (wrapped_channel != NULL) {
178     grpc_channel_destroy(wrapped_channel);
179   }
180 }
181
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);
193   fun_tpl.Reset(tpl);
194   Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked();
195   Nan::Set(exports, Nan::New("Channel").ToLocalChecked(), ctr);
196   constructor = new Callback(ctr);
197 }
198
199 bool Channel::HasInstance(Local<Value> val) {
200   HandleScope scope;
201   return Nan::New(fun_tpl)->HasInstance(val);
202 }
203
204 grpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; }
205
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");
211     }
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");
219     }
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");
229     }
230     if (creds == NULL) {
231       wrapped_channel =
232           grpc_insecure_channel_create(*host, channel_args_ptr, NULL);
233     } else {
234       wrapped_channel =
235           grpc_secure_channel_create(creds, *host, channel_args_ptr, NULL);
236     }
237     DeallocateChannelArgs(channel_args_ptr);
238     Channel *channel = new Channel(wrapped_channel);
239     channel->Wrap(info.This());
240     info.GetReturnValue().Set(info.This());
241     return;
242   } else {
243     const int argc = 3;
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
249       return;
250     } else {
251       info.GetReturnValue().Set(maybe_instance.ToLocalChecked());
252     }
253   }
254 }
255
256 NAN_METHOD(Channel::Close) {
257   if (!HasInstance(info.This())) {
258     return Nan::ThrowTypeError("close can only be called on Channel objects");
259   }
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;
264   }
265 }
266
267 NAN_METHOD(Channel::GetTarget) {
268   if (!HasInstance(info.This())) {
269     return Nan::ThrowTypeError(
270         "getTarget can only be called on Channel objects");
271   }
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");
276   }
277   info.GetReturnValue().Set(
278       Nan::New(grpc_channel_get_target(channel->wrapped_channel))
279           .ToLocalChecked());
280 }
281
282 NAN_METHOD(Channel::GetConnectivityState) {
283   if (!HasInstance(info.This())) {
284     return Nan::ThrowTypeError(
285         "getConnectivityState can only be called on Channel objects");
286   }
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");
291   }
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));
295 }
296
297 NAN_METHOD(Channel::WatchConnectivityState) {
298   if (!HasInstance(info.This())) {
299     return Nan::ThrowTypeError(
300         "watchConnectivityState can only be called on Channel objects");
301   }
302   if (!info[0]->IsUint32()) {
303     return Nan::ThrowTypeError(
304         "watchConnectivityState's first argument must be a channel state");
305   }
306   if (!(info[1]->IsNumber() || info[1]->IsDate())) {
307     return Nan::ThrowTypeError(
308         "watchConnectivityState's second argument must be a date or a number");
309   }
310   if (!info[2]->IsFunction()) {
311     return Nan::ThrowTypeError(
312         "watchConnectivityState's third argument must be a callback");
313   }
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");
318   }
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();
330 }
331
332 NAN_METHOD(Channel::CreateCall) {
333   /* Arguments:
334    * 0: Method
335    * 1: Deadline
336    * 2: host
337    * 3: parent Call
338    * 4: propagation flags
339    */
340   if (!HasInstance(info.This())) {
341     return Nan::ThrowTypeError(
342         "createCall can only be called on Channel objects");
343   }
344   if (!info[0]->IsString()){
345     return Nan::ThrowTypeError("createCall's first argument must be a string");
346   }
347   if (!(info[1]->IsNumber() || info[1]->IsDate())) {
348     return Nan::ThrowTypeError(
349       "createcall's second argument must be a date or a number");
350   }
351   // These arguments are at the end because they are optional
352   grpc_call *parent_call = NULL;
353   if (Call::HasInstance(info[3])) {
354     Call *parent_obj =
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");
360   }
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");
367   }
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");
372   }
373   grpc_slice method =
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;
379     *host =
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);
384     delete host;
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);
389   } else {
390     return Nan::ThrowTypeError("createCall's third argument must be a string");
391   }
392   grpc_slice_unref(method);
393   info.GetReturnValue().Set(Call::WrapStruct(wrapped_call));
394 }
395
396 }  // namespace node
397 }  // namespace grpc