Class: DevCycle::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/devcycle-ruby-server-sdk/api/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(sdkKey, dvc_options = Options.new, wait_for_init = false) ⇒ Client

Returns a new instance of Client.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 6

def initialize(sdkKey, dvc_options = Options.new, wait_for_init = false)
  if sdkKey.nil?
    raise ArgumentError.new('Missing SDK key!')
  elsif !sdkKey.start_with?('server') && !sdkKey.start_with?('dvc_server')
    raise ArgumentError.new('Invalid SDK key!')
  end

  @sdkKey = sdkKey
  @dvc_options = dvc_options
  @logger = dvc_options.logger

  if @dvc_options.enable_cloud_bucketing
    @api_client = ApiClient.default
    @api_client.config.api_key['bearerAuth'] = @sdkKey
    @api_client.config.enable_edge_db = @dvc_options.enable_edge_db
    @api_client.config.logger = @logger
  else
    @local_bucketing = LocalBucketing.new(@sdkKey, dvc_options, wait_for_init)
    @event_queue = EventQueue.new(@sdkKey, dvc_options.event_queue_options, @local_bucketing)
  end
end

Instance Method Details

#all_features(user, opts = {}) ⇒ Hash<String, Feature>

Get all features by key for user data

Parameters:

  • user (User)
  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 72

def all_features(user, opts = {})
  if !user.is_a?(DevCycle::User)
    fail ArgumentError, "user param must be an instance of DevCycle::User!"
  end

  validate_model(user)

  if @dvc_options.enable_cloud_bucketing
    data, _status_code, _headers = all_features_with_http_info(user, opts)
    return data
  end

  if local_bucketing_initialized? && @local_bucketing.has_config
    bucketed_config = @local_bucketing.generate_bucketed_config(user)
    bucketed_config.features
  else
    {}
  end
end

#all_features_with_http_info(user, opts = {}) ⇒ Array<(Hash<String, Feature>, Integer, Hash)>

Get all features by key for user data

Parameters:

  • user (User)
  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:

  • (Array<(Hash<String, Feature>, Integer, Hash)>)

    Hash<String, Feature> data, response status code and response headers



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 96

def all_features_with_http_info(user, opts = {})
  if @api_client.config.debugging
    @api_client.config.logger.debug 'Calling API: DevCycle::Client.all_features ...'
  end
  # verify the required parameter 'user' is set
  if @api_client.config.client_side_validation && user.nil?
    fail ArgumentError, "Missing the required parameter 'user' when calling DevCycle::Client.all_features"
  end
  # resource path
  local_var_path = '/v1/features'

  # query parameters
  query_params = opts[:query_params] || {}

  # header parameters
  header_params = opts[:header_params] || {}
  # HTTP header 'Accept' (if needed)
  header_params['Accept'] = @api_client.select_header_accept(['application/json'])
  # HTTP header 'Content-Type'
  content_type = @api_client.select_header_content_type(['application/json'])
  if !content_type.nil?
    header_params['Content-Type'] = content_type
  end

  # form parameters
  form_params = opts[:form_params] || {}

  # http body (model)
  post_body = opts[:debug_body] || user.to_json

  # return_type
  return_type = opts[:debug_return_type] || 'Hash<String, Feature>'

  # auth_names
  auth_names = opts[:debug_auth_names] || ['bearerAuth']

  new_options = opts.merge(
    :operation => :"Client.all_features",
    :header_params => header_params,
    :query_params => query_params,
    :form_params => form_params,
    :body => post_body,
    :auth_names => auth_names,
    :return_type => return_type
  )

  data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
  if @api_client.config.debugging
    @api_client.config.logger.debug "API called: DevCycle::Client#all_features\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
  end
  return data, status_code, headers
end

#all_variables(user, opts = {}) ⇒ Hash<String, Variable>

Get all variables by key for user data

Parameters:

  • user (User)
  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 302

def all_variables(user, opts = {})
  if !user.is_a?(DevCycle::User)
    fail ArgumentError, "user param must be an instance of DevCycle::User!"
  end

  validate_model(user)

  if @dvc_options.enable_cloud_bucketing
    data, _status_code, _headers = all_variables_with_http_info(user, opts)
    return data
  end

  if local_bucketing_initialized? && @local_bucketing.has_config
    bucketed_config = @local_bucketing.generate_bucketed_config(user)
    bucketed_config.variables
  else
    {}
  end
end

#all_variables_with_http_info(user, opts = {}) ⇒ Array<(Hash<String, Variable>, Integer, Hash)>

Get all variables by key for user data

Parameters:

  • user (User)
  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:

  • (Array<(Hash<String, Variable>, Integer, Hash)>)

    Hash<String, Variable> data, response status code and response headers



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 326

def all_variables_with_http_info(user, opts = {})
  if @api_client.config.debugging
    @api_client.config.logger.debug 'Calling API: DevCycle::Client.all_variables ...'
  end
  # verify the required parameter 'user' is set
  if @api_client.config.client_side_validation && user.nil?
    fail ArgumentError, "Missing the required parameter 'user' when calling DevCycle::Client.all_variables"
  end
  # resource path
  local_var_path = '/v1/variables'

  # query parameters
  query_params = opts[:query_params] || {}

  # header parameters
  header_params = opts[:header_params] || {}
  # HTTP header 'Accept' (if needed)
  header_params['Accept'] = @api_client.select_header_accept(['application/json'])
  # HTTP header 'Content-Type'
  content_type = @api_client.select_header_content_type(['application/json'])
  if !content_type.nil?
    header_params['Content-Type'] = content_type
  end

  # form parameters
  form_params = opts[:form_params] || {}

  # http body (model)
  post_body = opts[:debug_body] || user.to_json

  # return_type
  return_type = opts[:debug_return_type] || 'Hash<String, Variable>'

  # auth_names
  auth_names = opts[:debug_auth_names] || ['bearerAuth']

  new_options = opts.merge(
    :operation => :"Client.all_variables",
    :header_params => header_params,
    :query_params => query_params,
    :form_params => form_params,
    :body => post_body,
    :auth_names => auth_names,
    :return_type => return_type
  )

  data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
  if @api_client.config.debugging
    @api_client.config.logger.debug "API called: DevCycle::Client#all_variables\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
  end
  return data, status_code, headers
end

#closeObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 28

def close
  if @dvc_options.enable_cloud_bucketing
    @logger.info("Cloud Bucketing does not require closing.")
    return
  end
  if @local_bucketing != nil
    if !@local_bucketing.initialized
      @logger.info("Awaiting client initialization before closing")
      while !@local_bucketing.initialized
        sleep(0.5)
      end
    end
    @local_bucketing.close
    @local_bucketing = nil
    @logger.info("Closed DevCycle Local Bucketing Engine.")
  end

  @event_queue.close
  @logger.info("Closed DevCycle Client.")
  nil
end

#determine_variable_type(variable_value) ⇒ Object



484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 484

def determine_variable_type(variable_value)
  if variable_value.is_a?(String)
    'String'
  elsif variable_value.is_a?(TrueClass) || variable_value.is_a?(FalseClass)
    'Boolean'
  elsif variable_value.is_a?(Integer) || variable_value.is_a?(Float)
    'Number'
  elsif variable_value.is_a?(Hash)
    'JSON'
  else
    raise ArgumentError, "Invalid type for variable: #{variable_value}"
  end
end

#flush_eventsObject



476
477
478
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 476

def flush_events
  @event_queue.flush_events
end

#local_bucketing_initialized?Boolean

Returns:

  • (Boolean)


480
481
482
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 480

def local_bucketing_initialized?
  !@local_bucketing.nil? && @local_bucketing.initialized
end

#set_client_custom_data(custom_data) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 50

def set_client_custom_data(custom_data)
  if @dvc_options.enable_cloud_bucketing
    raise StandardError.new("Client Custom Data is only available in Local bucketing mode.")
  end

  if local_bucketing_initialized?
    @local_bucketing.set_client_custom_data(custom_data)
  else
    @logger.warn("Local bucketing not initialized. Unable to set client custom data.")
  end
  nil
end

#track(user, event_data, opts = {}) ⇒ InlineResponse201

Post events to DevCycle for user

Parameters:

  • user (User)
  • event_data (Event)
  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 384

def track(user, event_data, opts = {})
  if !user.is_a?(DevCycle::User)
    fail ArgumentError, "user param must be an instance of DevCycle::User!"
  end

  validate_model(user)

  if !event_data.is_a?(DevCycle::Event)
    fail ArgumentError, "event_data param must be an instance of DevCycle::Event!"
  end

  validate_model(event_data)

  if @dvc_options.enable_cloud_bucketing
    track_with_http_info(user, event_data, opts)
    return
  end

  if local_bucketing_initialized?
    @event_queue.queue_event(user, event_data)
  else
    @logger.warn('track called before DevCycle::Client initialized, event will not be tracked')
  end
end

#track_with_http_info(user, event_data, opts = {}) ⇒ Array<(InlineResponse201, Integer, Hash)>

Post events to DevCycle for user

Parameters:

  • user (User)
  • event_data (Event)
  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:

  • (Array<(InlineResponse201, Integer, Hash)>)

    InlineResponse201 data, response status code and response headers



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 414

def track_with_http_info(user, event_data, opts = {})
  if @api_client.config.debugging
    @api_client.config.logger.debug 'Calling API: DevCycle::Client.post_events ...'
  end
  # verify the required parameter 'user_data_and_events_body' is set
  if @api_client.config.client_side_validation && (user.nil? || event_data.nil?)
    fail ArgumentError, "Missing the required parameter 'user_data_and_events_body' when calling DevCycle::Client.post_events"
  end

  user_data_and_events_body = DevCycle::UserDataAndEventsBody.new({
                                                                    user: user,
                                                                    events: [event_data]
                                                                  })

  # resource path
  local_var_path = '/v1/track'

  # query parameters
  query_params = opts[:query_params] || {}

  # header parameters
  header_params = opts[:header_params] || {}
  # HTTP header 'Accept' (if needed)
  header_params['Accept'] = @api_client.select_header_accept(['application/json'])
  # HTTP header 'Content-Type'
  content_type = @api_client.select_header_content_type(['application/json'])
  if !content_type.nil?
    header_params['Content-Type'] = content_type
  end

  # form parameters
  form_params = opts[:form_params] || {}

  # http body (model)
  post_body = opts[:debug_body] || @api_client.object_to_http_body(user_data_and_events_body)

  # if post_body.user.respond_to?(:to_hash)
  #   post_body.user = post_body.user.to_hash()

  # return_type
  return_type = opts[:debug_return_type] || 'InlineResponse201'

  # auth_names
  auth_names = opts[:debug_auth_names] || ['bearerAuth']

  new_options = opts.merge(
    :operation => :"Client.post_events",
    :header_params => header_params,
    :query_params => query_params,
    :form_params => form_params,
    :body => post_body,
    :auth_names => auth_names,
    :return_type => return_type
  )

  data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
  if @api_client.config.debugging
    @api_client.config.logger.debug "API called: DevCycle::Client#post_events\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
  end
  return data, status_code, headers
end

#validate_model(model) ⇒ Object



63
64
65
66
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 63

def validate_model(model)
  return if model.valid?
  fail ArgumentError, "Invalid data provided for model #{model.class.name}: #{model.list_invalid_properties()}"
end

#variable(user, key, default, opts = {}) ⇒ Variable

Get variable by key for user data

Parameters:

  • user (User)
  • key (String)

    Variable key

  • default

    Default value for variable if none is retrieved

  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 166

def variable(user, key, default, opts = {})
  if !user.is_a?(DevCycle::User)
    fail ArgumentError, "user param must be an instance of DevCycle::User!"
  end

  validate_model(user)

  if @dvc_options.enable_cloud_bucketing
    data, _status_code, _headers = variable_with_http_info(key, user, default, opts)
    return data
  end

  value = default
  type = determine_variable_type(default)
  defaulted = true
  if local_bucketing_initialized? && @local_bucketing.has_config
    type_code = variable_type_code_from_type(type)
    variable_pb = variable_for_user_pb(user, key, type_code)
    unless variable_pb.nil?
      value = get_variable_value(variable_pb)
      defaulted = false
    end
  else
    @logger.warn("Local bucketing not initialized, returning default value for variable #{key}")
    variable_event = Event.new({ type: DevCycle::EventTypes[:agg_variable_defaulted], target: key })
    bucketed_config = BucketedUserConfig.new({}, {}, {}, {}, {}, {}, [])
    @event_queue.queue_aggregate_event(variable_event, bucketed_config)
  end

  Variable.new({
    key: key,
    value: value,
    type: type,
    defaultValue: default,
    isDefaulted: defaulted
  })
end

#variable_for_user(user, key, variable_type_code) ⇒ Object



204
205
206
207
208
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 204

def variable_for_user(user, key, variable_type_code)
  json_str = @local_bucketing.variable_for_user(user, key, variable_type_code)
  return nil if json_str.nil?
  JSON.parse(json_str)
end

#variable_for_user_pb(user, key, variable_type_code) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 210

def variable_for_user_pb(user, key, variable_type_code)
  user_data_pb = user.to_pb_user_data
  params_pb = Proto::VariableForUserParams_PB.new(
    sdkKey: @sdkKey,
    variableKey: key,
    variableType: variable_type_pb_code_from_type_code(variable_type_code),
    user: user_data_pb,
    shouldTrackEvent: true
  )
  param_bin_string = Proto::VariableForUserParams_PB.encode(params_pb)
  var_bin_string = @local_bucketing.variable_for_user_pb(param_bin_string)
  if var_bin_string.nil?
    return nil
  end
  Proto::SDKVariable_PB.decode(var_bin_string)
end

#variable_type_code_from_type(type) ⇒ Object



498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 498

def variable_type_code_from_type(type)
  case type
  when 'String'
    @local_bucketing.variable_type_codes[:string]
  when 'Boolean'
    @local_bucketing.variable_type_codes[:boolean]
  when 'Number'
    @local_bucketing.variable_type_codes[:number]
  when 'JSON'
    @local_bucketing.variable_type_codes[:json]
  else
    raise ArgumentError.new("Invalid type for variable: #{type}")
  end
end

#variable_type_pb_code_from_type_code(type_code) ⇒ Object



513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 513

def variable_type_pb_code_from_type_code(type_code)
  case type_code
  when @local_bucketing.variable_type_codes[:string]
    Proto::VariableType_PB::String
  when @local_bucketing.variable_type_codes[:boolean]
    Proto::VariableType_PB::Boolean
  when @local_bucketing.variable_type_codes[:number]
    Proto::VariableType_PB::Number
  when @local_bucketing.variable_type_codes[:json]
    Proto::VariableType_PB::JSON
  else
    raise ArgumentError.new("Invalid type code for variable: #{type_code}")
  end
end

#variable_value(user, key, default, opts = {}) ⇒ Object

Get variable value by key for user data

Parameters:

  • user (User)
  • key (String)

    Variable key

  • default

    Default value for variable if none is retrieved

  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:

  • variable value which can be: string, number, boolean, or JSON



155
156
157
158
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 155

def variable_value(user, key, default, opts = {})
  variable_obj = variable(user, key, default, opts)
  variable_obj.value
end

#variable_with_http_info(key, user, default, opts = {}) ⇒ Array<(Variable, Integer, Hash)>

Get variable by key for user data

Parameters:

  • key (String)

    Variable key

  • user (User)
  • default

    Default value for variable if none is retrieved

  • opts (Hash) (defaults to: {})

    the optional parameters

Returns:

  • (Array<(Variable, Integer, Hash)>)

    Variable data, response status code and response headers



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/devcycle-ruby-server-sdk/api/client.rb', line 233

def variable_with_http_info(key, user, default, opts = {})
  if @api_client.config.debugging
    @api_client.config.logger.debug 'Calling API: DevCycle::Client.variable ...'
  end
  # verify the required parameter 'key' is set
  if @api_client.config.client_side_validation && key.nil?
    fail ArgumentError, "Missing the required parameter 'key' when calling DevCycle::Client.variable"
  end
  # verify the required parameter 'user' is set
  if @api_client.config.client_side_validation && user.nil?
    fail ArgumentError, "Missing the required parameter 'user' when calling DevCycle::Client.variable"
  end
  # resource path
  local_var_path = '/v1/variables/{key}'.sub('{' + 'key' + '}', CGI.escape(key.to_s))

  # query parameters
  query_params = opts[:query_params] || {}

  # header parameters
  header_params = opts[:header_params] || {}
  # HTTP header 'Accept' (if needed)
  header_params['Accept'] = @api_client.select_header_accept(['application/json'])
  # HTTP header 'Content-Type'
  content_type = @api_client.select_header_content_type(['application/json'])
  if !content_type.nil?
    header_params['Content-Type'] = content_type
  end

  # form parameters
  form_params = opts[:form_params] || {}

  # http body (model)
  post_body = opts[:debug_body] || user.to_json

  # return_type
  return_type = opts[:debug_return_type] || 'Variable'

  # auth_names
  auth_names = opts[:debug_auth_names] || ['bearerAuth']

  new_options = opts.merge(
    :operation => :"Client.variable",
    :header_params => header_params,
    :query_params => query_params,
    :form_params => form_params,
    :body => post_body,
    :auth_names => auth_names,
    :return_type => return_type
  )

  begin
    data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
    if @api_client.config.debugging
      @api_client.config.logger.debug "API called: DevCycle::Client#variable\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
    end
    return data
  rescue ApiError => error
    if error.code != 404
      @api_client.config.logger.error("Failed to retrieve variable value: #{error.message}")
    end

    return Variable.new(key: key, value: default, isDefaulted: true)
  end
end