verifalia 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. checksums.yaml +5 -5
  2. data/Gemfile +5 -5
  3. data/LICENSE +3 -4
  4. data/README.md +328 -82
  5. data/Rakefile +4 -0
  6. data/lib/verifalia/client.rb +60 -0
  7. data/lib/verifalia/credits/balance.rb +30 -0
  8. data/lib/verifalia/credits/client.rb +25 -0
  9. data/lib/verifalia/email_validation/client.rb +207 -0
  10. data/lib/verifalia/email_validation/completion_callback.rb +15 -0
  11. data/lib/verifalia/email_validation/entry.rb +89 -0
  12. data/lib/verifalia/email_validation/job.rb +75 -0
  13. data/lib/verifalia/email_validation/overview.rb +76 -0
  14. data/lib/verifalia/email_validation/progress.rb +19 -0
  15. data/lib/verifalia/email_validation/request.rb +19 -0
  16. data/lib/verifalia/email_validation/request_entry.rb +14 -0
  17. data/lib/verifalia/email_validation/wait_options.rb +53 -0
  18. data/lib/verifalia/rest/client.rb +82 -0
  19. data/lib/verifalia/security/certificate_authenticator.rb +21 -0
  20. data/lib/verifalia/security/username_password_authenticator.rb +22 -0
  21. data/lib/verifalia.rb +8 -23
  22. data/sig/completion_callback.rbs +5 -0
  23. data/sig/verifalia/client.rbs +11 -0
  24. data/sig/verifalia/credits/balance.rbs +11 -0
  25. data/sig/verifalia/credits/client.rbs +7 -0
  26. data/sig/verifalia/email_validations/client.rbs +24 -0
  27. data/sig/verifalia/email_validations/entry.rbs +22 -0
  28. data/sig/verifalia/email_validations/job.rbs +13 -0
  29. data/sig/verifalia/email_validations/overview.rbs +20 -0
  30. data/sig/verifalia/email_validations/progress.rbs +8 -0
  31. data/sig/verifalia/email_validations/request.rbs +13 -0
  32. data/sig/verifalia/email_validations/request_entry.rbs +8 -0
  33. data/sig/verifalia/email_validations/wait_options.rbs +20 -0
  34. data/sig/verifalia/rest/client.rbs +12 -0
  35. data/sig/verifalia/rest.rbs +6 -0
  36. data/sig/verifalia/security/username_password_authenticator.rbs +10 -0
  37. data/verifalia.gemspec +27 -18
  38. metadata +56 -57
  39. data/.gitignore +0 -24
  40. data/lib/rest/account_balance.rb +0 -93
  41. data/lib/rest/client.rb +0 -83
  42. data/lib/rest/email_validations.rb +0 -195
  43. data/lib/verifalia/util/configuration.rb +0 -7
  44. data/lib/verifalia/version.rb +0 -3
  45. data/spec/rest/account_balance_spec.rb +0 -93
  46. data/spec/rest/client_spec.rb +0 -105
  47. data/spec/rest/email_validations_spec.rb +0 -322
  48. data/spec/spec_helper.rb +0 -21
  49. data/spec/util/configuration_spec.rb +0 -15
  50. data/spec/verifalia_spec.rb +0 -17
@@ -0,0 +1,207 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require_relative 'job'
5
+ require_relative 'overview'
6
+ require_relative 'entry'
7
+ require_relative 'wait_options'
8
+ require_relative 'request'
9
+ require_relative 'request_entry'
10
+ require_relative 'completion_callback'
11
+
12
+ module Verifalia
13
+ module EmailValidations
14
+ # Allows to verify email addresses and manage email verification jobs using the Verifalia service.
15
+ class Client
16
+ def initialize(rest_client)
17
+ @rest_client = rest_client
18
+ end
19
+
20
+ # Submits a new email validation for processing.
21
+ #
22
+ # By default, this method waits for the completion of the email validation job: pass a +WaitOptions+ to request
23
+ # a different waiting behavior.
24
+ #
25
+ # @param data The input data to verify.
26
+ # @param [nil] quality The desired results quality for this email validation.
27
+ # @param [nil] priority
28
+ # @param [nil] deduplication An optional string with the name of the algorithm our engine will use to scrub the list of email addresses and remove its duplicates. The following values are currently supported: +Off+ does not mark duplicated email addresses, +Safe+ mark duplicated email addresses with an algorithm which guarantees no false duplicates are returned, +Relaxed+ mark duplicated email addresses using a set of relaxed rules which assume the target email service providers are configured with modern settings only. If not specified, Verifalia will not mark duplicated email addresses.
29
+ # @param [nil] name An optional user-defined name for the validation job, for your own reference.
30
+ # @param [nil] retention An optional string with the desired data retention period to observe for the validation job, expressed in the format +dd.hh:mm:ss+ (where +dd.+ days, +hh:+ hours, +mm:+ minutes, +ss:+ seconds); the initial +dd.+ part is added only for periods of more than 24 hours. The value has a minimum of 5 minutes (+0:5:0+) and a maximum of 30 days (+30.0:0:0+): Verifalia will delete the job and its data once its data retention period is over, starting to count when it gets completed. If not specified, Verifalia falls back to the configured data retention period of the submitting user / browser app and, should it be unset, to the configured data retention period of the Verifalia account, with a default of 30 days.
31
+ # @param [nil] completion_callback An optional hash describing the desired completion callback behavior, with the following keys: +url+ A string with the URL Verifalia will invoke once the job results are ready. See how to handle completion callbacks. +version+ An optional string which defines the callback schema our dispatcher must obey when invoking the provided callback URL. Valid values are: +1.0+ the callback includes the completed job ID. +1.1+ everything included with +1.0+ plus the job name. If not specified, Verifalia will use the most recent schema available at the time the used API version was released. +skipServerCertificateValidation+ An optional boolean which allows to skip the server certificate validation for the external callback server, useful for testing purposes at development time when the callback server is using a self-signed certificate.
32
+ # @param [nil] wait_options The options which rule out how to wait for the completion of the email validation.
33
+ # @return [Verifalia::EmailValidations::Job] The submitted validation job (or +nil+ if expired / deleted while waiting for its completion).
34
+ def submit(data,
35
+ quality: nil,
36
+ priority: nil,
37
+ deduplication: nil,
38
+ name: nil,
39
+ retention: nil,
40
+ completion_callback: nil,
41
+ wait_options: nil)
42
+ # Determine how to handle the submission, based on the type of the argument
43
+
44
+ if data.nil?
45
+ raise ArgumentError, 'data can\'t be nil.'
46
+ elsif data.is_a?(String)
47
+ data = Request.new [(RequestEntry.new data)],
48
+ quality: quality
49
+ elsif data.is_a? Enumerable
50
+ entries = data.map do |entry|
51
+ case entry
52
+ when String
53
+ # data is an Array[String]
54
+ RequestEntry.new entry.to_s
55
+ when RequestEntry
56
+ # data is an Array[RequestEntry]
57
+ entry
58
+ when Hash
59
+ # data is an Array[{ :inputData, :custom }]
60
+
61
+ raise ArgumentError, 'Input hash must have an :inputData key.' unless entry.key?(:input_data)
62
+
63
+ RequestEntry.new entry[:input_data], entry[:custom]
64
+ else
65
+ raise ArgumentError, 'Cannot map input data.'
66
+ end
67
+ end
68
+
69
+ data = Request.new entries,
70
+ quality: quality
71
+ elsif data.is_a?(RequestEntry)
72
+ data = Request.new data,
73
+ quality: quality
74
+ elsif !data.is_a?(Request)
75
+ raise ArgumentError, "Unsupported data type #{data.class}"
76
+ end
77
+
78
+ # Completion callback
79
+
80
+ if completion_callback.is_a?(Hash)
81
+ completion_callback = Verifalia::EmailValidations::CompletionCallback.new(completion_callback['url'],
82
+ completion_callback['version'],
83
+ completion_callback['skip_server_certificate_validation'])
84
+ end
85
+
86
+ # Send the request to the Verifalia API
87
+
88
+ wait_options_or_default = wait_options.nil? ? WaitOptions.default : wait_options
89
+
90
+ payload = {
91
+ entries: data.entries.map do |entry|
92
+ {
93
+ inputData: entry.input_data,
94
+ custom: entry.custom
95
+ }
96
+ end,
97
+ quality: quality,
98
+ priority: priority,
99
+ deduplication: deduplication,
100
+ name: name,
101
+ retention: retention,
102
+ callback: (
103
+ unless completion_callback.nil?
104
+ {
105
+ url: completion_callback&.url,
106
+ version: completion_callback&.version,
107
+ skipServerCertificateValidation: completion_callback&.skip_server_certificate_validation
108
+ }
109
+ end
110
+ )
111
+ }.compact.to_json
112
+
113
+ response = @rest_client.invoke 'post',
114
+ "email-validations?waitTime=#{wait_options_or_default.submission_wait_time}",
115
+ {
116
+ body: payload,
117
+ headers:
118
+ {
119
+ 'Content-Type': 'application/json',
120
+ 'Accept': 'application/json'
121
+ }
122
+ }
123
+
124
+ if response.status == 202 || response.status == 200
125
+ job = Job.from_json(JSON.parse(response.body))
126
+
127
+ return job if wait_options_or_default == WaitOptions.no_wait || response.status == 200
128
+
129
+ return get(job.overview.id, wait_options: wait_options_or_default)
130
+ end
131
+
132
+ raise "Unexpected HTTP response: #{response.status} #{response.body}"
133
+ end
134
+
135
+ # Returns an email validation job previously submitted for processing.
136
+ #
137
+ # By default, this method waits for the completion of the email validation job: pass a +WaitOptions+ to request
138
+ # a different waiting behavior.
139
+ # @param [String] id The ID of the email validation job to retrieve.
140
+ # @param [nil] wait_options The options which rule out how to wait for the completion of the email validation.
141
+ # @return [Verifalia::EmailValidations::Job] The fetched validation job (or +nil+ if not found).
142
+ def get(id, wait_options: nil)
143
+ wait_options_or_default = wait_options.nil? ? WaitOptions.default : wait_options
144
+
145
+ loop do
146
+ response = @rest_client.invoke 'get',
147
+ "email-validations/#{id}?waitTime=#{wait_options_or_default.poll_wait_time}"
148
+
149
+ return nil if response.status == 404 || response.status == 410
150
+
151
+ unless response.status == 202 || response.status == 200
152
+ raise "Unexpected HTTP response: #{response.status} #{response.body}"
153
+ end
154
+
155
+ job = Job.from_json(JSON.parse(response.body))
156
+
157
+ return job if wait_options_or_default == WaitOptions.no_wait || response.status == 200
158
+
159
+ # Fires a progress, since we are not yet completed
160
+
161
+ wait_options.progress&.call(job.overview)
162
+
163
+ # Wait for the next polling schedule
164
+
165
+ wait_options.wait_for_next_poll(job)
166
+ end
167
+ end
168
+
169
+ # Exports the validated entries for a completed email validation job, using the specified output format.
170
+ #
171
+ # Supported formats:
172
+ # - +text/csv+: Comma-Separated Values (CSV)
173
+ # - +application/vnd.openxmlformats-officedocument.spreadsheetml.sheet+: Microsoft Excel (.xlsx)
174
+ # - +application/vnd.ms-excel+: Microsoft Excel 97-2003 (.xls)
175
+ #
176
+ # @param [String] id The ID of the email validation job to retrieve.
177
+ # @param [String] format The MIME content type of the desired output file format.
178
+ # @return [String] The exported data.
179
+ def export(id, format)
180
+ response = @rest_client.invoke 'get',
181
+ "email-validations/#{id}/entries",
182
+ {
183
+ headers:
184
+ {
185
+ 'Accept': format
186
+ }
187
+ }
188
+
189
+ return nil if response.status == 404 || response.status == 410
190
+ return response.body if response.status == 200
191
+
192
+ raise "Unexpected HTTP response: #{response.status} #{response.body}"
193
+ end
194
+
195
+ # Deletes an email validation job previously submitted for processing.
196
+ # @param [String] id The ID of the email validation job to delete.
197
+ def delete(id)
198
+ response = @rest_client.invoke 'delete',
199
+ "email-validations/#{id}"
200
+
201
+ return if response.status == 200 || response.status == 410
202
+
203
+ raise "Unexpected HTTP response: #{response.status} #{response.body}"
204
+ end
205
+ end
206
+ end
207
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verifalia
4
+ module EmailValidations
5
+ class CompletionCallback
6
+ attr_accessor :url, :version, :skip_server_certificate_validation
7
+
8
+ def initialize(url, version = nil, skip_server_certificate_validation = false)
9
+ @url = url
10
+ @version = version
11
+ @skip_server_certificate_validation = skip_server_certificate_validation
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verifalia
4
+ module EmailValidations
5
+ class Entry
6
+ # The input string being validated.
7
+ attr_reader :input_data
8
+
9
+ # The classification for the status of this email address.
10
+ #
11
+ # Standard values include +Deliverable+, +Risky+, +Undeliverable+ and +Unknown+.
12
+ attr_reader :classification
13
+
14
+ # The validation status for this entry.
15
+ attr_reader :status
16
+
17
+ # Gets the email address, without any eventual comment or folding white space. Returns +nil+ if the input data
18
+ # is not a syntactically invalid e-mail address.
19
+ attr_reader :email_address
20
+
21
+ # Gets the local part of the email address, without comments and folding white spaces.
22
+ attr_reader :email_address_local_part
23
+
24
+ # Gets the domain part of the email address, without comments and folding white spaces.
25
+ #
26
+ # If the ASCII-only (punycode) version of the domain part is needed, use +@ascii_email_address_domain_part+.
27
+ attr_reader :email_address_domain_part
28
+
29
+ # Gets the domain part of the email address, converted to ASCII if needed using the punycode algorithm and with
30
+ # comments and folding white spaces stripped off.
31
+ #
32
+ # If the non-punycode version of the domain part is needed, use +@email_address_domain_part+.
33
+ attr_reader :ascii_email_address_domain_part
34
+
35
+ # If +true+, the email address has an international mailbox name.
36
+ attr_reader :has_international_mailbox_name
37
+
38
+ # If +true+, the email address has an international domain name.
39
+ attr_reader :has_international_domain_name
40
+
41
+ # If +true+, the email address comes from a disposable email address (DEA) provider.
42
+ #
43
+ # See https://verifalia.com/help/email-validations/what-is-a-disposable-email-address-dea for additional information
44
+ # about disposable email addresses.
45
+ attr_reader :is_disposable_email_address
46
+
47
+ # If +true+, the local part of the email address is a well-known role account.
48
+ attr_reader :is_role_account
49
+
50
+ # If +true+, the email address comes from a free email address provider (e.g. gmail, yahoo, outlook / hotmail, ...).
51
+ attr_reader :is_free_email_address
52
+
53
+ # The position of the character in the email address that eventually caused the syntax validation to fail.
54
+ attr_reader :syntax_failure_index
55
+
56
+ # The user-defined, optional string which is passed back upon completing the validation.
57
+ attr_reader :custom
58
+
59
+ # The zero-based index of the first occurrence of this email address in the parent +Job+, in the event the +status+
60
+ # for this entry is +Duplicate+; duplicated items do not expose any result detail apart from this and the eventual
61
+ # +custom+ values.
62
+ attr_reader :duplicate_of
63
+
64
+ # The date this entry has been completed, if available.
65
+ attr_reader :completed_on
66
+
67
+ def initialize (input_data, classification, status, email_address, email_address_local_part, email_address_domain_part,
68
+ has_international_mailbox_name, has_international_domain_name, is_disposable_email_address, is_role_account,
69
+ is_free_email_address, syntax_failure_index, custom, duplicate_of, completed_on, ascii_email_address_domain_part)
70
+ @input_data = input_data
71
+ @classification = classification
72
+ @status = status
73
+ @email_address = email_address
74
+ @email_address_local_part = email_address_local_part
75
+ @email_address_domain_part = email_address_domain_part
76
+ @has_international_mailbox_name = has_international_mailbox_name
77
+ @has_international_domain_name = has_international_domain_name
78
+ @is_disposable_email_address = is_disposable_email_address
79
+ @is_role_account = is_role_account
80
+ @is_free_email_address = is_free_email_address
81
+ @syntax_failure_index = syntax_failure_index
82
+ @custom = custom
83
+ @duplicate_of = duplicate_of
84
+ @completed_on = completed_on
85
+ @ascii_email_address_domain_part = ascii_email_address_domain_part
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ipaddr'
4
+
5
+ module Verifalia
6
+ module EmailValidations
7
+ # Represents a snapshot of an email validation job, along with its overview and eventual validated entries.
8
+ class Job
9
+ # Overview information for this email validation job.
10
+ attr_reader :overview
11
+
12
+ # The eventual validated items for this email validation job.
13
+ attr_reader :entries
14
+
15
+ def initialize(overview, entries)
16
+ @overview = overview
17
+ @entries = entries
18
+ end
19
+
20
+ # Parse a Job from a JSON string.
21
+ def self.from_json(data)
22
+ progress = nil
23
+
24
+ # Parse the eventual progress information
25
+
26
+ if data['overview'].respond_to?('progress')
27
+ progress = Progress.new data['overview']['progress']['percentage'].to_f,
28
+ data['overview']['estimatedTimeRemaining']
29
+ end
30
+
31
+ # Parse the job overview
32
+
33
+ overview = Overview.new data['overview']['id'],
34
+ DateTime.iso8601(data['overview']['submittedOn']),
35
+ (DateTime.iso8601(data['overview']['completedOn']) if data['overview'].key?('completedOn')),
36
+ data['overview']['priority'],
37
+ data['overview']['name'],
38
+ data['overview']['owner'],
39
+ IPAddr.new(data['overview']['clientIP']),
40
+ DateTime.iso8601(data['overview']['createdOn']),
41
+ data['overview']['quality'],
42
+ data['overview']['retention'],
43
+ data['overview']['deduplication'],
44
+ data['overview']['status'],
45
+ data['overview']['noOfEntries'],
46
+ progress
47
+
48
+ # Parse the eventual entries
49
+
50
+ if data.key?('entries')
51
+ entries = data['entries']['data'].map do |entry|
52
+ Entry.new entry['inputData'],
53
+ entry['classification'],
54
+ entry['status'],
55
+ entry['emailAddress'],
56
+ entry['emailAddressLocalPart'],
57
+ entry['emailAddressDomainPart'],
58
+ (entry['hasInternationalMailboxName'] if entry.key?('hasInternationalMailboxName')),
59
+ (entry['hasInternationalDomainName'] if entry.key?('hasInternationalDomainName')),
60
+ (entry['isDisposableEmailAddress'] if entry.key?('isDisposableEmailAddress')),
61
+ (entry['isRoleAccount'] if entry.key?('isRoleAccount')),
62
+ (entry['isFreeEmailAddress'] if entry.key?('isFreeEmailAddress')),
63
+ (entry['syntaxFailureIndex'] if entry.key?('syntaxFailureIndex')),
64
+ entry['custom'],
65
+ (entry['duplicateOf'] if entry.key?('duplicateOf')),
66
+ DateTime.iso8601(entry['completedOn']),
67
+ entry['asciiEmailAddressDomainPart']
68
+ end
69
+ end
70
+
71
+ Job.new overview, entries
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verifalia
4
+ module EmailValidations
5
+ # Overview information for an email validation job.
6
+ class Overview
7
+ # The unique identifier for the validation job.
8
+ attr_reader :id
9
+
10
+ # The processing status for the validation job.
11
+ attr_reader :status
12
+
13
+ # The date and time this validation job has been submitted to Verifalia.
14
+ attr_reader :submitted_on
15
+
16
+ # The date and time this validation job has been eventually completed.
17
+ attr_reader :completed_on
18
+
19
+ # The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account
20
+ # with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others.
21
+ #
22
+ # The allowed range of values spans from +0+ - lowest priority, to +255+ - highest priority, where the midway value
23
+ # +127+ means normal priority; if not specified, Verifalia processes all the concurrent validation jobs for an
24
+ # account using the same priority.
25
+ attr_reader :priority
26
+
27
+ # An optional user-defined name for the validation job, for your own reference.
28
+ attr_reader :name
29
+
30
+ # The unique ID of the Verifalia user who submitted the validation job.
31
+ attr_reader :owner
32
+
33
+ # The IP address of the client which submitted the validation job.
34
+ attr_reader :client_ip
35
+
36
+ # The date and time the validation job was created.
37
+ attr_reader :created_on
38
+
39
+ # A reference to the results quality level this job was validated against.
40
+ attr_reader :quality
41
+
42
+ # The maximum data retention period Verifalia observes for this verification job, after which the job will be
43
+ # automatically deleted.
44
+ #
45
+ # A verification job can be deleted anytime prior to its retention period through the +delete()+ method.
46
+ attr_reader :retention
47
+
48
+ # A deduplication mode option which affected the way Verifalia eventually marked entries as duplicates upon processing.
49
+ attr_reader :deduplication
50
+
51
+ # The number of entries the validation job contains.
52
+ attr_reader :no_of_entries
53
+
54
+ # The eventual completion progress for the validation job.
55
+ attr_reader :progress
56
+
57
+ def initialize(id, submitted_on, completed_on, priority, name, owner, client_ip, created_on, quality, retention,
58
+ deduplication, status, no_of_entries, progress)
59
+ @id = id
60
+ @status = status
61
+ @submitted_on = submitted_on
62
+ @completed_on = completed_on
63
+ @priority = priority
64
+ @name = name
65
+ @owner = owner
66
+ @client_ip = client_ip
67
+ @created_on = created_on
68
+ @quality = quality
69
+ @retention = retention
70
+ @deduplication = deduplication
71
+ @no_of_entries = no_of_entries
72
+ @progress = progress
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verifalia
4
+ module EmailValidations
5
+ class Progress
6
+ # The overall progress percentage for the job, with a value between 0 and 1.
7
+ attr_reader :percentage
8
+ # A string representing the estimated remaining time for completing the email validation job, expressed in the
9
+ # format +dd.hh:mm:ss+ (where dd: days, hh: hours, mm: minutes, ss: seconds); the initial dd. part is added only
10
+ # for huge lists requiring more than 24 hours to complete.
11
+ attr_reader :estimated_time_remaining
12
+
13
+ def initialize(percentage, estimated_time_remaining)
14
+ @percentage = percentage
15
+ @estimated_time_remaining = estimated_time_remaining
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verifalia
4
+ module EmailValidations
5
+ class Request
6
+ attr_accessor :entries, :quality, :priority, :deduplication, :name, :retention, :callback
7
+
8
+ def initialize(entries, quality: nil, priority: nil, deduplication: nil, name: nil, retention: nil, callback: nil)
9
+ @entries = entries
10
+ @quality = quality
11
+ @priority = priority
12
+ @deduplication = deduplication
13
+ @name = name
14
+ @retention = retention
15
+ @callback = callback
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verifalia
4
+ module EmailValidations
5
+ class RequestEntry
6
+ attr_accessor :input_data, :custom
7
+
8
+ def initialize(input_data, custom = nil)
9
+ @input_data = input_data
10
+ @custom = custom
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verifalia
4
+ module EmailValidations
5
+ class WaitOptions
6
+ @@default = nil
7
+ @@no_wait = nil
8
+
9
+ attr_reader :submission_wait_time, :poll_wait_time, :progress
10
+
11
+ def initialize(submission_wait_time, poll_wait_time, progress: nil)
12
+ @submission_wait_time = submission_wait_time
13
+ @poll_wait_time = poll_wait_time
14
+ @progress = progress
15
+ end
16
+
17
+ def self.default
18
+ @@default = WaitOptions.new 30 * 1000, 30 * 1000 if @@default.nil?
19
+ @@default
20
+ end
21
+
22
+ def self.no_wait
23
+ @@no_wait = WaitOptions.new 0, 0 if @@no_wait.nil?
24
+ @@no_wait
25
+ end
26
+
27
+ def wait_for_next_poll(job)
28
+ # Observe the ETA if we have one, otherwise a delay given the following formula:
29
+ # delay = max(0.5, min(30, 2^(log(noOfEntries, 10) - 1)))
30
+
31
+ if !job.overview.progress.nil? && !job.overview.progress.estimated_time_remaining.nil?
32
+ # Convert the ETA format (dd.)HH:mm:ss into the number of remaining seconds
33
+
34
+ eta_match = /((\d*)\.)?(\d{1,2}):(\d{1,2}):(\d{1,2})/.match(job.overview.progress.estimated_time_remaining)
35
+
36
+ days = (eta_match[2] || '0').to_i
37
+ hours = eta_match[3].to_i
38
+ minutes = eta_match[4].to_i
39
+ seconds = eta_match[5].to_i
40
+
41
+ delay = days * 24 * 60 * 60 +
42
+ hours * 60 * 60 +
43
+ minutes * 60 +
44
+ seconds
45
+ else
46
+ delay = [0.5, [30, 2**(Math.log10(job.overview.no_of_entries) - 1)].min].max
47
+ end
48
+
49
+ sleep(delay)
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday'
4
+ require 'json'
5
+
6
+ module Verifalia
7
+ module Rest
8
+ BASE_URLS = %w[https://api-1.verifalia.com/v2.4 https://api-2.verifalia.com/v2.4 https://api-3.verifalia.com/v2.4].freeze
9
+ BASE_CCA_URLS = %w[https://api-cca-1.verifalia.com/v2.4 https://api-cca-2.verifalia.com/v2.4 https://api-cca-3.verifalia.com/v2.4].freeze
10
+
11
+ class Client
12
+ # Optional debug logger
13
+ attr_writer :logger
14
+
15
+ def initialize(authenticator, user_agent, base_urls)
16
+ @authenticator = authenticator
17
+ @user_agent = user_agent
18
+ @base_urls = base_urls.shuffle
19
+
20
+ @current_base_url_idx = 0
21
+ end
22
+
23
+ def invoke(method, resource, options = nil)
24
+ errors = []
25
+
26
+ # Performs a maximum of as many attempts as the number of configured base API endpoints, keeping track
27
+ # of the last used endpoint after each call, in order to try to distribute the load evenly across the
28
+ # available endpoints.
29
+
30
+ (0...@base_urls.length).each {
31
+ base_url = @base_urls[@current_base_url_idx % @base_urls.length]
32
+ @current_base_url_idx += 1
33
+
34
+ # Build the final URL
35
+
36
+ final_url = "#{base_url}/#{resource}"
37
+
38
+ @logger&.info("Invoking #{method.upcase} #{final_url}")
39
+
40
+ # Init the HTTP request
41
+
42
+ connection = Faraday.new(
43
+ headers: { 'User-Agent' => @user_agent }
44
+ )
45
+
46
+ request = connection.build_request(method)
47
+ request.url(final_url)
48
+
49
+ # Options
50
+
51
+ unless options.nil?
52
+ request.body = options[:body] unless options[:body].nil?
53
+ request.headers = request.headers.merge(options[:headers]) unless options[:headers].nil?
54
+ end
55
+
56
+ # Authenticate the underlying client, if needed
57
+
58
+ @authenticator.authenticate connection, request
59
+
60
+ begin
61
+ # Send the request to the Verifalia servers
62
+
63
+ connection.builder.build_response(connection, request).on_complete do |response|
64
+ if (500...599).include?(response.status)
65
+ raise "Server error (HTTP status #{response.status}) while invoking #{final_url}"
66
+ end
67
+
68
+ return response
69
+ end
70
+ rescue => e
71
+ @logger&.warn("Error while invoking #{method.upcase} #{final_url}. #{e.to_s}")
72
+ errors.append(e)
73
+ end
74
+ }
75
+
76
+ # Generate an error out of the potentially multiple invocation errors
77
+
78
+ raise "All the base URIs are unreachable:\n#{errors.map { |error| error.to_s }.join("\n")}"
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verifalia
4
+ module Security
5
+ # Allows to authenticate to Verifalia with a client certificate.
6
+ class CertificateAuthenticator
7
+ def initialize(ssl_client_cert, ssl_client_key)
8
+ ssl_client_cert = OpenSSL::X509::Certificate.new(File.read(ssl_client_cert)) if ssl_client_cert.is_a?(String)
9
+ ssl_client_key = OpenSSL::PKey::RSA.new(File.read(ssl_client_key)) if ssl_client_key.is_a?(String) && !ssl_client_key.nil?
10
+
11
+ @ssl_client_cert = ssl_client_cert
12
+ @ssl_client_key = ssl_client_key
13
+ end
14
+
15
+ def authenticate(connection, request)
16
+ connection.ssl.client_cert = @ssl_client_cert
17
+ connection.ssl.client_key = @ssl_client_key
18
+ end
19
+ end
20
+ end
21
+ end