kameleoon-client-ruby 3.22.2 → 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.
- checksums.yaml +4 -4
- data/lib/kameleoon/configuration/settings.rb +28 -4
- data/lib/kameleoon/data/user_agent.rb +1 -1
- data/lib/kameleoon/kameleoon_client.rb +122 -50
- data/lib/kameleoon/network/content_type.rb +0 -1
- data/lib/kameleoon/network/network_manager.rb +1 -1
- data/lib/kameleoon/network/streaming/data_file_update_message.rb +25 -0
- data/lib/kameleoon/network/streaming/sse_client.rb +113 -0
- data/lib/kameleoon/network/streaming/sse_message.rb +25 -0
- data/lib/kameleoon/network/streaming/sse_request.rb +78 -0
- data/lib/kameleoon/network/streaming/streaming_service.rb +177 -0
- data/lib/kameleoon/network/url_provider.rb +4 -9
- data/lib/kameleoon/sem_version.rb +28 -11
- data/lib/kameleoon/version.rb +1 -1
- metadata +7 -7
- data/lib/kameleoon/real_time/real_time_event.rb +0 -22
- data/lib/kameleoon/real_time/real_time_event_service.rb +0 -106
- data/lib/kameleoon/real_time/sse_client.rb +0 -113
- data/lib/kameleoon/real_time/sse_message.rb +0 -23
- data/lib/kameleoon/real_time/sse_request.rb +0 -62
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 5e99837e0d5fa905c2635ec24e42867b55d5fba98a68283b79b59ffb51d95312
|
|
4
|
+
data.tar.gz: e0375cd6f8aca052dbb50cc839f41ce853d34bf48b0ee52ae92b841f24b5dc26
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: a432523e9510c65671d627f55250169b550feea3026004e908191828baccb6e75c43b345701041894aeaa180e2ff700dfe2b693e64e1236091620a15f5c4d572
|
|
7
|
+
data.tar.gz: 9da0e374af6713aa7e15ae4e2e2e1f4726bcc7322a7a764143f05e0e7c7bf8402c60fc8ef924b360532b738a4a66ff12560ebc023813d29f9c0694d5e0ae8918
|
|
@@ -8,22 +8,25 @@ module Kameleoon
|
|
|
8
8
|
# KameleoonConfigurationSettings is used for saving setting's parameters, e.g
|
|
9
9
|
# state of real time update for site code and etc
|
|
10
10
|
class Settings
|
|
11
|
-
|
|
11
|
+
# `true` when configuration updates are to be received as streaming events rather than polled.
|
|
12
|
+
attr_reader :streaming_mode
|
|
12
13
|
attr_reader :is_consent_required, :blocking_behaviour_if_consent_not_given, :data_api_domain
|
|
13
14
|
|
|
15
|
+
alias streaming_mode? streaming_mode
|
|
16
|
+
|
|
14
17
|
def to_s
|
|
15
|
-
"Settings{
|
|
18
|
+
"Settings{streaming_mode:#{@streaming_mode},is_consent_required:#{@is_consent_required}," \
|
|
16
19
|
"data_api_domain:#{@data_api_domain}}"
|
|
17
20
|
end
|
|
18
21
|
|
|
19
22
|
def initialize(configuration = nil)
|
|
20
23
|
if configuration.nil?
|
|
21
|
-
@
|
|
24
|
+
@streaming_mode = false
|
|
22
25
|
@is_consent_required = false
|
|
23
26
|
@blocking_behaviour_if_consent_not_given = ConsentBlockingBehaviour::PARTIALLY_BLOCKED
|
|
24
27
|
@data_api_domain = nil
|
|
25
28
|
else
|
|
26
|
-
@
|
|
29
|
+
@streaming_mode = ConfigUpdateMode.streaming?(configuration['configUpdateMode'])
|
|
27
30
|
@is_consent_required = configuration['consentType'] == 'REQUIRED'
|
|
28
31
|
@blocking_behaviour_if_consent_not_given =
|
|
29
32
|
ConsentBlockingBehaviour.from_str(configuration['consentOptOutBehavior'])
|
|
@@ -32,6 +35,27 @@ module Kameleoon
|
|
|
32
35
|
end
|
|
33
36
|
end
|
|
34
37
|
|
|
38
|
+
# ConfigUpdateMode is the way the SDK receives configuration updates, as set in the configuration.
|
|
39
|
+
module ConfigUpdateMode
|
|
40
|
+
POLLING = 'POLLING'
|
|
41
|
+
STREAMING = 'STREAMING'
|
|
42
|
+
# Streaming for server-side SDKs only, this one included
|
|
43
|
+
STREAMING_SERVER_ONLY = 'STREAMING_SERVER_ONLY'
|
|
44
|
+
|
|
45
|
+
def self.streaming?(str)
|
|
46
|
+
mode = str.is_a?(String) ? str.upcase : nil
|
|
47
|
+
case mode
|
|
48
|
+
when STREAMING, STREAMING_SERVER_ONLY
|
|
49
|
+
true
|
|
50
|
+
when POLLING
|
|
51
|
+
false
|
|
52
|
+
else
|
|
53
|
+
Logging::KameleoonLogger.warning("Unexpected ConfigUpdateMode '%s'", str)
|
|
54
|
+
false
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
|
|
35
59
|
# ConsentBlockingBehaviour
|
|
36
60
|
module ConsentBlockingBehaviour
|
|
37
61
|
PARTIALLY_BLOCKED = 0
|
|
@@ -29,7 +29,7 @@ require 'kameleoon/network/activity_event'
|
|
|
29
29
|
require 'kameleoon/network/network_manager'
|
|
30
30
|
require 'kameleoon/network/url_provider'
|
|
31
31
|
require 'kameleoon/network/cookie/cookie_manager'
|
|
32
|
-
require 'kameleoon/
|
|
32
|
+
require 'kameleoon/network/streaming/streaming_service'
|
|
33
33
|
require 'kameleoon/targeting/models'
|
|
34
34
|
require 'kameleoon/targeting/targeting_manager'
|
|
35
35
|
require 'kameleoon/types/variable'
|
|
@@ -65,9 +65,11 @@ module Kameleoon
|
|
|
65
65
|
@site_code = site_code
|
|
66
66
|
@config = config
|
|
67
67
|
@disposed = false
|
|
68
|
-
@
|
|
68
|
+
@streaming_service = nil
|
|
69
69
|
@update_configuration_handler = nil
|
|
70
70
|
@fetch_configuration_update_job = nil
|
|
71
|
+
@configuration_update_mutex = Mutex.new
|
|
72
|
+
@apply_configuration_mutex = Mutex.new
|
|
71
73
|
data_file = Configuration::DataFile.new(config.environment, nil)
|
|
72
74
|
@data_manager = Managers::Data::DataManager.new(data_file)
|
|
73
75
|
@visitor_manager = Kameleoon::DataManager::VisitorManager.new(
|
|
@@ -886,27 +888,34 @@ module Kameleoon
|
|
|
886
888
|
private
|
|
887
889
|
|
|
888
890
|
HYBRID_EXPIRATION_TIME = 5
|
|
891
|
+
# Delay before the first poll after a fallback from the streaming mode, so that the streaming is
|
|
892
|
+
# retried soon (each successful poll switches back to it when it is enabled), unless the polls are
|
|
893
|
+
# even more frequent.
|
|
894
|
+
STREAMING_RETRY_DELAY_SECONDS = 60
|
|
889
895
|
|
|
890
|
-
# Fetches the configuration in a background thread; used for the initial fetch
|
|
891
|
-
# the
|
|
892
|
-
# the client readiness, and a failed fetch always falls back to the polling mode:
|
|
893
|
-
# a streaming event means the configuration has changed, so staying in the
|
|
894
|
-
# streaming mode would leave the SDK serving the outdated configuration until
|
|
895
|
-
# the next event arrives. The server-provided settings are not mutated, so a
|
|
896
|
-
# later successful fetch switches back to streaming when requested.
|
|
896
|
+
# Fetches the configuration in a background thread; used for the initial fetch and
|
|
897
|
+
# the streaming events, while the polling job fetches in its own thread.
|
|
897
898
|
def fetch_configuration_job(time_stamp = nil)
|
|
898
|
-
Thread.new
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
899
|
+
Thread.new { fetch_configuration_sync(time_stamp) }
|
|
900
|
+
end
|
|
901
|
+
|
|
902
|
+
# Fetches the configuration and applies the outcome. The fetch outcome settles the
|
|
903
|
+
# client readiness, and a failed fetch always falls back to the polling mode: a
|
|
904
|
+
# streaming event means the configuration has changed, so staying in the streaming
|
|
905
|
+
# mode would leave the SDK serving the outdated configuration until the next event
|
|
906
|
+
# arrives. The server-provided settings are not mutated, so a later successful fetch
|
|
907
|
+
# switches back to streaming when requested.
|
|
908
|
+
def fetch_configuration_sync(time_stamp = nil)
|
|
909
|
+
cause = nil
|
|
910
|
+
ok = false
|
|
911
|
+
begin
|
|
912
|
+
ok = obtain_configuration(time_stamp)
|
|
913
|
+
rescue StandardError => e
|
|
914
|
+
cause = e
|
|
915
|
+
Logging::KameleoonLogger.error('Error occurred during configuration fetching: %s', e)
|
|
909
916
|
end
|
|
917
|
+
settle_readiness(ok, cause)
|
|
918
|
+
manage_configuration_update(ok && @data_manager.data_file.settings.streaming_mode?)
|
|
910
919
|
end
|
|
911
920
|
|
|
912
921
|
# A successful fetch marks the SDK ready, a failed one reports the failure so
|
|
@@ -921,13 +930,18 @@ module Kameleoon
|
|
|
921
930
|
end
|
|
922
931
|
end
|
|
923
932
|
|
|
924
|
-
|
|
933
|
+
# @param first_in [Numeric | NilClass] Delay in seconds before the first poll; the refresh interval by
|
|
934
|
+
# default. Ignored while the polling is already scheduled.
|
|
935
|
+
def start_polling_datafile_update(first_in = nil)
|
|
925
936
|
return unless @fetch_configuration_update_job.nil?
|
|
926
937
|
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
938
|
+
# The fetch runs in the job's thread, so `overlap: false` skips the ticks which come while a slow
|
|
939
|
+
# fetch is still in progress instead of piling up fetches
|
|
940
|
+
@fetch_configuration_update_job =
|
|
941
|
+
@scheduler.schedule_every(@config.refresh_interval_second, first_in: first_in, overlap: false) do
|
|
942
|
+
Logging::KameleoonLogger.info('Scheduled job to fetch configuration is started.')
|
|
943
|
+
fetch_configuration_sync
|
|
944
|
+
end
|
|
931
945
|
end
|
|
932
946
|
|
|
933
947
|
def stop_polling_datafile_update
|
|
@@ -938,34 +952,76 @@ module Kameleoon
|
|
|
938
952
|
Logging::KameleoonLogger.info('Scheduled job to fetch configuration is stopped.')
|
|
939
953
|
end
|
|
940
954
|
|
|
941
|
-
|
|
942
|
-
|
|
955
|
+
# Returns whether the service runs. A service which gave up reconnecting is replaced right away; its
|
|
956
|
+
# pending fallback notification is then ignored, see `on_streaming_unavailable`.
|
|
957
|
+
def start_streaming_service
|
|
958
|
+
return true unless @streaming_service.nil? || @streaming_service.closed?
|
|
943
959
|
|
|
944
960
|
url = @network_manager.url_provider.make_real_time_url
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
961
|
+
@streaming_service = Kameleoon::Network::Streaming::StreamingService.new(
|
|
962
|
+
url, method(:on_data_file_update_message), streaming_unavailable_handler: method(:on_streaming_unavailable)
|
|
963
|
+
)
|
|
964
|
+
true
|
|
965
|
+
rescue StandardError => e # e.g. `ThreadError` when no thread can be created
|
|
966
|
+
Logging::KameleoonLogger.error('Failed to start the streaming service: %s; switching to polling', e)
|
|
967
|
+
false
|
|
968
|
+
end
|
|
969
|
+
|
|
970
|
+
# Every event (a configuration update, or the connection open event sent on every (re)connection)
|
|
971
|
+
# carries the timestamp of the current configuration, so the SDK fetches it only when it is newer
|
|
972
|
+
# than the one it holds.
|
|
973
|
+
def on_data_file_update_message(message)
|
|
974
|
+
time_stamp = message.time_stamp
|
|
975
|
+
date_modified = @data_manager.data_file.date_modified
|
|
976
|
+
if time_stamp <= date_modified
|
|
977
|
+
Logging::KameleoonLogger.debug(
|
|
978
|
+
'Configuration is up to date (ts: %s, dateModified: %s), skipping update', time_stamp, date_modified
|
|
979
|
+
)
|
|
980
|
+
return
|
|
981
|
+
end
|
|
982
|
+
fetch_configuration_job(time_stamp)
|
|
948
983
|
end
|
|
949
984
|
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
985
|
+
# Called by the service which gave up reconnecting. A fetch completing meanwhile may have replaced
|
|
986
|
+
# the service already, in which case there is nothing to fall back from.
|
|
987
|
+
def on_streaming_unavailable(service)
|
|
988
|
+
@configuration_update_mutex.synchronize do
|
|
989
|
+
return if @disposed || !service.equal?(@streaming_service)
|
|
990
|
+
|
|
991
|
+
stop_streaming_service
|
|
992
|
+
start_polling_datafile_update(streaming_retry_delay)
|
|
993
|
+
end
|
|
994
|
+
end
|
|
995
|
+
|
|
996
|
+
def streaming_retry_delay
|
|
997
|
+
[STREAMING_RETRY_DELAY_SECONDS, @config.refresh_interval_second].min
|
|
998
|
+
end
|
|
999
|
+
|
|
1000
|
+
def stop_streaming_service
|
|
1001
|
+
@streaming_service&.close
|
|
1002
|
+
@streaming_service = nil
|
|
953
1003
|
end
|
|
954
1004
|
|
|
955
1005
|
# A disposed client must not (re)start the update services: a fetch which was
|
|
956
1006
|
# in flight when `dispose` ran would otherwise resurrect them. `@disposed` is
|
|
957
1007
|
# set before `dispose` stops the services, so a fetch completing after that
|
|
958
|
-
# point can only stop things.
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
1008
|
+
# point can only stop things. The polling is stopped only once the streaming
|
|
1009
|
+
# runs, so that a failed start never leaves the SDK without updates. Whenever
|
|
1010
|
+
# the current settings enable streaming but it is not running (a failed fetch,
|
|
1011
|
+
# a failed start), the first poll comes soon, so that streaming is retried
|
|
1012
|
+
# without waiting a full refresh interval.
|
|
1013
|
+
def manage_configuration_update(streaming_mode)
|
|
1014
|
+
@configuration_update_mutex.synchronize do
|
|
1015
|
+
if @disposed
|
|
1016
|
+
stop_polling_datafile_update
|
|
1017
|
+
stop_streaming_service
|
|
1018
|
+
elsif streaming_mode && start_streaming_service
|
|
1019
|
+
stop_polling_datafile_update
|
|
1020
|
+
else
|
|
1021
|
+
stop_streaming_service
|
|
1022
|
+
first_in = @data_manager.data_file.settings.streaming_mode? ? streaming_retry_delay : nil
|
|
1023
|
+
start_polling_datafile_update(first_in)
|
|
1024
|
+
end
|
|
969
1025
|
end
|
|
970
1026
|
end
|
|
971
1027
|
|
|
@@ -1000,13 +1056,27 @@ module Kameleoon
|
|
|
1000
1056
|
true
|
|
1001
1057
|
end
|
|
1002
1058
|
|
|
1059
|
+
# The data file is only ever replaced by one at least as new: fetches may run concurrently (a
|
|
1060
|
+
# streaming event can arrive while another fetch is in flight) and finish out of order, and a stale
|
|
1061
|
+
# reply must not roll the configuration back. The comparison and the replacement are atomic, and
|
|
1062
|
+
# the update event fires under the same lock, so handlers see the data files in the applied order.
|
|
1003
1063
|
def apply_new_configuration(data_file, source)
|
|
1004
1064
|
Logging::KameleoonLogger.debug('CALL: KameleoonClient.apply_new_configuration(data_file: %s, source: %s)',
|
|
1005
1065
|
data_file, source)
|
|
1006
|
-
@
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1066
|
+
@apply_configuration_mutex.synchronize do
|
|
1067
|
+
current_date_modified = @data_manager.data_file.date_modified
|
|
1068
|
+
if data_file.date_modified < current_date_modified
|
|
1069
|
+
Logging::KameleoonLogger.info(
|
|
1070
|
+
'Fetched configuration (dateModified: %s) is older than the current one (dateModified: %s), skipping',
|
|
1071
|
+
data_file.date_modified, current_date_modified
|
|
1072
|
+
)
|
|
1073
|
+
else
|
|
1074
|
+
@data_manager.data_file = data_file
|
|
1075
|
+
@network_manager.url_provider.apply_data_api_domain(data_file.settings.data_api_domain)
|
|
1076
|
+
@event_manager.fire_data_file_update(Events::DataFileUpdateEvent.new(source, data_file.date_modified))
|
|
1077
|
+
call_deprecated_update_handler if source == Events::DataFileUpdateEvent::Source::STREAMING
|
|
1078
|
+
end
|
|
1079
|
+
end
|
|
1010
1080
|
Logging::KameleoonLogger.debug('RETURN: KameleoonClient.apply_new_configuration(data_file: %s, source: %s)',
|
|
1011
1081
|
data_file, source)
|
|
1012
1082
|
end
|
|
@@ -1028,8 +1098,10 @@ module Kameleoon
|
|
|
1028
1098
|
def dispose(_object_id = nil)
|
|
1029
1099
|
Logging::KameleoonLogger.debug('CALL: KameleoonClient.dispose')
|
|
1030
1100
|
@disposed = true
|
|
1031
|
-
|
|
1032
|
-
|
|
1101
|
+
@configuration_update_mutex.synchronize do
|
|
1102
|
+
stop_polling_datafile_update
|
|
1103
|
+
stop_streaming_service
|
|
1104
|
+
end
|
|
1033
1105
|
@visitor_manager.stop
|
|
1034
1106
|
@tracking_manager.stop
|
|
1035
1107
|
@scheduler.shutdown
|
|
@@ -69,7 +69,7 @@ module Kameleoon
|
|
|
69
69
|
|
|
70
70
|
url = @url_provider.make_tracking_url
|
|
71
71
|
timeout = ensure_timeout(timeout)
|
|
72
|
-
request = Request.new(Method::POST, url, ContentType::
|
|
72
|
+
request = Request.new(Method::POST, url, ContentType::TEXT, timeout, data: lines)
|
|
73
73
|
unwrap_response(*make_call(Events::RequestType::TRACKING, request, true,
|
|
74
74
|
TRACKING_CALL_ATTEMPT_NUMBER - 1, TRACKING_CALL_RETRY_DELAY))
|
|
75
75
|
end
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Kameleoon Data File Update Message
|
|
4
|
+
|
|
5
|
+
module Kameleoon
|
|
6
|
+
module Network
|
|
7
|
+
module Streaming
|
|
8
|
+
##
|
|
9
|
+
# DataFileUpdateMessage contains information about timestamp when configuration was updated.
|
|
10
|
+
# Timestamp parameter is used to fetch the latest configuration.
|
|
11
|
+
class DataFileUpdateMessage
|
|
12
|
+
attr_reader :time_stamp
|
|
13
|
+
|
|
14
|
+
##
|
|
15
|
+
# Parametrized initializer. Gets the new time stamp from a JSON message.
|
|
16
|
+
#
|
|
17
|
+
# @param event_dict [Hash] Hash of SSE message data.
|
|
18
|
+
def initialize(event_dict)
|
|
19
|
+
# Both hold milliseconds; `ts` is only read while the server still sends events without `tsMs`
|
|
20
|
+
@time_stamp = event_dict['tsMs'] || event_dict['ts']
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
@@ -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
|
-
|
|
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
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
data/lib/kameleoon/version.rb
CHANGED
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: kameleoon-client-ruby
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 3.
|
|
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-
|
|
11
|
+
date: 2026-11-19 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: concurrent-ruby
|
|
@@ -133,13 +133,13 @@ files:
|
|
|
133
133
|
- lib/kameleoon/network/network_manager.rb
|
|
134
134
|
- lib/kameleoon/network/request.rb
|
|
135
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
|
|
136
141
|
- lib/kameleoon/network/uri_helper.rb
|
|
137
142
|
- lib/kameleoon/network/url_provider.rb
|
|
138
|
-
- lib/kameleoon/real_time/real_time_event.rb
|
|
139
|
-
- lib/kameleoon/real_time/real_time_event_service.rb
|
|
140
|
-
- lib/kameleoon/real_time/sse_client.rb
|
|
141
|
-
- lib/kameleoon/real_time/sse_message.rb
|
|
142
|
-
- lib/kameleoon/real_time/sse_request.rb
|
|
143
143
|
- lib/kameleoon/sem_version.rb
|
|
144
144
|
- lib/kameleoon/targeting/condition.rb
|
|
145
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
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
# Kameleoon Real Time Event Service
|
|
4
|
-
|
|
5
|
-
require 'json'
|
|
6
|
-
require 'kameleoon/logging/kameleoon_logger'
|
|
7
|
-
require 'kameleoon/real_time/real_time_event'
|
|
8
|
-
require 'kameleoon/real_time/sse_request'
|
|
9
|
-
require 'kameleoon/real_time/sse_client'
|
|
10
|
-
|
|
11
|
-
module Kameleoon
|
|
12
|
-
module RealTime
|
|
13
|
-
DATA_FILE_UPDATE_EVENT = 'configuration-update-event'
|
|
14
|
-
|
|
15
|
-
##
|
|
16
|
-
# RealTimeEventService is used for fetching updates of configuration
|
|
17
|
-
# (experiments and feature flags) in real time.
|
|
18
|
-
class RealTimeEventService
|
|
19
|
-
# Delay before re-establishing a failed SSE connection, so a persistent
|
|
20
|
-
# failure does not turn into a hot reconnect loop.
|
|
21
|
-
RECONNECT_DELAY_SECONDS = 3
|
|
22
|
-
|
|
23
|
-
##
|
|
24
|
-
# Parametrized initializer.
|
|
25
|
-
#
|
|
26
|
-
# @param url [String]
|
|
27
|
-
# @param update_handler [Callable[Kameleoon::RealTime::RealTimeEvent] | NilClass] Handler which
|
|
28
|
-
# is synchronously called for gotten RealTimeEvent objects.
|
|
29
|
-
# @param reconnect_delay [Numeric] Delay in seconds before a reconnect attempt.
|
|
30
|
-
def initialize(url, update_handler, sse_request_source = nil, reconnect_delay: RECONNECT_DELAY_SECONDS)
|
|
31
|
-
@url = url
|
|
32
|
-
@update_handler = update_handler
|
|
33
|
-
@need_close = false
|
|
34
|
-
@headers = {
|
|
35
|
-
'Accept': 'text/event-stream',
|
|
36
|
-
'Cache-Control': 'no-cache',
|
|
37
|
-
'Connection': 'Keep-Alive'
|
|
38
|
-
}
|
|
39
|
-
@sse_request_source = sse_request_source
|
|
40
|
-
@reconnect_delay = reconnect_delay
|
|
41
|
-
@sse_thread = nil
|
|
42
|
-
@sse_client = nil
|
|
43
|
-
create_sse_client
|
|
44
|
-
end
|
|
45
|
-
|
|
46
|
-
##
|
|
47
|
-
# Closes the connection to the server.
|
|
48
|
-
def close
|
|
49
|
-
return if @need_close
|
|
50
|
-
|
|
51
|
-
Logging::KameleoonLogger.info('Real-time event service is shutting down')
|
|
52
|
-
@need_close = true
|
|
53
|
-
return if @sse_thread.nil?
|
|
54
|
-
|
|
55
|
-
@sse_thread.kill
|
|
56
|
-
@sse_thread = nil
|
|
57
|
-
@sse_client&.call_close_handler
|
|
58
|
-
end
|
|
59
|
-
|
|
60
|
-
private
|
|
61
|
-
|
|
62
|
-
def create_sse_client
|
|
63
|
-
@sse_thread = Thread.new { run_sse_client } unless @need_close
|
|
64
|
-
end
|
|
65
|
-
|
|
66
|
-
def init_sse_client
|
|
67
|
-
message_handler = proc do |message|
|
|
68
|
-
Logging::KameleoonLogger.debug("Got SSE event: #{message.event}")
|
|
69
|
-
if message.event == DATA_FILE_UPDATE_EVENT
|
|
70
|
-
event_dict = JSON.parse(message.data)
|
|
71
|
-
@update_handler&.call(RealTimeEvent.new(event_dict))
|
|
72
|
-
end
|
|
73
|
-
end
|
|
74
|
-
sse_request = make_sse_request
|
|
75
|
-
@sse_client = SseClient.new(sse_request, message_handler)
|
|
76
|
-
Logging::KameleoonLogger.info('Created SSE client')
|
|
77
|
-
end
|
|
78
|
-
|
|
79
|
-
def make_sse_request
|
|
80
|
-
open_handler = proc { Logging::KameleoonLogger.info('SSE connection open') }
|
|
81
|
-
close_handler = proc { Logging::KameleoonLogger.info('SSE connection closed') }
|
|
82
|
-
unexpected_status_code_handler =
|
|
83
|
-
proc { |resp| Logging::KameleoonLogger.error("Unexpected status code of SSE response: #{resp.code}") }
|
|
84
|
-
if @sse_request_source.nil?
|
|
85
|
-
return SseRequest.new(@url, @headers, open_handler, close_handler, unexpected_status_code_handler)
|
|
86
|
-
end
|
|
87
|
-
|
|
88
|
-
@sse_request_source.call(@url, @headers, open_handler, close_handler, unexpected_status_code_handler)
|
|
89
|
-
end
|
|
90
|
-
|
|
91
|
-
def run_sse_client
|
|
92
|
-
until @need_close
|
|
93
|
-
init_sse_client
|
|
94
|
-
begin
|
|
95
|
-
@sse_client.start
|
|
96
|
-
rescue StandardError => e
|
|
97
|
-
Logging::KameleoonLogger.error("Error occurred within SSE client: #{e}")
|
|
98
|
-
end
|
|
99
|
-
# The delay is applied to every re-establishment (a failed connection and
|
|
100
|
-
# a dropped stream alike), so a persistent failure cannot produce a hot loop.
|
|
101
|
-
sleep(@reconnect_delay) unless @need_close
|
|
102
|
-
end
|
|
103
|
-
end
|
|
104
|
-
end
|
|
105
|
-
end
|
|
106
|
-
end
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
require 'kameleoon/real_time/sse_message'
|
|
4
|
-
|
|
5
|
-
# TODO: Fix hanging (https://project.kameleoon.net/issues/26520)
|
|
6
|
-
|
|
7
|
-
module Kameleoon
|
|
8
|
-
module RealTime
|
|
9
|
-
##
|
|
10
|
-
# SseClient is used to interpret SSE event stream.
|
|
11
|
-
class SseClient
|
|
12
|
-
##
|
|
13
|
-
# Parametrized initializer.
|
|
14
|
-
#
|
|
15
|
-
# @param sse_request [Kameleoon::RealTime::SseRequest] Used to access SSE event stream.
|
|
16
|
-
# @param message_handler [Callable[Kameleoon::RealTime::SseMessage] | NilClass] Callable object which
|
|
17
|
-
# is synchronously called for received SSE messages.
|
|
18
|
-
def initialize(sse_request, message_handler)
|
|
19
|
-
@sse_request = sse_request
|
|
20
|
-
@message_handler = message_handler
|
|
21
|
-
|
|
22
|
-
@cr_prev = nil
|
|
23
|
-
@buffer = nil
|
|
24
|
-
@data_buffer = nil
|
|
25
|
-
@event = nil
|
|
26
|
-
@id = nil
|
|
27
|
-
@reconnection_time = nil
|
|
28
|
-
|
|
29
|
-
@sse_request.resp_char_handler = method(:process_char)
|
|
30
|
-
end
|
|
31
|
-
|
|
32
|
-
##
|
|
33
|
-
# Starts SSE connection and stay in the loop until close.
|
|
34
|
-
def start
|
|
35
|
-
@cr_prev = false
|
|
36
|
-
@data_buffer = []
|
|
37
|
-
@event = nil
|
|
38
|
-
@id = nil
|
|
39
|
-
@buffer = []
|
|
40
|
-
@sse_request.start
|
|
41
|
-
end
|
|
42
|
-
|
|
43
|
-
##
|
|
44
|
-
# Calls @sse_request@close_handler if it is not nil.
|
|
45
|
-
def call_close_handler
|
|
46
|
-
@sse_request.call_close_handler
|
|
47
|
-
end
|
|
48
|
-
|
|
49
|
-
private
|
|
50
|
-
|
|
51
|
-
def process_char(ch)
|
|
52
|
-
if @cr_prev && (ch == "\n")
|
|
53
|
-
@cr_prev = false
|
|
54
|
-
return
|
|
55
|
-
end
|
|
56
|
-
@cr_prev = ch == "\r"
|
|
57
|
-
if @cr_prev || (ch == "\n")
|
|
58
|
-
line = @buffer.join
|
|
59
|
-
@buffer.clear
|
|
60
|
-
if line.empty?
|
|
61
|
-
dispatch_event
|
|
62
|
-
else
|
|
63
|
-
handle_line(line)
|
|
64
|
-
end
|
|
65
|
-
return
|
|
66
|
-
end
|
|
67
|
-
@buffer << ch
|
|
68
|
-
end
|
|
69
|
-
|
|
70
|
-
def handle_line(line)
|
|
71
|
-
field, value = parse_line(line)
|
|
72
|
-
return if field.nil?
|
|
73
|
-
|
|
74
|
-
case field
|
|
75
|
-
when 'event'
|
|
76
|
-
@event = value
|
|
77
|
-
when 'data'
|
|
78
|
-
@data_buffer << value
|
|
79
|
-
when 'id'
|
|
80
|
-
@id = value
|
|
81
|
-
when 'retry'
|
|
82
|
-
@reconnection_time = value.to_i # This does not affect anything
|
|
83
|
-
end
|
|
84
|
-
end
|
|
85
|
-
|
|
86
|
-
def parse_line(line)
|
|
87
|
-
colon_index = line.index(':')
|
|
88
|
-
return line, nil if colon_index.nil?
|
|
89
|
-
return nil, nil if colon_index.zero?
|
|
90
|
-
|
|
91
|
-
field = line[0, colon_index]
|
|
92
|
-
return field, '' if colon_index + 1 == line.length
|
|
93
|
-
|
|
94
|
-
value = if line[colon_index + 1] == ' '
|
|
95
|
-
line[colon_index + 2..]
|
|
96
|
-
else
|
|
97
|
-
line[colon_index + 1..]
|
|
98
|
-
end
|
|
99
|
-
[field, value]
|
|
100
|
-
end
|
|
101
|
-
|
|
102
|
-
def dispatch_event
|
|
103
|
-
return unless !@event.nil? || !@data_buffer.empty? # Ignoring empty events
|
|
104
|
-
|
|
105
|
-
data = @data_buffer.join("\n")
|
|
106
|
-
message = SseMessage.new(@event, @id, data)
|
|
107
|
-
@event = nil
|
|
108
|
-
@data_buffer.clear
|
|
109
|
-
@message_handler&.call(message)
|
|
110
|
-
end
|
|
111
|
-
end
|
|
112
|
-
end
|
|
113
|
-
end
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
module Kameleoon
|
|
4
|
-
module RealTime
|
|
5
|
-
##
|
|
6
|
-
# SseMessage is a container for a received SSE message.
|
|
7
|
-
class SseMessage
|
|
8
|
-
attr_reader :event, :id, :data
|
|
9
|
-
|
|
10
|
-
##
|
|
11
|
-
# Parametrized initializer.
|
|
12
|
-
#
|
|
13
|
-
# @param event [String]
|
|
14
|
-
# @param id [String]
|
|
15
|
-
# @param data [String]
|
|
16
|
-
def initialize(event, id, data)
|
|
17
|
-
@event = event
|
|
18
|
-
@id = id
|
|
19
|
-
@data = data
|
|
20
|
-
end
|
|
21
|
-
end
|
|
22
|
-
end
|
|
23
|
-
end
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
require 'net/http'
|
|
4
|
-
|
|
5
|
-
module Kameleoon
|
|
6
|
-
module RealTime
|
|
7
|
-
##
|
|
8
|
-
# SseRequest is used keep SSE connection and read from its stream.
|
|
9
|
-
class SseRequest
|
|
10
|
-
attr_writer :resp_char_handler
|
|
11
|
-
|
|
12
|
-
##
|
|
13
|
-
# Parametrized initializer.
|
|
14
|
-
#
|
|
15
|
-
# @param url [String]
|
|
16
|
-
# @param headers [Hash]
|
|
17
|
-
# @param open_handler [Callable | NilClass] Handler which is synchronously called when SSE connection is open.
|
|
18
|
-
# @param close_handler [Callable | NilClass] Handler which is synchronously called when SSE connection is closed.
|
|
19
|
-
# @param unexpected_status_code_handler [Callable[Net::HTTPResponse] | NilClass] Handler whick
|
|
20
|
-
# is synchronously called for responses with not 200 status code.
|
|
21
|
-
def initialize(url, headers, open_handler, close_handler, unexpected_status_code_handler)
|
|
22
|
-
@url = url
|
|
23
|
-
@headers = headers
|
|
24
|
-
@open_handler = open_handler
|
|
25
|
-
@close_handler = close_handler
|
|
26
|
-
@unexpected_status_code_handler = unexpected_status_code_handler
|
|
27
|
-
|
|
28
|
-
@resp_char_handler = nil
|
|
29
|
-
end
|
|
30
|
-
|
|
31
|
-
##
|
|
32
|
-
# Starts SSE connection and stay in the loop until close.
|
|
33
|
-
def start
|
|
34
|
-
uri = URI(@url)
|
|
35
|
-
# No read timeout: the stream is expected to stay silent between events.
|
|
36
|
-
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', read_timeout: nil) do |http|
|
|
37
|
-
http.request(Net::HTTP::Get.new(uri, @headers)) { |resp| handle_resp(resp) }
|
|
38
|
-
end
|
|
39
|
-
end
|
|
40
|
-
|
|
41
|
-
##
|
|
42
|
-
# Calls @close_handler if it is not nil.
|
|
43
|
-
def call_close_handler
|
|
44
|
-
@close_handler&.call
|
|
45
|
-
end
|
|
46
|
-
|
|
47
|
-
private
|
|
48
|
-
|
|
49
|
-
def handle_resp(resp)
|
|
50
|
-
@open_handler&.call
|
|
51
|
-
if resp.code == '200'
|
|
52
|
-
resp.read_body do |chunk|
|
|
53
|
-
chunk.each_char { |ch| @resp_char_handler&.call(ch) }
|
|
54
|
-
end
|
|
55
|
-
else
|
|
56
|
-
@unexpected_status_code_handler&.call(resp)
|
|
57
|
-
end
|
|
58
|
-
call_close_handler
|
|
59
|
-
end
|
|
60
|
-
end
|
|
61
|
-
end
|
|
62
|
-
end
|