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 <ruby/ruby.h>
20 
21 #include "rb_byte_buffer.h"
22 #include "rb_compression_options.h"
23 #include "rb_grpc_imports.generated.h"
24 
25 #include <grpc/compression.h>
26 #include <grpc/grpc.h>
27 #include <grpc/impl/codegen/compression_types.h>
28 #include <grpc/impl/codegen/grpc_types.h>
29 #include <grpc/support/alloc.h>
30 #include <grpc/support/log.h>
31 #include <grpc/support/string_util.h>
32 #include <string.h>
33 
34 #include "rb_grpc.h"
35 
36 static VALUE grpc_rb_cCompressionOptions = Qnil;
37 
38 /* Ruby Ids for the names of valid compression levels. */
39 static VALUE id_compress_level_none = Qnil;
40 static VALUE id_compress_level_low = Qnil;
41 static VALUE id_compress_level_medium = Qnil;
42 static VALUE id_compress_level_high = Qnil;
43 
44 /* grpc_rb_compression_options wraps a grpc_compression_options.
45  * It can be used to get the channel argument key-values for specific
46  * compression settings. */
47 
48 /* Note that ruby objects of this type don't carry any state in other
49  * Ruby objects and don't have a mark for GC. */
50 typedef struct grpc_rb_compression_options {
51   /* The actual compression options that's being wrapped */
52   grpc_compression_options* wrapped;
53 } grpc_rb_compression_options;
54 
grpc_rb_compression_options_free_internal(void * p)55 static void grpc_rb_compression_options_free_internal(void* p) {
56   grpc_rb_compression_options* wrapper = NULL;
57   if (p == NULL) {
58     return;
59   };
60   wrapper = (grpc_rb_compression_options*)p;
61   if (wrapper->wrapped != NULL) {
62     gpr_free(wrapper->wrapped);
63     wrapper->wrapped = NULL;
64   }
65   xfree(p);
66 }
67 
68 /* Destroys the compression options instances and free the
69  * wrapped grpc compression options. */
grpc_rb_compression_options_free(void * p)70 static void grpc_rb_compression_options_free(void* p) {
71   grpc_rb_compression_options_free_internal(p);
72   grpc_ruby_shutdown();
73 }
74 
75 /* Ruby recognized data type for the CompressionOptions class. */
76 static rb_data_type_t grpc_rb_compression_options_data_type = {
77     "grpc_compression_options",
78     {NULL,
79      grpc_rb_compression_options_free,
80      GRPC_RB_MEMSIZE_UNAVAILABLE,
81      {NULL, NULL}},
82     NULL,
83     NULL,
84 #ifdef RUBY_TYPED_FREE_IMMEDIATELY
85     RUBY_TYPED_FREE_IMMEDIATELY
86 #endif
87 };
88 
89 /* Allocates CompressionOptions instances.
90    Allocate the wrapped grpc compression options and
91    initialize it here too. */
grpc_rb_compression_options_alloc(VALUE cls)92 static VALUE grpc_rb_compression_options_alloc(VALUE cls) {
93   grpc_ruby_init();
94   grpc_rb_compression_options* wrapper = NULL;
95 
96   wrapper = gpr_malloc(sizeof(grpc_rb_compression_options));
97   wrapper->wrapped = NULL;
98   wrapper->wrapped = gpr_malloc(sizeof(grpc_compression_options));
99   grpc_compression_options_init(wrapper->wrapped);
100 
101   return TypedData_Wrap_Struct(cls, &grpc_rb_compression_options_data_type,
102                                wrapper);
103 }
104 
105 /* Disables a compression algorithm, given the GRPC core internal number of a
106  * compression algorithm. */
grpc_rb_compression_options_disable_compression_algorithm_internal(VALUE self,VALUE algorithm_to_disable)107 VALUE grpc_rb_compression_options_disable_compression_algorithm_internal(
108     VALUE self, VALUE algorithm_to_disable) {
109   grpc_compression_algorithm compression_algorithm = 0;
110   grpc_rb_compression_options* wrapper = NULL;
111 
112   TypedData_Get_Struct(self, grpc_rb_compression_options,
113                        &grpc_rb_compression_options_data_type, wrapper);
114   compression_algorithm =
115       (grpc_compression_algorithm)NUM2INT(algorithm_to_disable);
116 
117   grpc_compression_options_disable_algorithm(wrapper->wrapped,
118                                              compression_algorithm);
119 
120   return Qnil;
121 }
122 
123 /* Gets the compression internal enum value of a compression level given its
124  * name. */
grpc_rb_compression_options_level_name_to_value_internal(VALUE level_name)125 grpc_compression_level grpc_rb_compression_options_level_name_to_value_internal(
126     VALUE level_name) {
127   Check_Type(level_name, T_SYMBOL);
128 
129   /* Check the compression level of the name passed in, and see which macro
130    * from the GRPC core header files match. */
131   if (id_compress_level_none == SYM2ID(level_name)) {
132     return GRPC_COMPRESS_LEVEL_NONE;
133   } else if (id_compress_level_low == SYM2ID(level_name)) {
134     return GRPC_COMPRESS_LEVEL_LOW;
135   } else if (id_compress_level_medium == SYM2ID(level_name)) {
136     return GRPC_COMPRESS_LEVEL_MED;
137   } else if (id_compress_level_high == SYM2ID(level_name)) {
138     return GRPC_COMPRESS_LEVEL_HIGH;
139   }
140 
141   rb_raise(rb_eArgError,
142            "Unrecognized compression level name."
143            "Valid compression level names are none, low, medium, and high.");
144 
145   /* Dummy return statement. */
146   return GRPC_COMPRESS_LEVEL_NONE;
147 }
148 
149 /* Sets the default compression level, given the name of a compression level.
150  * Throws an error if no algorithm matched. */
grpc_rb_compression_options_set_default_level(grpc_compression_options * options,VALUE new_level_name)151 void grpc_rb_compression_options_set_default_level(
152     grpc_compression_options* options, VALUE new_level_name) {
153   options->default_level.level =
154       grpc_rb_compression_options_level_name_to_value_internal(new_level_name);
155   options->default_level.is_set = 1;
156 }
157 
158 /* Gets the internal value of a compression algorithm suitable as the value
159  * in a GRPC core channel arguments hash.
160  * algorithm_value is an out parameter.
161  * Raises an error if the name of the algorithm passed in is invalid. */
grpc_rb_compression_options_algorithm_name_to_value_internal(grpc_compression_algorithm * algorithm_value,VALUE algorithm_name)162 void grpc_rb_compression_options_algorithm_name_to_value_internal(
163     grpc_compression_algorithm* algorithm_value, VALUE algorithm_name) {
164   grpc_slice name_slice;
165   VALUE algorithm_name_as_string = Qnil;
166 
167   Check_Type(algorithm_name, T_SYMBOL);
168 
169   /* Convert the algorithm symbol to a ruby string, so that we can get the
170    * correct C string out of it. */
171   algorithm_name_as_string = rb_funcall(algorithm_name, rb_intern("to_s"), 0);
172 
173   name_slice =
174       grpc_slice_from_copied_buffer(RSTRING_PTR(algorithm_name_as_string),
175                                     RSTRING_LEN(algorithm_name_as_string));
176 
177   /* Raise an error if the name isn't recognized as a compression algorithm by
178    * the algorithm parse function
179    * in GRPC core. */
180   if (!grpc_compression_algorithm_parse(name_slice, algorithm_value)) {
181     char* name_slice_str = grpc_slice_to_c_string(name_slice);
182     char* error_message_str = NULL;
183     VALUE error_message_ruby_str = Qnil;
184     GPR_ASSERT(gpr_asprintf(&error_message_str,
185                             "Invalid compression algorithm name: %s",
186                             name_slice_str) != -1);
187     gpr_free(name_slice_str);
188     error_message_ruby_str =
189         rb_str_new(error_message_str, strlen(error_message_str));
190     gpr_free(error_message_str);
191     rb_raise(rb_eNameError, "%s", StringValueCStr(error_message_ruby_str));
192   }
193 
194   grpc_slice_unref(name_slice);
195 }
196 
197 /* Indicates whether a given algorithm is enabled on this instance, given the
198  * readable algorithm name. */
grpc_rb_compression_options_is_algorithm_enabled(VALUE self,VALUE algorithm_name)199 VALUE grpc_rb_compression_options_is_algorithm_enabled(VALUE self,
200                                                        VALUE algorithm_name) {
201   grpc_rb_compression_options* wrapper = NULL;
202   grpc_compression_algorithm internal_algorithm_value;
203 
204   TypedData_Get_Struct(self, grpc_rb_compression_options,
205                        &grpc_rb_compression_options_data_type, wrapper);
206   grpc_rb_compression_options_algorithm_name_to_value_internal(
207       &internal_algorithm_value, algorithm_name);
208 
209   if (grpc_compression_options_is_algorithm_enabled(wrapper->wrapped,
210                                                     internal_algorithm_value)) {
211     return Qtrue;
212   }
213   return Qfalse;
214 }
215 
216 /* Sets the default algorithm to the name of the algorithm passed in.
217  * Raises an error if the name is not a valid compression algorithm name. */
grpc_rb_compression_options_set_default_algorithm(grpc_compression_options * options,VALUE algorithm_name)218 void grpc_rb_compression_options_set_default_algorithm(
219     grpc_compression_options* options, VALUE algorithm_name) {
220   grpc_rb_compression_options_algorithm_name_to_value_internal(
221       &options->default_algorithm.algorithm, algorithm_name);
222   options->default_algorithm.is_set = 1;
223 }
224 
225 /* Disables an algorithm on the current instance, given the name of an
226  * algorithm.
227  * Fails if the algorithm name is invalid. */
grpc_rb_compression_options_disable_algorithm(grpc_compression_options * compression_options,VALUE algorithm_name)228 void grpc_rb_compression_options_disable_algorithm(
229     grpc_compression_options* compression_options, VALUE algorithm_name) {
230   grpc_compression_algorithm internal_algorithm_value;
231 
232   grpc_rb_compression_options_algorithm_name_to_value_internal(
233       &internal_algorithm_value, algorithm_name);
234   grpc_compression_options_disable_algorithm(compression_options,
235                                              internal_algorithm_value);
236 }
237 
238 /* Provides a ruby hash of GRPC core channel argument key-values that
239  * correspond to the compression settings on this instance. */
grpc_rb_compression_options_to_hash(VALUE self)240 VALUE grpc_rb_compression_options_to_hash(VALUE self) {
241   grpc_rb_compression_options* wrapper = NULL;
242   grpc_compression_options* compression_options = NULL;
243   VALUE channel_arg_hash = rb_hash_new();
244   VALUE key = Qnil;
245   VALUE value = Qnil;
246 
247   TypedData_Get_Struct(self, grpc_rb_compression_options,
248                        &grpc_rb_compression_options_data_type, wrapper);
249   compression_options = wrapper->wrapped;
250 
251   /* Add key-value pairs to the new Ruby hash. It can be used
252    * as GRPC core channel arguments. */
253   if (compression_options->default_level.is_set) {
254     key = rb_str_new2(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL);
255     value = INT2NUM((int)compression_options->default_level.level);
256     rb_hash_aset(channel_arg_hash, key, value);
257   }
258 
259   if (compression_options->default_algorithm.is_set) {
260     key = rb_str_new2(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM);
261     value = INT2NUM((int)compression_options->default_algorithm.algorithm);
262     rb_hash_aset(channel_arg_hash, key, value);
263   }
264 
265   key = rb_str_new2(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET);
266   value = INT2NUM((int)compression_options->enabled_algorithms_bitset);
267   rb_hash_aset(channel_arg_hash, key, value);
268 
269   return channel_arg_hash;
270 }
271 
272 /* Converts an internal enum level value to a readable level name.
273  * Fails if the level value is invalid. */
grpc_rb_compression_options_level_value_to_name_internal(grpc_compression_level compression_value)274 VALUE grpc_rb_compression_options_level_value_to_name_internal(
275     grpc_compression_level compression_value) {
276   switch (compression_value) {
277     case GRPC_COMPRESS_LEVEL_NONE:
278       return ID2SYM(id_compress_level_none);
279     case GRPC_COMPRESS_LEVEL_LOW:
280       return ID2SYM(id_compress_level_low);
281     case GRPC_COMPRESS_LEVEL_MED:
282       return ID2SYM(id_compress_level_medium);
283     case GRPC_COMPRESS_LEVEL_HIGH:
284       return ID2SYM(id_compress_level_high);
285     default:
286       rb_raise(
287           rb_eArgError,
288           "Failed to convert compression level value to name for value: %d",
289           (int)compression_value);
290       /* return something to avoid compiler error about no return */
291       return Qnil;
292   }
293 }
294 
295 /* Converts an algorithm internal enum value to a readable name.
296  * Fails if the enum value is invalid. */
grpc_rb_compression_options_algorithm_value_to_name_internal(grpc_compression_algorithm internal_value)297 VALUE grpc_rb_compression_options_algorithm_value_to_name_internal(
298     grpc_compression_algorithm internal_value) {
299   char* algorithm_name = NULL;
300 
301   if (!grpc_compression_algorithm_name(internal_value, &algorithm_name)) {
302     rb_raise(rb_eArgError, "Failed to convert algorithm value to name");
303   }
304 
305   return ID2SYM(rb_intern(algorithm_name));
306 }
307 
308 /* Gets the readable name of the default algorithm if one has been set.
309  * Returns nil if no algorithm has been set. */
grpc_rb_compression_options_get_default_algorithm(VALUE self)310 VALUE grpc_rb_compression_options_get_default_algorithm(VALUE self) {
311   grpc_compression_algorithm internal_value;
312   grpc_rb_compression_options* wrapper = NULL;
313 
314   TypedData_Get_Struct(self, grpc_rb_compression_options,
315                        &grpc_rb_compression_options_data_type, wrapper);
316 
317   if (wrapper->wrapped->default_algorithm.is_set) {
318     internal_value = wrapper->wrapped->default_algorithm.algorithm;
319     return grpc_rb_compression_options_algorithm_value_to_name_internal(
320         internal_value);
321   }
322 
323   return Qnil;
324 }
325 
326 /* Gets the internal value of the default compression level that is to be passed
327  * to the GRPC core as a channel argument value.
328  * A nil return value means that it hasn't been set. */
grpc_rb_compression_options_get_default_level(VALUE self)329 VALUE grpc_rb_compression_options_get_default_level(VALUE self) {
330   grpc_compression_level internal_value;
331   grpc_rb_compression_options* wrapper = NULL;
332 
333   TypedData_Get_Struct(self, grpc_rb_compression_options,
334                        &grpc_rb_compression_options_data_type, wrapper);
335 
336   if (wrapper->wrapped->default_level.is_set) {
337     internal_value = wrapper->wrapped->default_level.level;
338     return grpc_rb_compression_options_level_value_to_name_internal(
339         internal_value);
340   }
341 
342   return Qnil;
343 }
344 
345 /* Gets a list of the disabled algorithms as readable names.
346  * Returns an empty list if no algorithms have been disabled. */
grpc_rb_compression_options_get_disabled_algorithms(VALUE self)347 VALUE grpc_rb_compression_options_get_disabled_algorithms(VALUE self) {
348   VALUE disabled_algorithms = rb_ary_new();
349   grpc_compression_algorithm internal_value;
350   grpc_rb_compression_options* wrapper = NULL;
351 
352   TypedData_Get_Struct(self, grpc_rb_compression_options,
353                        &grpc_rb_compression_options_data_type, wrapper);
354 
355   for (internal_value = GRPC_COMPRESS_NONE;
356        internal_value < GRPC_COMPRESS_ALGORITHMS_COUNT; internal_value++) {
357     if (!grpc_compression_options_is_algorithm_enabled(wrapper->wrapped,
358                                                        internal_value)) {
359       rb_ary_push(disabled_algorithms,
360                   grpc_rb_compression_options_algorithm_value_to_name_internal(
361                       internal_value));
362     }
363   }
364   return disabled_algorithms;
365 }
366 
367 /* Initializes the compression options wrapper.
368  * Takes an optional hash parameter.
369  *
370  * Example call-seq:
371  *   options = CompressionOptions.new(
372  *     default_level: :none,
373  *     disabled_algorithms: [:gzip]
374  *   )
375  *   channel_arg hash = Hash.new[...]
376  *   channel_arg_hash_with_compression_options = channel_arg_hash.merge(options)
377  */
grpc_rb_compression_options_init(int argc,VALUE * argv,VALUE self)378 VALUE grpc_rb_compression_options_init(int argc, VALUE* argv, VALUE self) {
379   grpc_rb_compression_options* wrapper = NULL;
380   VALUE default_algorithm = Qnil;
381   VALUE default_level = Qnil;
382   VALUE disabled_algorithms = Qnil;
383   VALUE algorithm_name = Qnil;
384   VALUE hash_arg = Qnil;
385 
386   rb_scan_args(argc, argv, "01", &hash_arg);
387 
388   /* Check if the hash parameter was passed, or if invalid arguments were
389    * passed. */
390   if (hash_arg == Qnil) {
391     return self;
392   } else if (TYPE(hash_arg) != T_HASH || argc > 1) {
393     rb_raise(rb_eArgError,
394              "Invalid arguments. Expecting optional hash parameter");
395   }
396 
397   TypedData_Get_Struct(self, grpc_rb_compression_options,
398                        &grpc_rb_compression_options_data_type, wrapper);
399 
400   /* Set the default algorithm if one was chosen. */
401   default_algorithm =
402       rb_hash_aref(hash_arg, ID2SYM(rb_intern("default_algorithm")));
403   if (default_algorithm != Qnil) {
404     grpc_rb_compression_options_set_default_algorithm(wrapper->wrapped,
405                                                       default_algorithm);
406   }
407 
408   /* Set the default level if one was chosen. */
409   default_level = rb_hash_aref(hash_arg, ID2SYM(rb_intern("default_level")));
410   if (default_level != Qnil) {
411     grpc_rb_compression_options_set_default_level(wrapper->wrapped,
412                                                   default_level);
413   }
414 
415   /* Set the disabled algorithms if any were chosen. */
416   disabled_algorithms =
417       rb_hash_aref(hash_arg, ID2SYM(rb_intern("disabled_algorithms")));
418   if (disabled_algorithms != Qnil) {
419     Check_Type(disabled_algorithms, T_ARRAY);
420 
421     for (int i = 0; i < RARRAY_LEN(disabled_algorithms); i++) {
422       algorithm_name = rb_ary_entry(disabled_algorithms, i);
423       grpc_rb_compression_options_disable_algorithm(wrapper->wrapped,
424                                                     algorithm_name);
425     }
426   }
427 
428   return self;
429 }
430 
Init_grpc_compression_options()431 void Init_grpc_compression_options() {
432   grpc_rb_cCompressionOptions = rb_define_class_under(
433       grpc_rb_mGrpcCore, "CompressionOptions", rb_cObject);
434 
435   /* Allocates an object managed by the ruby runtime. */
436   rb_define_alloc_func(grpc_rb_cCompressionOptions,
437                        grpc_rb_compression_options_alloc);
438 
439   /* Initializes the ruby wrapper. #new method takes an optional hash argument.
440    */
441   rb_define_method(grpc_rb_cCompressionOptions, "initialize",
442                    grpc_rb_compression_options_init, -1);
443 
444   /* Methods for getting the default algorithm, default level, and disabled
445    * algorithms as readable names. */
446   rb_define_method(grpc_rb_cCompressionOptions, "default_algorithm",
447                    grpc_rb_compression_options_get_default_algorithm, 0);
448   rb_define_method(grpc_rb_cCompressionOptions, "default_level",
449                    grpc_rb_compression_options_get_default_level, 0);
450   rb_define_method(grpc_rb_cCompressionOptions, "disabled_algorithms",
451                    grpc_rb_compression_options_get_disabled_algorithms, 0);
452 
453   /* Determines whether or not an algorithm is enabled, given a readable
454    * algorithm name.*/
455   rb_define_method(grpc_rb_cCompressionOptions, "algorithm_enabled?",
456                    grpc_rb_compression_options_is_algorithm_enabled, 1);
457 
458   /* Provides a hash of the compression settings suitable
459    * for passing to server or channel args. */
460   rb_define_method(grpc_rb_cCompressionOptions, "to_hash",
461                    grpc_rb_compression_options_to_hash, 0);
462   rb_define_alias(grpc_rb_cCompressionOptions, "to_channel_arg_hash",
463                   "to_hash");
464 
465   /* Ruby ids for the names of the different compression levels. */
466   id_compress_level_none = rb_intern("none");
467   id_compress_level_low = rb_intern("low");
468   id_compress_level_medium = rb_intern("medium");
469   id_compress_level_high = rb_intern("high");
470 }
471