kameleoon-client-ruby 3.22.1 → 3.23.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,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'kameleoon/network/streaming/sse_message'
4
+
5
+ module Kameleoon
6
+ module Network
7
+ module Streaming
8
+ ##
9
+ # SseClient is used to interpret SSE event stream.
10
+ class SseClient
11
+ ##
12
+ # Parametrized initializer.
13
+ #
14
+ # @param sse_request [Kameleoon::Network::Streaming::SseRequest] Used to access SSE event stream.
15
+ # @param message_handler [Callable[Kameleoon::Network::Streaming::SseMessage] | NilClass] Callable object which
16
+ # is synchronously called for received SSE messages.
17
+ def initialize(sse_request, message_handler)
18
+ @sse_request = sse_request
19
+ @message_handler = message_handler
20
+
21
+ @cr_prev = nil
22
+ @buffer = nil
23
+ @data_buffer = nil
24
+ @event = nil
25
+ @id = nil
26
+ @reconnection_time = nil
27
+
28
+ @sse_request.resp_char_handler = method(:process_char)
29
+ end
30
+
31
+ ##
32
+ # Starts SSE connection and stay in the loop until close.
33
+ def start
34
+ @cr_prev = false
35
+ @data_buffer = []
36
+ @event = nil
37
+ @id = nil
38
+ @buffer = []
39
+ @sse_request.start
40
+ end
41
+
42
+ ##
43
+ # Calls @sse_request@close_handler if it is not nil.
44
+ def call_close_handler
45
+ @sse_request.call_close_handler
46
+ end
47
+
48
+ private
49
+
50
+ def process_char(ch)
51
+ if @cr_prev && (ch == "\n")
52
+ @cr_prev = false
53
+ return
54
+ end
55
+ @cr_prev = ch == "\r"
56
+ if @cr_prev || (ch == "\n")
57
+ line = @buffer.join
58
+ @buffer.clear
59
+ if line.empty?
60
+ dispatch_event
61
+ else
62
+ handle_line(line)
63
+ end
64
+ return
65
+ end
66
+ @buffer << ch
67
+ end
68
+
69
+ def handle_line(line)
70
+ field, value = parse_line(line)
71
+ return if field.nil?
72
+
73
+ case field
74
+ when 'event'
75
+ @event = value
76
+ when 'data'
77
+ @data_buffer << value
78
+ when 'id'
79
+ @id = value
80
+ when 'retry'
81
+ @reconnection_time = value.to_i # This does not affect anything
82
+ end
83
+ end
84
+
85
+ def parse_line(line)
86
+ colon_index = line.index(':')
87
+ return line, nil if colon_index.nil?
88
+ return nil, nil if colon_index.zero?
89
+
90
+ field = line[0, colon_index]
91
+ return field, '' if colon_index + 1 == line.length
92
+
93
+ value = if line[colon_index + 1] == ' '
94
+ line[colon_index + 2..]
95
+ else
96
+ line[colon_index + 1..]
97
+ end
98
+ [field, value]
99
+ end
100
+
101
+ def dispatch_event
102
+ return unless !@event.nil? || !@data_buffer.empty? # Ignoring empty events
103
+
104
+ data = @data_buffer.join("\n")
105
+ message = SseMessage.new(@event, @id, data)
106
+ @event = nil
107
+ @data_buffer.clear
108
+ @message_handler&.call(message)
109
+ end
110
+ end
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kameleoon
4
+ module Network
5
+ module Streaming
6
+ ##
7
+ # SseMessage is a container for a received SSE message.
8
+ class SseMessage
9
+ attr_reader :event, :id, :data
10
+
11
+ ##
12
+ # Parametrized initializer.
13
+ #
14
+ # @param event [String]
15
+ # @param id [String]
16
+ # @param data [String]
17
+ def initialize(event, id, data)
18
+ @event = event
19
+ @id = id
20
+ @data = data
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+
5
+ module Kameleoon
6
+ module Network
7
+ module Streaming
8
+ ##
9
+ # SseRequest is used keep SSE connection and read from its stream.
10
+ class SseRequest
11
+ # Detects stalled and half-dead connections (e.g. silently dropped by a NAT or load balancer), which
12
+ # would otherwise hang forever. Must stay above the server's keep-alive interval (180 s,
13
+ # `server.sse.keepalive.writer-idle` in ms-client-configs), so don't change it without the agreement
14
+ # of the ms-client-configs team.
15
+ READ_TIMEOUT_SECONDS = 6 * 60
16
+
17
+ attr_writer :resp_char_handler
18
+
19
+ ##
20
+ # Parametrized initializer.
21
+ #
22
+ # @param url [String]
23
+ # @param headers [Hash]
24
+ # @param open_handler [Callable | NilClass] Handler which is synchronously called when SSE connection is open
25
+ # (a 200 response is received).
26
+ # @param close_handler [Callable | NilClass] Handler which is synchronously called when SSE connection is closed.
27
+ # @param unexpected_status_code_handler [Callable[Net::HTTPResponse] | NilClass] Handler whick
28
+ # is synchronously called for responses with not 200 status code.
29
+ # @param read_timeout [Numeric] Seconds of silence after which the connection is considered stalled;
30
+ # `start` then raises `Net::ReadTimeout`.
31
+ def initialize(url, headers, open_handler, close_handler, unexpected_status_code_handler,
32
+ read_timeout: READ_TIMEOUT_SECONDS)
33
+ @url = url
34
+ @headers = headers
35
+ @open_handler = open_handler
36
+ @close_handler = close_handler
37
+ @unexpected_status_code_handler = unexpected_status_code_handler
38
+ @read_timeout = read_timeout
39
+
40
+ @resp_char_handler = nil
41
+ end
42
+
43
+ ##
44
+ # Starts SSE connection and stay in the loop until close.
45
+ def start
46
+ uri = URI(@url)
47
+ # The stream is silent between events, but the server sends keep-alives more often than the timeout.
48
+ # No implicit retry on a read timeout (`Net::HTTP` retries a GET once by default): a stalled
49
+ # connection is reported to the caller, which reconnects following its own policy.
50
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', read_timeout: @read_timeout,
51
+ max_retries: 0) do |http|
52
+ http.request(Net::HTTP::Get.new(uri, @headers)) { |resp| handle_resp(resp) }
53
+ end
54
+ end
55
+
56
+ ##
57
+ # Calls @close_handler if it is not nil.
58
+ def call_close_handler
59
+ @close_handler&.call
60
+ end
61
+
62
+ private
63
+
64
+ def handle_resp(resp)
65
+ if resp.code == '200'
66
+ @open_handler&.call
67
+ resp.read_body do |chunk|
68
+ chunk.each_char { |ch| @resp_char_handler&.call(ch) }
69
+ end
70
+ else
71
+ @unexpected_status_code_handler&.call(resp)
72
+ end
73
+ call_close_handler
74
+ end
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,177 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Kameleoon Streaming Service
4
+
5
+ require 'json'
6
+ require 'kameleoon/logging/kameleoon_logger'
7
+ require 'kameleoon/network/streaming/data_file_update_message'
8
+ require 'kameleoon/network/streaming/sse_request'
9
+ require 'kameleoon/network/streaming/sse_client'
10
+
11
+ module Kameleoon
12
+ module Network
13
+ module Streaming
14
+ # The server pushed a new configuration.
15
+ CONFIGURATION_UPDATE_EVENT = 'configuration-update-event'
16
+ # Sent by the server on every (re)connection with the timestamp of the current
17
+ # configuration, so that an update published while the SDK was disconnected is not missed.
18
+ CONNECTION_OPEN_EVENT = 'connection-open-event'
19
+ STREAMING_EVENT_TYPES = [CONFIGURATION_UPDATE_EVENT, CONNECTION_OPEN_EVENT].freeze
20
+
21
+ ##
22
+ # StreamingService is used for fetching updates of configuration
23
+ # (experiments and feature flags) through the streaming (SSE) connection.
24
+ class StreamingService
25
+ # Delay before re-establishing the SSE connection after a failure or a server-side close.
26
+ RECONNECT_DELAY_SECONDS = 10
27
+ # Reconnections attempted, without a received event in between, before giving up.
28
+ MAX_RETRIES = 1
29
+ CLOSED_BY_SERVER = 'was closed by server'
30
+
31
+ ##
32
+ # Parametrized initializer.
33
+ #
34
+ # @param url [String]
35
+ # @param data_file_update_handler [Callable[DataFileUpdateMessage] | NilClass] Handler which is
36
+ # synchronously called for each received DataFileUpdateMessage.
37
+ # @param reconnect_delay [Numeric] Delay in seconds before a reconnect attempt.
38
+ # @param streaming_unavailable_handler [Callable[StreamingService] | NilClass] Handler which is
39
+ # called once `MAX_RETRIES + 1` connections in a row have ended without delivering an event; the
40
+ # service is closed by then.
41
+ def initialize(url, data_file_update_handler, sse_request_source = nil,
42
+ reconnect_delay: RECONNECT_DELAY_SECONDS, streaming_unavailable_handler: nil)
43
+ @url = url
44
+ @data_file_update_handler = data_file_update_handler
45
+ @streaming_unavailable_handler = streaming_unavailable_handler
46
+ @need_close = false
47
+ @failure_reason = nil # set while the current connection has failed
48
+ @consecutive_disconnects = 0
49
+ @headers = {
50
+ 'Accept': 'text/event-stream',
51
+ 'Cache-Control': 'no-cache',
52
+ 'Connection': 'Keep-Alive'
53
+ }
54
+ @sse_request_source = sse_request_source
55
+ @reconnect_delay = reconnect_delay
56
+ @sse_thread = nil
57
+ @sse_client = nil
58
+ create_sse_client
59
+ end
60
+
61
+ ##
62
+ # `true` once the service has been closed, or has given up reconnecting.
63
+ def closed?
64
+ @need_close
65
+ end
66
+
67
+ ##
68
+ # Closes the connection to the server.
69
+ def close
70
+ return if @need_close
71
+
72
+ Logging::KameleoonLogger.info('Streaming service is shutting down')
73
+ @need_close = true
74
+ return if @sse_thread.nil?
75
+
76
+ @sse_thread.kill
77
+ @sse_thread = nil
78
+ @sse_client&.call_close_handler
79
+ end
80
+
81
+ private
82
+
83
+ def create_sse_client
84
+ @sse_thread = Thread.new { run_sse_client } unless @need_close
85
+ end
86
+
87
+ def init_sse_client
88
+ sse_request = make_sse_request
89
+ @sse_client = SseClient.new(sse_request, method(:handle_message))
90
+ Logging::KameleoonLogger.info('Created SSE client')
91
+ end
92
+
93
+ def handle_message(message)
94
+ Logging::KameleoonLogger.debug("Got SSE event: #{message.event}")
95
+ @consecutive_disconnects = 0
96
+ return unless STREAMING_EVENT_TYPES.include?(message.event)
97
+
98
+ begin
99
+ update = DataFileUpdateMessage.new(JSON.parse(message.data))
100
+ raise ArgumentError, 'timestamp is missing' unless update.time_stamp.is_a?(Numeric)
101
+ rescue StandardError => e
102
+ Logging::KameleoonLogger.error("Received event from SSE server with wrong format: #{message.data}; #{e}")
103
+ return
104
+ end
105
+ @data_file_update_handler&.call(update)
106
+ rescue StandardError => e
107
+ # a handler failure must not drop the connection
108
+ Logging::KameleoonLogger.error("Data file update handler failed: #{e}")
109
+ end
110
+
111
+ def make_sse_request
112
+ open_handler = proc { Logging::KameleoonLogger.info("Established a new SSE connection with: '#{@url}'") }
113
+ close_handler = proc { Logging::KameleoonLogger.debug('SSE connection closed') }
114
+ unexpected_status_code_handler = proc { |resp| @failure_reason = "failed with status code #{resp.code}" }
115
+ if @sse_request_source.nil?
116
+ return SseRequest.new(@url, @headers, open_handler, close_handler, unexpected_status_code_handler)
117
+ end
118
+
119
+ @sse_request_source.call(@url, @headers, open_handler, close_handler, unexpected_status_code_handler)
120
+ end
121
+
122
+ # Every end of a connection is followed by a delayed reconnection, whether it is a routine close
123
+ # by the server (which recycles connections periodically) or a failure (error response, network
124
+ # error, stalled stream). Every received event resets the count of disconnects, and the server
125
+ # sends the connection open event on every connection, so a working stream keeps the count low.
126
+ # Once more than `MAX_RETRIES` connections in a row end without an event, the service gives up and
127
+ # reports it, so that the SDK can fall back to polling instead of retrying forever.
128
+ def run_sse_client
129
+ until @need_close
130
+ init_sse_client
131
+ @failure_reason = nil
132
+ begin
133
+ @sse_client.start
134
+ rescue StandardError => e
135
+ @failure_reason = "failed: #{e}"
136
+ end
137
+ break if @need_close
138
+
139
+ if (@consecutive_disconnects += 1) > MAX_RETRIES
140
+ give_up
141
+ break
142
+ end
143
+ log_reconnection
144
+ sleep(@reconnect_delay)
145
+ end
146
+ end
147
+
148
+ def log_reconnection
149
+ if @failure_reason
150
+ Logging::KameleoonLogger.error(
151
+ connection_message("#{@failure_reason}; reconnecting in #{@reconnect_delay} s")
152
+ )
153
+ else
154
+ Logging::KameleoonLogger.info(
155
+ connection_message("#{CLOSED_BY_SERVER}; reconnecting in #{@reconnect_delay} s")
156
+ )
157
+ end
158
+ end
159
+
160
+ def give_up
161
+ @need_close = true
162
+ Logging::KameleoonLogger.error(connection_message(
163
+ "#{@failure_reason || CLOSED_BY_SERVER}; streaming is unavailable after #{MAX_RETRIES + 1} " \
164
+ 'consecutive disconnects, switching to polling'
165
+ ))
166
+ @streaming_unavailable_handler&.call(self)
167
+ rescue StandardError => e
168
+ Logging::KameleoonLogger.error("Streaming unavailable handler failed: #{e}")
169
+ end
170
+
171
+ def connection_message(suffix)
172
+ "SSE connection: '#{@url}' #{suffix}"
173
+ end
174
+ end
175
+ end
176
+ end
177
+ end
@@ -46,8 +46,7 @@ module Kameleoon
46
46
  siteCode: @site_code
47
47
  }
48
48
  @access_token_url_params = UriHelper.encode_query(url_params)
49
- url_params[:bodyUa] = true
50
- @tracking_url_params = UriHelper.encode_query(url_params)
49
+ @tracking_url_params = @access_token_url_params
51
50
  update_domains(network_domain)
52
51
  end
53
52
 
@@ -63,17 +62,11 @@ module Kameleoon
63
62
  end
64
63
 
65
64
  def make_tracking_url
66
- params = {
67
- sdkName: SDK_NAME,
68
- sdkVersion: SDK_VERSION,
69
- siteCode: @site_code,
70
- bodyUa: true
71
- }
72
65
  format(DATA_API_URL_FORMAT, @data_api_domain, TRACKING_PATH, @tracking_url_params)
73
66
  end
74
67
 
75
68
  def make_visitor_data_get_url(visitor_code, filter, is_unique_identifier = false)
76
- params = { siteCode: @site_code }
69
+ params = { sdkName: SDK_NAME, sdkVersion: SDK_VERSION, siteCode: @site_code }
77
70
  params[is_unique_identifier ? :mappingValue : :visitorCode] = visitor_code
78
71
  params[:maxNumberPreviousVisits] = filter.previous_visit_amount
79
72
  params[:version] = 0
@@ -92,6 +85,8 @@ module Kameleoon
92
85
 
93
86
  def make_api_data_get_request_url(key)
94
87
  params = {
88
+ sdkName: SDK_NAME,
89
+ sdkVersion: SDK_VERSION,
95
90
  siteCode: @site_code,
96
91
  key: key
97
92
  }
@@ -7,6 +7,13 @@ module Kameleoon
7
7
  class SemVersion
8
8
  include Comparable
9
9
 
10
+ ZERO = '0'.ord
11
+ NINE = '9'.ord
12
+ DOT = '.'.ord
13
+ DASH = '-'.ord
14
+ PLUS = '+'.ord
15
+ private_constant :ZERO, :NINE, :DOT, :DASH, :PLUS
16
+
10
17
  attr_reader :major, :minor, :patch
11
18
 
12
19
  def initialize(major = 0, minor = 0, patch = 0)
@@ -31,23 +38,33 @@ module Kameleoon
31
38
  "#{@major}.#{@minor}".to_f
32
39
  end
33
40
 
41
+ # Parses `major[.minor[.patch]]`, ignoring a pre-release (-) or build (+) suffix.
42
+ # Returns nil if the string is invalid.
34
43
  def self.from_string(version_string)
35
44
  return nil unless version_string.is_a?(String)
36
45
 
37
46
  versions = [0, 0, 0]
38
- version_parts = version_string.split('.')
39
- return nil unless version_parts.length >= 1
40
-
41
- version_parts.each_with_index do |part, i|
42
- break if i >= 3
43
-
44
- begin
45
- versions[i] = Integer(part)
46
- rescue ArgumentError
47
- Logging::KameleoonLogger.error("Invalid version component, index: %s, value: '%s'", i, part)
48
- return nil
47
+ index = 0
48
+ has_digits = false
49
+ valid = true
50
+ # Single pass without splitting, stops at pre-release (-) or build (+) suffix
51
+ version_string.each_byte do |byte|
52
+ if byte >= ZERO && byte <= NINE
53
+ versions[index] = versions[index] * 10 + (byte - ZERO)
54
+ has_digits = true
55
+ elsif byte == DOT && has_digits && index < 2
56
+ index += 1
57
+ has_digits = false
58
+ else
59
+ valid = byte == DOT || byte == DASH || byte == PLUS
60
+ break
49
61
  end
50
62
  end
63
+ # Each parsed component must have at least one digit
64
+ unless valid && has_digits
65
+ Logging::KameleoonLogger.error("Invalid version component, index: %s, version: '%s'", index, version_string)
66
+ return nil
67
+ end
51
68
 
52
69
  SemVersion.new(versions[0], versions[1], versions[2])
53
70
  end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Kameleoon
4
- SDK_VERSION = '3.22.1'
4
+ SDK_VERSION = '3.23.0'
5
5
  SDK_NAME = 'RUBY'
6
6
  end
metadata CHANGED
@@ -1,43 +1,29 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kameleoon-client-ruby
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.22.1
4
+ version: 3.23.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Kameleoon
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-09-11 00:00:00.000000000 Z
11
+ date: 2026-11-19 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
- name: em-http-request
14
+ name: concurrent-ruby
15
15
  requirement: !ruby/object:Gem::Requirement
16
16
  requirements:
17
- - - ">="
18
- - !ruby/object:Gem::Version
19
- version: 1.1.5
20
- type: :runtime
21
- prerelease: false
22
- version_requirements: !ruby/object:Gem::Requirement
23
- requirements:
24
- - - ">="
25
- - !ruby/object:Gem::Version
26
- version: 1.1.5
27
- - !ruby/object:Gem::Dependency
28
- name: em-synchrony
29
- requirement: !ruby/object:Gem::Requirement
30
- requirements:
31
- - - ">="
17
+ - - "~>"
32
18
  - !ruby/object:Gem::Version
33
- version: 1.0.6
19
+ version: '1.2'
34
20
  type: :runtime
35
21
  prerelease: false
36
22
  version_requirements: !ruby/object:Gem::Requirement
37
23
  requirements:
38
- - - ">="
24
+ - - "~>"
39
25
  - !ruby/object:Gem::Version
40
- version: 1.0.6
26
+ version: '1.2'
41
27
  - !ruby/object:Gem::Dependency
42
28
  name: rufus-scheduler
43
29
  requirement: !ruby/object:Gem::Requirement
@@ -53,19 +39,19 @@ dependencies:
53
39
  - !ruby/object:Gem::Version
54
40
  version: '3.7'
55
41
  - !ruby/object:Gem::Dependency
56
- name: rest-client
42
+ name: net-http-persistent
57
43
  requirement: !ruby/object:Gem::Requirement
58
44
  requirements:
59
45
  - - "~>"
60
46
  - !ruby/object:Gem::Version
61
- version: '2.1'
47
+ version: '4.0'
62
48
  type: :runtime
63
49
  prerelease: false
64
50
  version_requirements: !ruby/object:Gem::Requirement
65
51
  requirements:
66
52
  - - "~>"
67
53
  - !ruby/object:Gem::Version
68
- version: '2.1'
54
+ version: '4.0'
69
55
  description: Kameleoon Client Ruby Software Development Kit
70
56
  email:
71
57
  - sdk@kameleoon.com
@@ -147,13 +133,13 @@ files:
147
133
  - lib/kameleoon/network/network_manager.rb
148
134
  - lib/kameleoon/network/request.rb
149
135
  - lib/kameleoon/network/response.rb
136
+ - lib/kameleoon/network/streaming/data_file_update_message.rb
137
+ - lib/kameleoon/network/streaming/sse_client.rb
138
+ - lib/kameleoon/network/streaming/sse_message.rb
139
+ - lib/kameleoon/network/streaming/sse_request.rb
140
+ - lib/kameleoon/network/streaming/streaming_service.rb
150
141
  - lib/kameleoon/network/uri_helper.rb
151
142
  - lib/kameleoon/network/url_provider.rb
152
- - lib/kameleoon/real_time/real_time_event.rb
153
- - lib/kameleoon/real_time/real_time_event_service.rb
154
- - lib/kameleoon/real_time/sse_client.rb
155
- - lib/kameleoon/real_time/sse_message.rb
156
- - lib/kameleoon/real_time/sse_request.rb
157
143
  - lib/kameleoon/sem_version.rb
158
144
  - lib/kameleoon/targeting/condition.rb
159
145
  - lib/kameleoon/targeting/condition_factory.rb
@@ -1,22 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- # Kameleoon Real Time Event
4
-
5
- module Kameleoon
6
- module RealTime
7
- ##
8
- # RealTimeEvent contains information about timestamp when configuration was updated.
9
- # Timestamp parameter is used to fetch the latest configuration.
10
- class RealTimeEvent
11
- attr_reader :time_stamp
12
-
13
- ##
14
- # Parametrized initializer. Gets the new time stamp from a JSON message.
15
- #
16
- # @param event_dict [Hash] Hash of SSE message data.
17
- def initialize(event_dict)
18
- @time_stamp = event_dict['ts']
19
- end
20
- end
21
- end
22
- end