zuora_connect 2.0.60v → 2.0.60

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: be544177acd9fb2c32ff1e1924980726c9b68ee3d8461e5f1721e5333f9ef60e
4
- data.tar.gz: 15951349ed0a7064eff31fbb79d63585bc69a64408c0065993575925f01eb493
3
+ metadata.gz: bae96287832facbb0f512eedca7038f2bd566650d4e057f0d623613cb3acb559
4
+ data.tar.gz: d3b1f756842c3231a23719669d81c7aa206dfc677ae19ae2e537d3c3f6c089ae
5
5
  SHA512:
6
- metadata.gz: c43e5c4d523ced8219b069aca21d3273d001ca2816be985dbca23827a3203bf415f9b77423056d226ad2cb8cdaff2442e36831d2e1833350ee2e5b5791fc9665
7
- data.tar.gz: 72672400172011e402715935ee443594461b73d43ba15bd51c9b4f00061bd1d485aa22ec46f0fe181857cad49a109bdd65d7e31ced60f22c9678f381ff4cde5c
6
+ metadata.gz: 872a07f80dfbe1c12428cacc4369fe83a0f59eb20d953c0c43f609d19cd75556138e1162f4e175c6fdf10844f4bf2a01c0f8f1529c7a6e0774d7b53b47f4e68a
7
+ data.tar.gz: c2f5653b77bbc93521c37062542d12697fb21e055cff18a55846837e6f454dd2ce15963580f6623e523d6b30f677bce8e1fb7820a28b981cfa69c73bd6f7333a
@@ -1,11 +1,10 @@
1
1
  module ZuoraConnect
2
2
  class StaticController < ApplicationController
3
- before_action :authenticate_connect_app_request, :except => [:metrics, :health, :initialize_app, :provision, :instance_user]
4
- before_action :clear_connect_app_session, :only => [:metrics, :health, :initialize_app, :provision, :instance_user]
5
- after_action :persist_connect_app_session, :except => [:metrics, :health, :initialize_app, :provision, :instance_user]
6
-
7
- skip_before_action :verify_authenticity_token, :only => [:initialize_app, :provision]
8
- http_basic_authenticate_with name: ENV['PROVISION_USER'], password: ENV['PROVISION_SECRET'], :only => [:provision, :instance_user]
3
+ before_action :authenticate_connect_app_request, :except => [:metrics, :health, :initialize_app]
4
+ before_action :clear_connect_app_session, :only => [:metrics, :health, :initialize_app]
5
+ after_action :persist_connect_app_session, :except => [:metrics, :health, :initialize_app]
6
+
7
+ skip_before_action :verify_authenticity_token, :only => [:initialize_app]
9
8
 
10
9
  def metrics
11
10
  type = params[:type].present? ? params[:type] : "versions"
@@ -14,11 +13,11 @@ module ZuoraConnect
14
13
 
15
14
  def health
16
15
  if params[:error].present?
17
- begin
16
+ begin
18
17
  raise ZuoraConnect::Exceptions::Error.new('This is an error')
19
18
  rescue => ex
20
19
  case params[:error]
21
- when 'Log'
20
+ when 'Log'
22
21
  Rails.logger.error("Error in Health", ex)
23
22
  when 'Exception'
24
23
  raise
@@ -35,13 +34,11 @@ module ZuoraConnect
35
34
  def initialize_app
36
35
  begin
37
36
  authenticate_connect_app_request
38
- unless performed?
39
- @appinstance.new_session(:session => @appinstance.data_lookup(:session => session))
40
- render json: {
41
- message: 'Success',
42
- status: 200
43
- }, status: 200
44
- end
37
+ @appinstance.new_session(:session => @appinstance.data_lookup(:session => session))
38
+ render json: {
39
+ message: "Success",
40
+ status: 200
41
+ }, status: 200
45
42
  rescue => ex
46
43
  Rails.logger.error("Failed to Initialize application", ex)
47
44
  if performed?
@@ -55,74 +52,6 @@ module ZuoraConnect
55
52
  end
56
53
  end
57
54
 
58
- def provision
59
- create_new_instance
60
- unless performed?
61
- render json: {
62
- status: 200,
63
- message: 'Success',
64
- app_instance_id: @appinstance.id
65
- }, status: 200
66
- end
67
- rescue StandardError => e
68
- message = 'Failed to provision new instance'
69
- if performed?
70
- Rails.logger.error("#{message}: #{performed?}", e)
71
- else
72
- Rails.logger.error(message, e)
73
- render json: {
74
- status: 500,
75
- message: message
76
- }, status: 500
77
- end
78
- end
79
-
80
- def instance_user
81
- ZuoraConnect::AppInstance.read_master_db do
82
- ZuoraConnect.logger.with_fields = {} if ZuoraConnect.logger.is_a?(Ougai::Logger)
83
- Rails.logger.with_fields = {} if Rails.logger.is_a?(Ougai::Logger)
84
-
85
- if defined?(ElasticAPM) && ElasticAPM.running? && ElasticAPM.respond_to?(:set_label)
86
- ElasticAPM.set_label(:trace_id, request.uuid)
87
- end
88
-
89
- unless params[:id].present?
90
- render json: {
91
- status: 400,
92
- message: 'No app instance id provided'
93
- }, status: :bad_request
94
- return
95
- end
96
-
97
- @appinstance = ZuoraConnect::AppInstance.find(params[:id]).new_session
98
- end
99
-
100
- zuora_client = @appinstance.send(ZuoraConnect::AppInstance::LOGIN_TENANT_DESTINATION).client
101
- client_describe, = zuora_client.rest_call(
102
- url: zuora_client.rest_endpoint('genesis/user/info').gsub('v1/', ''),
103
- session_type: zuora_client.class == ZuoraAPI::Oauth ? :bearer : :basic
104
- )
105
-
106
- render json: {
107
- status: 200,
108
- message: 'Success',
109
- user_id: client_describe['coreUserId'],
110
- username: client_describe['username'],
111
- email: client_describe['workEmail']
112
- }, status: 200
113
- rescue ActiveRecord::RecordNotFound
114
- render json: {
115
- status: 400,
116
- message: 'No app instance found'
117
- }, status: :bad_request
118
- rescue StandardError => e
119
- Rails.logger.error('Error occurred getting user details', e)
120
- render json: {
121
- status: 500,
122
- message: 'Failed to get user details'
123
- }, status: 500
124
- end
125
-
126
55
  private
127
56
 
128
57
  def clear_connect_app_session
@@ -11,7 +11,7 @@ module ZuoraConnect
11
11
  before_destroy :prune_data
12
12
 
13
13
  self.table_name = "zuora_connect_app_instances"
14
- attr_accessor :options, :mode, :logins, :task_data, :last_refresh, :username, :password, :s3_client, :api_version, :drop_message, :new_session_message, :connect_user, :logitems, :user_timezone
14
+ attr_accessor :options, :mode, :logins, :task_data, :last_refresh, :username, :password, :s3_client, :api_version, :drop_message, :new_session_message, :connect_user, :logitems
15
15
  @@telegraf_host = nil
16
16
  REFRESH_TIMEOUT = 2.minute #Used to determine how long to wait on current refresh call before executing another
17
17
  INSTANCE_REFRESH_WINDOW = 1.hours #Used to set how how long till app starts attempting to refresh cached task connect data
@@ -21,12 +21,6 @@ module ZuoraConnect
21
21
  HOLDING_PATTERN_SLEEP = 5.seconds
22
22
  CONNECT_APPLICATION_ID = 0
23
23
  CONNECT_COMMUNICATION_SLEEP = Rails.env.test? ? 0.seconds : 5.seconds
24
- CATALOG_LOOKUP_PAGE_SIZE = 10_000
25
- CATALOG_LOOKUP_CACHE_TIME_KEY = 'CatalogCachedAt'
26
- CATALOG_LOOKUP_TTL = 60.seconds
27
- CATALOG_LOOKUP_CACHE_RESULT_KEY = 'CatalogCache'
28
- TIMEZONE_LOG_RATE_LIMIT_KEY = 'TimezoneLoggedAt'
29
- TIMEZONE_LOG_PERIOD = 4.hours
30
24
  IGNORED_LOCALS = ['fr', 'ja', 'es', 'zh', 'de']
31
25
  INTERNAL_HOSTS = []
32
26
  LOGIN_TENANT_DESTINATION = 'target_login'
@@ -246,9 +240,7 @@ module ZuoraConnect
246
240
  rescue I18n::InvalidLocale => ex
247
241
  ZuoraConnect.logger.error(ex) if !IGNORED_LOCALS.include?(ex.locale.to_s.downcase)
248
242
  end
249
-
250
- self.set_timezone
251
-
243
+ Time.zone = self.timezone
252
244
  if self.task_data.present?
253
245
  tenants = self.task_data.fetch('tenant_ids', [])
254
246
  organizations = self.task_data.fetch('organizations', [])
@@ -280,74 +272,6 @@ module ZuoraConnect
280
272
  end
281
273
  end
282
274
 
283
- def set_timezone(timezone: self.timezone, type: :default)
284
- if timezone.blank?
285
- timezone = self.timezone
286
- end
287
-
288
- if type == :default
289
- Time.zone = timezone
290
- elsif type == :user
291
- begin
292
- sql = <<-eos
293
- SELECT zuora_users.zuora_identity_response
294
- FROM "#{self.id}".zuora_users
295
- ORDER BY zuora_users.updated_at DESC
296
- LIMIT 1;
297
- eos
298
- user = ActiveRecord::Base.connection.execute(sql).to_a.first
299
-
300
- if user.present?
301
- zuora_identity_response = JSON.parse(user.fetch('zuora_identity_response', '{}'))
302
- self.user_timezone = zuora_identity_response.values.first&.dig('timeZone')
303
- else
304
- if (Redis.current.hget(TIMEZONE_LOG_RATE_LIMIT_KEY, self.id).to_i + TIMEZONE_LOG_PERIOD.to_i) <= Time.now.to_i
305
- Rails.logger.error('Cannot find any user to set the timezone', app_instance_id: self.id)
306
- Redis.current.hset(TIMEZONE_LOG_RATE_LIMIT_KEY, self.id, Time.now.to_i)
307
- end
308
- end
309
- rescue => ex
310
- Rails.logger.error('There is an error while getting timezone users', ex)
311
- end
312
-
313
- if self.user_timezone.present?
314
- # connect instance which has a custom timezone
315
- if !self.auto_deployed? && (
316
- ActiveSupport::TimeZone[self.task_data.dig('user_settings', 'timezone') || '']&.utc_offset !=
317
- ActiveSupport::TimeZone[self.user_timezone]&.utc_offset
318
- )
319
- if self.environment == 'Production' &&
320
- (Redis.current.hget(TIMEZONE_LOG_RATE_LIMIT_KEY, self.id).to_i + TIMEZONE_LOG_PERIOD.to_i) <= Time.now.to_i
321
- ZuoraConnect.logger.error(
322
- "Instance and user timezones are different. User has '#{self.user_timezone}' and " \
323
- "instance has '#{self.task_data.dig('user_settings', 'timezone')}'",
324
- app_instance_id: self.id
325
- )
326
- Redis.current.hset(TIMEZONE_LOG_RATE_LIMIT_KEY, self.id, Time.now.to_i)
327
- end
328
- self.user_timezone = nil
329
- Time.zone = timezone
330
- else
331
- begin
332
- Time.zone = self.user_timezone
333
- rescue ArgumentError
334
- Rails.logger.error('Malformed user timezone', app_instance_id: self.id)
335
- Time.zone = timezone
336
- end
337
- end
338
- else
339
- Time.zone = timezone
340
- end
341
- end
342
- rescue => e
343
- Rails.logger.error('Malformed timezone used', e, app_instance_id: self.id)
344
- Time.zone = self.timezone
345
- end
346
-
347
- def auto_deployed?
348
- self.id >= 25000000
349
- end
350
-
351
275
  def refresh(session: {})
352
276
  refresh_count ||= 0
353
277
  skip_connect ||= false
@@ -414,10 +338,6 @@ module ZuoraConnect
414
338
  raise
415
339
  end
416
340
 
417
- def aws_secrets
418
- (Rails.application.secrets.aws || {}).transform_keys { |key| key.to_s }
419
- end
420
-
421
341
  #### START KMS ENCRYPTION Methods ####
422
342
  def zuora_logins=(val)
423
343
  write_attribute(:zuora_logins, kms_encrypt(val.to_json))
@@ -430,7 +350,7 @@ module ZuoraConnect
430
350
 
431
351
  def kms_decrypt(value)
432
352
  kms_tries ||= 0
433
- kms_client = Aws::KMS::Client.new({region: aws_secrets['AWS_REGION'], credentials: self.aws_auth_client}.delete_if { |k, v| v.blank? })
353
+ kms_client = Aws::KMS::Client.new({region: Rails.application.secrets.aws['AWS_REGION'], credentials: self.aws_auth_client}.delete_if { |k, v| v.blank? })
434
354
  resp = kms_client.decrypt({ciphertext_blob: [value].pack("H*") })
435
355
  return resp.plaintext
436
356
  rescue *AWS_AUTH_ERRORS => ex
@@ -445,7 +365,7 @@ module ZuoraConnect
445
365
 
446
366
  def kms_encrypt(value)
447
367
  kms_tries ||= 0
448
- kms_client = Aws::KMS::Client.new({region: aws_secrets['AWS_REGION'], credentials: self.aws_auth_client}.delete_if {|k,v| v.blank? })
368
+ kms_client = Aws::KMS::Client.new({region: Rails.application.secrets.aws['AWS_REGION'], credentials: self.aws_auth_client}.delete_if {|k,v| v.blank? })
449
369
 
450
370
  resp = kms_client.encrypt({key_id: kms_key, plaintext: value})
451
371
  return resp.ciphertext_blob.unpack('H*').first
@@ -460,12 +380,12 @@ module ZuoraConnect
460
380
  end
461
381
 
462
382
  def kms_key
463
- return ENV['AWS_KMS_ARN'] || aws_secrets['AWS_KMS_ARN']
383
+ return ENV['AWS_KMS_ARN'] || Rails.application.secrets.dig(:aws,'AWS_KMS_ARN')
464
384
  end
465
385
 
466
386
  def aws_auth_client
467
387
  if Rails.env.to_s == 'development'
468
- return Aws::Credentials.new(aws_secrets['AWS_ACCESS_KEY_ID'], aws_secrets['AWS_SECRET_ACCESS_KEY'])
388
+ return Aws::Credentials.new(Rails.application.secrets.aws['AWS_ACCESS_KEY_ID'], Rails.application.secrets.aws['AWS_SECRET_ACCESS_KEY'])
469
389
  else
470
390
  return nil
471
391
  end
@@ -482,7 +402,7 @@ module ZuoraConnect
482
402
  end
483
403
 
484
404
  def self.write_to_telegraf(*args)
485
- if ZuoraConnect.configuration.enable_metrics && !defined?(Prometheus)
405
+ if ZuoraConnect.configuration.enable_metrics
486
406
  @@telegraf_host = ZuoraConnect::Telegraf.new() if @@telegraf_host == nil
487
407
  unicorn_stats = self.unicorn_listener_stats() if defined?(Unicorn) && Unicorn.respond_to?(:listener_names)
488
408
  @@telegraf_host.write(direction: 'Raindrops', tags: {}, values: unicorn_stats) unless unicorn_stats.blank?
@@ -1035,81 +955,13 @@ module ZuoraConnect
1035
955
  # object_id: The id or id's of the object/objects to be returned.
1036
956
  # child_objects: Whether to include child objects of the object in question.
1037
957
  # cache: Store individual "1" object lookup in redis for caching.
1038
- def catalog_lookup(entity_id: nil, object: :product, object_id: nil, child_objects: false, cache: false, source: 'DB')
958
+ def catalog_lookup(entity_id: nil, object: :product, object_id: nil, child_objects: false, cache: false)
1039
959
  entity_reference = entity_id.blank? ? 'Default' : entity_id
1040
960
 
1041
961
  if object_id.present? && ![Array, String].include?(object_id.class)
1042
962
  raise "Object Id can only be a string or an array of strings"
1043
963
  end
1044
964
 
1045
- if source == 'API'
1046
- catalog_container = {}
1047
-
1048
- if (Redis.current.hget(CATALOG_LOOKUP_CACHE_TIME_KEY, self.id).to_i + CATALOG_LOOKUP_TTL.to_i) > Time.now.to_i
1049
- begin
1050
- catalog_container = JSON.parse(Redis.current.hget(CATALOG_LOOKUP_CACHE_RESULT_KEY, self.id))
1051
- rescue JSON::ParserError => ex
1052
- Rails.logger.warn('Failed to parse catalog cache', ex)
1053
- end
1054
- else
1055
- zuora_login = self.login_lookup(type: 'Zuora').first
1056
- login = zuora_login.client(entity_reference)
1057
-
1058
- response = {
1059
- 'nextPage' => login.rest_endpoint("catalog/products?pageSize=#{CATALOG_LOOKUP_PAGE_SIZE}")
1060
- }
1061
-
1062
- while response['nextPage'].present?
1063
- url = login.rest_endpoint(response['nextPage'].split('/v1/').last)
1064
- output_json, response = login.rest_call(debug: false, url: url, timeout_retry: true)
1065
-
1066
- case object
1067
- when :product
1068
- output_json.fetch('products', []).each do |product|
1069
- rate_plans = {}
1070
- product['productRatePlans'].each do |rate_plan|
1071
- charges = {}
1072
- rate_plan['productRatePlanCharges'].each do |charge|
1073
- charges[charge['id']] = charge.merge(
1074
- {
1075
- 'productId' => product['id'],
1076
- 'productName' => product['name'],
1077
- 'productRatePlanId' => rate_plan['id'],
1078
- 'productRatePlanName' => rate_plan['name'],
1079
- }
1080
- )
1081
- end
1082
-
1083
- rate_plan['productRatePlanCharges'] = charges
1084
- rate_plans[rate_plan['id']] = rate_plan.merge(
1085
- {
1086
- 'productId' => product['id'],
1087
- 'productName' => product['name']
1088
- }
1089
- )
1090
- end
1091
-
1092
- product['productRatePlans'] = rate_plans
1093
- catalog_container[product['id']] = product
1094
- end
1095
- else
1096
- raise "Available objects include [:product]"
1097
- end
1098
- end
1099
-
1100
- Redis.current.hset(CATALOG_LOOKUP_CACHE_RESULT_KEY, self.id, catalog_container.to_json)
1101
- Redis.current.hset(CATALOG_LOOKUP_CACHE_TIME_KEY, self.id, Time.now.to_i)
1102
- end
1103
-
1104
- if object_id.nil?
1105
- catalog_container.transform_values! { |v| v.except('productRatePlans') }
1106
- elsif object_id.is_a?(String)
1107
- catalog_container = catalog_container[object_id]
1108
- end
1109
-
1110
- return catalog_container
1111
- end
1112
-
1113
965
  if defined?(Redis.current) && object_id.present? && object_id.class == String && object_id.present?
1114
966
  stub_catalog = cache ? decrypt_data(data: Redis.current.get("Catalog:#{self.id}:#{object_id}:Children:#{child_objects}")) : nil
1115
967
  object_hierarchy = decrypt_data(data: Redis.current.get("Catalog:#{self.id}:#{object_id}:Hierarchy"))
@@ -2,6 +2,6 @@ module ZuoraConnect
2
2
  class ZuoraUser < ActiveRecord::Base
3
3
  self.table_name = "zuora_users"
4
4
  attr_accessor :session
5
- cattr_accessor :current_user_id
5
+
6
6
  end
7
7
  end
@@ -1,15 +1,9 @@
1
1
  module ActiveRecord
2
2
  module ConnectionAdapters
3
3
  class PostgreSQLAdapter < AbstractAdapter
4
-
5
- SCHEMA_ADDITIONAL_TYPES = 'SchemaAdditionalTypes'.freeze
6
-
7
4
  private
8
- def load_additional_types_latest(oids = nil)
5
+ def load_additional_types(type_map, oids = nil)
9
6
  initializer = OID::TypeMapInitializer.new(type_map)
10
-
11
- return if loaded_from_cache?(initializer)
12
-
13
7
  if supports_ranges?
14
8
  query = <<-SQL
15
9
  SELECT DISTINCT on (t.typname) t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
@@ -30,73 +24,9 @@ module ActiveRecord
30
24
  end
31
25
 
32
26
  execute_and_clear(query, "SCHEMA", []) do |records|
33
- cache_additional_types(records)
34
27
  initializer.run(records)
35
28
  end
36
29
  end
37
-
38
- def load_additional_types_deprecated(type_map, oids = nil)
39
- initializer = OID::TypeMapInitializer.new(type_map)
40
-
41
- return if loaded_from_cache?(initializer)
42
-
43
- if supports_ranges?
44
- query = <<-SQL
45
- SELECT DISTINCT on (t.typname) t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
46
- FROM pg_type as t
47
- LEFT JOIN pg_range as r ON oid = rngtypid
48
- SQL
49
- else
50
- query = <<-SQL
51
- SELECT DISTINCT on (t.typname) t.oid, t.typname, t.typelem, t.typdelim, t.typinput, t.typtype, t.typbasetype
52
- FROM pg_type as t
53
- SQL
54
- end
55
-
56
- if oids
57
- query += "WHERE t.oid::integer IN (%s)" % oids.join(", ")
58
- else
59
- query += initializer.query_conditions_for_initial_load(type_map)
60
- end
61
-
62
- execute_and_clear(query, "SCHEMA", []) do |records|
63
- cache_additional_types(records)
64
- initializer.run(records)
65
- end
66
- end
67
-
68
- def loaded_from_cache?(initializer)
69
- if defined?(Redis.current)
70
- begin
71
- if Redis.current.exists(SCHEMA_ADDITIONAL_TYPES)
72
- initializer.run(JSON.parse(Redis.current.get(SCHEMA_ADDITIONAL_TYPES)))
73
- return true
74
- end
75
- rescue => ex
76
- Rails.logger.warn('Exception occurred while loading additional types', ex)
77
- end
78
- end
79
-
80
- false
81
- end
82
-
83
- def cache_additional_types(records)
84
- if defined?(Redis.current)
85
- begin
86
- Redis.current.setex(SCHEMA_ADDITIONAL_TYPES, 1.hour.to_i, records.to_json)
87
- rescue => ex
88
- Rails.logger.warn('Exception occurred while caching additional types', ex)
89
- end
90
- end
91
- end
92
-
93
-
94
- rails_version = Rails.version.split('.').map { |x| x.to_i }
95
- if (rails_version <=> [5, 2, 0]) >= 1
96
- alias :load_additional_types :load_additional_types_latest
97
- else
98
- alias :load_additional_types :load_additional_types_deprecated
99
- end
100
30
  end
101
31
  end
102
32
  end