spreedly-composer-sdk-server 1.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.
@@ -0,0 +1,250 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Composer
4
+ # Logs that a tracking event was not sent because a required field was missing.
5
+ module UnsentEvent
6
+ def self.log(reason)
7
+ Logger.error("Composer event was not sent: #{reason}").log
8
+ end
9
+ end
10
+
11
+ # Main Composer SDK class
12
+ class ComposerClient
13
+ attr_reader :secret_key, :config
14
+
15
+ def initialize(secret_key, config = {})
16
+ # Validate secret key
17
+ raise MissingConfigError, 'Secret API key is required' if Utilities.null_or_empty?(secret_key)
18
+
19
+ @secret_key = secret_key
20
+
21
+ # Merge with default config
22
+ @config = DEFAULT_CONFIG.merge(config)
23
+
24
+ # Validate API version
25
+ unless [ApiVersion::V1].include?(@config[:api_version])
26
+ raise InvalidConfigError, "Invalid API version: #{@config[:api_version]}"
27
+ end
28
+
29
+ # Validate log level
30
+ log_level = @config[:log_level] || ComposerLogLevel::INFO
31
+ unless [ComposerLogLevel::TRACE, ComposerLogLevel::INFO, ComposerLogLevel::ERROR, ComposerLogLevel::NONE].include?(log_level)
32
+ raise InvalidConfigError, "Invalid log level: #{log_level}"
33
+ end
34
+
35
+ # Set logger filter level
36
+ Logger.filter_level = Severity.from_log_level(log_level)
37
+
38
+ # Resolved after the logger is configured so any warning respects log_level.
39
+ @config[:request_timeout_ms] = Utilities.resolve_request_timeout_ms(@config[:request_timeout_ms])
40
+ end
41
+
42
+ # Send tracking event
43
+ def event(event:, session_id: nil, user_id: nil, source_token: nil)
44
+ return UnsentEvent.log('no event was provided') if Utilities.null_or_empty?(event)
45
+ return UnsentEvent.log('event.type is missing') if Utilities.null_or_empty?(event.type) || event.type.to_s.strip.empty?
46
+ if session_id.to_s.strip.empty? && source_token.to_s.strip.empty?
47
+ return UnsentEvent.log('Must provide either a sessionId or sourceToken')
48
+ end
49
+
50
+ # Only an explicit false disables the SDK. nil must not overwrite the default.
51
+ return nil if @config[:enabled] == false
52
+
53
+ # Ensure event has a timestamp
54
+ event.event_time ||= (Time.now.to_f * 1000).to_i
55
+
56
+ # Send event to API
57
+ url = "#{Utilities.construct_api_url(@config[:api_url], @config[:api_version])}track"
58
+ headers = Utilities.construct_api_headers(@secret_key, nil, source_token, user_id, session_id)
59
+
60
+ response = Utilities.make_request(
61
+ url: url,
62
+ method: :post,
63
+ headers: headers,
64
+ body: event.to_h,
65
+ request_timeout_ms: @config[:request_timeout_ms]
66
+ )
67
+ # make_request already logged a request that never got a response.
68
+ if !response[:request_failed] && !(200..299).cover?(response[:status])
69
+ Logger.error("Composer event was not accepted by the API (HTTP #{response[:status]}).").log
70
+ end
71
+
72
+ nil
73
+ end
74
+
75
+ # Alias methods for backward compatibility
76
+ alias notify event
77
+ alias track event
78
+
79
+ # Submit checkpoint
80
+ def checkpoint(checkpoint_name:, event:, session_id: nil, user_id: nil, source_token: nil,
81
+ use_verification_id: nil, options: {})
82
+ # Validate required parameters
83
+ raise MissingParameterError, 'checkpoint_name is required' if checkpoint_name.to_s.strip.empty?
84
+ raise MissingParameterError, 'event is required' if Utilities.null_or_empty?(event)
85
+
86
+ if session_id.to_s.strip.empty? && source_token.to_s.strip.empty?
87
+ raise MissingParameterError, 'Either session_id or source_token is required'
88
+ end
89
+
90
+ # Only an explicit false disables the SDK. nil must not overwrite the default.
91
+ if @config[:enabled] == false
92
+ return CheckpointResponse.new(
93
+ success: true,
94
+ errors: [],
95
+ version: ApiVersion::V1,
96
+ verification: Verification.new(
97
+ id: 'COMPOSER_IS_DISABLED',
98
+ status: VerificationStatus::COMPLETE,
99
+ outcome: VerificationOutcome::APPROVED,
100
+ step_data: {}
101
+ ),
102
+ is_timeout: false
103
+ )
104
+ end
105
+
106
+ # Setup timing and polling parameters
107
+ checkpoint_timeout = options[:timeout]&.positive? ? options[:timeout] : BASE_CHECKPOINT_MAX_TIMEOUT_MS
108
+ current_polling_wait = BASE_CHECKPOINT_POLLING_WAIT_MS
109
+ has_never_polled = true
110
+ num_failures = 0
111
+ checkpoint_start_time = Time.now
112
+
113
+ # Prepare request options
114
+ request_options = { sync: options[:sync] || false }
115
+
116
+ # Submit checkpoint to API
117
+ url = "#{Utilities.construct_api_url(@config[:api_url], @config[:api_version])}checkpoint"
118
+ headers = Utilities.construct_api_headers(@secret_key, use_verification_id, source_token, user_id, session_id)
119
+
120
+ event_body = { type: checkpoint_name, data: event.data }
121
+ event_body[:ip] = event.ip unless Utilities.null_or_empty?(event.ip)
122
+ body = { event: event_body, options: request_options }
123
+
124
+ http_response = Utilities.make_request(url: url, method: :post, headers: headers, body: body,
125
+ request_timeout_ms: @config[:request_timeout_ms])
126
+ response_body = http_response[:body]
127
+ response = Utilities.parse_checkpoint_response(response_body)
128
+
129
+ # Handle error or unsuccessful response
130
+ return response unless response.success
131
+
132
+ # Log initial response
133
+ if Logger.trace?
134
+ Logger.trace("Initial checkpoint response: #{Utilities.redact_sensitive_fields(response_body).to_json}").log
135
+ end
136
+
137
+ # Only poll PENDING; BLOCKED waits on a client action such as MFA.
138
+ is_resolved = response.verification&.status != VerificationStatus::PENDING
139
+ verification_id = response.verification&.id
140
+
141
+ # Poll for verification result if needed
142
+ while !is_resolved &&
143
+ ((Time.now - checkpoint_start_time) * 1000 < checkpoint_timeout || has_never_polled) &&
144
+ num_failures < MAX_FAILURE_COUNT
145
+
146
+ Utilities.sleep_ms(current_polling_wait)
147
+ current_polling_wait = [current_polling_wait * 2, MAX_POLLING_WAIT_MS].min
148
+ has_never_polled = false
149
+
150
+ # Poll verification endpoint
151
+ poll_url = "#{Utilities.construct_api_url(@config[:api_url],
152
+ @config[:api_version])}verification/#{verification_id}"
153
+ poll_response = Utilities.make_request(url: poll_url, method: :get, headers: headers,
154
+ request_timeout_ms: @config[:request_timeout_ms])
155
+ response_body = poll_response[:body]
156
+ response = Utilities.parse_checkpoint_response(response_body)
157
+
158
+ if response.success && response.verification
159
+ status = response.verification.status
160
+ if status.nil?
161
+ num_failures += 1
162
+ else
163
+ is_resolved = status != VerificationStatus::PENDING
164
+ num_failures = 0 # Reset on successful response
165
+ end
166
+ else
167
+ num_failures += 1
168
+ end
169
+ end
170
+
171
+ # Handle max failures
172
+ if num_failures >= MAX_FAILURE_COUNT
173
+ Logger.error('Service Unavailable: Maximum retry count exceeded').log
174
+ return CheckpointResponse.new(
175
+ success: false,
176
+ errors: [ApiError.new(code: 503, message: 'Service Unavailable: Maximum retry count exceeded')],
177
+ version: ApiVersion::V1,
178
+ is_timeout: true
179
+ )
180
+ end
181
+
182
+ # Log final response
183
+ Logger.trace("Returning response: #{Utilities.redact_sensitive_fields(response_body).to_json}").log if Logger.trace?
184
+
185
+ response
186
+ end
187
+
188
+ # Helper methods (can be used as instance or class methods)
189
+ def self.allowed?(response)
190
+ response.allowed?
191
+ end
192
+
193
+ def self.denied?(response)
194
+ response.denied?
195
+ end
196
+
197
+ def self.running?(response)
198
+ response.running?
199
+ end
200
+
201
+ def self.undecided?(response)
202
+ response.undecided?
203
+ end
204
+
205
+ def self.error?(response)
206
+ response.error?
207
+ end
208
+
209
+ # rubocop:disable Naming/PredicatePrefix
210
+ def self.has_error?(response)
211
+ error?(response)
212
+ end
213
+ # rubocop:enable Naming/PredicatePrefix
214
+
215
+ def self.timeout?(response)
216
+ response.timeout?
217
+ end
218
+
219
+ # Instance method versions
220
+ def allowed?(response)
221
+ self.class.allowed?(response)
222
+ end
223
+
224
+ def denied?(response)
225
+ self.class.denied?(response)
226
+ end
227
+
228
+ def running?(response)
229
+ self.class.running?(response)
230
+ end
231
+
232
+ def undecided?(response)
233
+ self.class.undecided?(response)
234
+ end
235
+
236
+ def error?(response)
237
+ self.class.error?(response)
238
+ end
239
+
240
+ # rubocop:disable Naming/PredicatePrefix
241
+ def has_error?(response)
242
+ error?(response)
243
+ end
244
+ # rubocop:enable Naming/PredicatePrefix
245
+
246
+ def timeout?(response)
247
+ self.class.timeout?(response)
248
+ end
249
+ end
250
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Composer
4
+ # API version constants
5
+ module ApiVersion
6
+ V1 = 'v1'
7
+ end
8
+
9
+ # Verification status constants
10
+ module VerificationStatus
11
+ PENDING = 'PENDING'
12
+ BLOCKED = 'BLOCKED'
13
+ COMPLETE = 'COMPLETE'
14
+ FAILED = 'FAILED'
15
+ end
16
+
17
+ # Verification outcome constants
18
+ module VerificationOutcome
19
+ APPROVED = 'APPROVED'
20
+ DENIED = 'DENIED'
21
+ PENDING = 'PENDING'
22
+ ERROR = 'ERROR'
23
+ USAGE_LIMIT = 'USAGE_LIMIT'
24
+ API_LIMIT = 'API_LIMIT'
25
+ end
26
+
27
+ DEFAULT_REQUEST_TIMEOUT_MS = 30 * 1000 # 30 seconds
28
+
29
+ # Default configuration
30
+ DEFAULT_CONFIG = {
31
+ api_version: ApiVersion::V1,
32
+ api_url: 'https://api.dodgeballhq.com/',
33
+ log_level: ComposerLogLevel::INFO,
34
+ enabled: true,
35
+ request_timeout_ms: DEFAULT_REQUEST_TIMEOUT_MS
36
+ }.freeze
37
+
38
+ # Polling constants
39
+ BASE_CHECKPOINT_POLLING_WAIT_MS = 100
40
+ MAX_POLLING_WAIT_MS = 2000
41
+ BASE_CHECKPOINT_MAX_TIMEOUT_MS = 10 * 60 * 1000 # 10 minutes in ms
42
+ MAX_FAILURE_COUNT = 3
43
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Composer
4
+ # Backward compatibility wrapper for Dodgeball naming
5
+ class DodgeballClient < ComposerClient
6
+ # Inherits all methods from ComposerClient
7
+ # This provides backward compatibility for code using the Dodgeball name
8
+ end
9
+ end
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'time'
5
+
6
+ module Composer
7
+ # Log levels for Composer SDK
8
+ module ComposerLogLevel
9
+ TRACE = 'TRACE'
10
+ INFO = 'INFO'
11
+ ERROR = 'ERROR'
12
+ NONE = 'NONE'
13
+ end
14
+
15
+ # Backward compatibility alias
16
+ DodgeballLogLevel = ComposerLogLevel
17
+
18
+ # Logger severity enum
19
+ module Severity
20
+ TRACE = 0
21
+ INFO = 1
22
+ ERROR = 2
23
+ NONE = 3
24
+
25
+ def self.from_log_level(level)
26
+ case level
27
+ when ComposerLogLevel::TRACE then TRACE
28
+ when ComposerLogLevel::INFO then INFO
29
+ when ComposerLogLevel::ERROR then ERROR
30
+ when ComposerLogLevel::NONE then NONE
31
+ else INFO # rubocop:disable Lint/DuplicateBranch
32
+ end
33
+ end
34
+
35
+ def self.to_string(severity)
36
+ case severity
37
+ when TRACE then 'TRACE'
38
+ when INFO then 'INFO'
39
+ when ERROR then 'ERROR'
40
+ when NONE then 'NONE'
41
+ else 'UNKNOWN'
42
+ end
43
+ end
44
+ end
45
+
46
+ # Log entry class for structured logging
47
+ class LogEntry
48
+ attr_accessor :message, :severity, :error, :date
49
+ attr_reader :parameters
50
+
51
+ def initialize(message, severity, error = nil)
52
+ @message = message
53
+ @severity = severity
54
+ @error = error
55
+ @parameters = {}
56
+ @date = Time.now
57
+ end
58
+
59
+ def parameters=(params)
60
+ @parameters = params || {}
61
+ end
62
+
63
+ # rubocop:disable Naming/AccessorMethodName
64
+ def set_parameters(params)
65
+ self.parameters = params
66
+ self
67
+ end
68
+ # rubocop:enable Naming/AccessorMethodName
69
+
70
+ def set_parameter(key, value)
71
+ @parameters[key] = value
72
+ self
73
+ end
74
+
75
+ # rubocop:disable Naming/AccessorMethodName
76
+ def set_severity(sev)
77
+ @severity = sev
78
+ self
79
+ end
80
+
81
+ def set_error(err)
82
+ @error = err
83
+ self
84
+ end
85
+ # rubocop:enable Naming/AccessorMethodName
86
+
87
+ def log
88
+ Logger.log(self)
89
+ end
90
+ end
91
+
92
+ # Main logger class
93
+ class Logger
94
+ @filter_level = Severity::INFO
95
+
96
+ class << self
97
+ attr_accessor :filter_level
98
+
99
+ # Callers check this before assembling an expensive trace message, because the
100
+ # message is built before log gets a chance to discard it
101
+ def trace?
102
+ @filter_level <= Severity::TRACE
103
+ end
104
+
105
+ def info(message, parameters = nil)
106
+ entry = LogEntry.new(message, Severity::INFO)
107
+ entry.set_parameters(parameters) if parameters
108
+ entry
109
+ end
110
+
111
+ def trace(message, parameters = nil)
112
+ entry = LogEntry.new(message, Severity::TRACE)
113
+ entry.set_parameters(parameters) if parameters
114
+ entry
115
+ end
116
+
117
+ def error(message, error = nil)
118
+ LogEntry.new(message, Severity::ERROR, error)
119
+ end
120
+
121
+ def format_error(error)
122
+ return '' unless error
123
+
124
+ result = {
125
+ message: error.message,
126
+ name: error.class.name
127
+ }
128
+
129
+ result[:stack] = error.backtrace.join("\n") if error.backtrace
130
+
131
+ result.to_json
132
+ end
133
+
134
+ def log(log_entry)
135
+ return if log_entry.severity < @filter_level
136
+
137
+ output = {
138
+ severity: Severity.to_string(log_entry.severity),
139
+ date: log_entry.date.utc.iso8601(6),
140
+ message: log_entry.message
141
+ }
142
+
143
+ output[:parameters] = log_entry.parameters unless log_entry.parameters.empty?
144
+ output[:error] = format_error(log_entry.error) if log_entry.error
145
+
146
+ puts output.to_json
147
+ end
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Composer
4
+ # Custom error classes
5
+ class ComposerError < StandardError; end
6
+ class MissingParameterError < ComposerError; end
7
+ class MissingConfigError < ComposerError; end
8
+ class InvalidConfigError < ComposerError; end
9
+
10
+ # Checkpoint event structure
11
+ class CheckpointEvent
12
+ attr_accessor :ip, :data
13
+
14
+ def initialize(ip: nil, data: {})
15
+ @ip = ip
16
+ @data = data
17
+ end
18
+
19
+ def to_h
20
+ {
21
+ ip: @ip,
22
+ data: @data
23
+ }
24
+ end
25
+ end
26
+
27
+ # Track event structure
28
+ class TrackEvent
29
+ attr_accessor :type, :data, :event_time
30
+
31
+ def initialize(type:, data: {}, event_time: nil)
32
+ @type = type
33
+ @data = data
34
+ @event_time = event_time
35
+ end
36
+
37
+ def to_h
38
+ result = {
39
+ type: @type,
40
+ data: @data
41
+ }
42
+ result[:eventTime] = @event_time if @event_time
43
+ result
44
+ end
45
+ end
46
+
47
+ # Verification step data
48
+ class VerificationStepData
49
+ attr_accessor :id, :name, :data
50
+
51
+ def initialize(id:, name:, data: {})
52
+ @id = id
53
+ @name = name
54
+ @data = data
55
+ end
56
+ end
57
+
58
+ # Verification object
59
+ class Verification
60
+ attr_accessor :id, :status, :outcome, :step_data, :next_steps
61
+
62
+ def initialize(id:, status:, outcome:, step_data: {}, next_steps: [])
63
+ @id = id
64
+ @status = status
65
+ @outcome = outcome
66
+ @step_data = step_data
67
+ @next_steps = next_steps
68
+ end
69
+ end
70
+
71
+ # API error structure
72
+ class ApiError
73
+ attr_accessor :code, :message
74
+
75
+ def initialize(message:, code: nil)
76
+ @code = code
77
+ @message = message
78
+ end
79
+ end
80
+
81
+ # Checkpoint response
82
+ class CheckpointResponse
83
+ attr_accessor :success, :errors, :version, :verification, :is_timeout
84
+
85
+ def initialize(success:, errors: [], version: ApiVersion::V1, verification: nil, is_timeout: false)
86
+ @success = success
87
+ @errors = errors
88
+ @version = version
89
+ @verification = verification
90
+ @is_timeout = is_timeout
91
+ end
92
+
93
+ # Helper methods for checking response status
94
+ def allowed?
95
+ @success && @verification&.status == VerificationStatus::COMPLETE &&
96
+ @verification&.outcome == VerificationOutcome::APPROVED
97
+ end
98
+
99
+ def denied?
100
+ @success && @verification&.outcome == VerificationOutcome::DENIED
101
+ end
102
+
103
+ def running?
104
+ @success && @verification &&
105
+ [VerificationStatus::PENDING, VerificationStatus::BLOCKED].include?(@verification.status) &&
106
+ @verification.outcome == VerificationOutcome::PENDING
107
+ end
108
+
109
+ def undecided?
110
+ @success && @verification&.status == VerificationStatus::COMPLETE &&
111
+ @verification&.outcome == VerificationOutcome::PENDING
112
+ end
113
+
114
+ def error?
115
+ !@success || @verification&.outcome == VerificationOutcome::ERROR
116
+ end
117
+
118
+ # rubocop:disable Naming/PredicatePrefix
119
+ def has_error?
120
+ error?
121
+ end
122
+ # rubocop:enable Naming/PredicatePrefix
123
+
124
+ def timeout?
125
+ @is_timeout
126
+ end
127
+ end
128
+ end