launchdarkly-server-sdk 8.11.3-java → 8.12.0-java

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,401 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ldclient-rb/interfaces"
4
+ require "ldclient-rb/interfaces/data_system"
5
+ require "ldclient-rb/impl/data_system"
6
+ require "ldclient-rb/impl/data_system/protocolv2"
7
+ require "ldclient-rb/impl/data_system/polling" # For shared constants
8
+ require "ldclient-rb/impl/data_system/data_source_builder_common"
9
+ require "ldclient-rb/impl/util"
10
+ require "concurrent"
11
+ require "json"
12
+ require "uri"
13
+ require "ld-eventsource"
14
+
15
+ module LaunchDarkly
16
+ module Impl
17
+ module DataSystem
18
+ FDV2_STREAMING_ENDPOINT = "/sdk/stream"
19
+
20
+ # Allows for up to 5 minutes to elapse without any data sent across the stream.
21
+ # The heartbeats sent as comments on the stream will keep this from triggering.
22
+ STREAM_READ_TIMEOUT = 5 * 60
23
+
24
+ #
25
+ # StreamingDataSource is a Synchronizer that uses Server-Sent Events (SSE)
26
+ # to receive real-time updates from LaunchDarkly's Flag Delivery services.
27
+ #
28
+ class StreamingDataSource
29
+ include LaunchDarkly::Interfaces::DataSystem::Synchronizer
30
+
31
+ attr_reader :name
32
+
33
+ #
34
+ # @param sdk_key [String]
35
+ # @param http_config [HttpConfigOptions] HTTP connection settings
36
+ # @param initial_reconnect_delay [Float] Initial delay before reconnecting after an error
37
+ # @param config [LaunchDarkly::Config] Used for global header settings
38
+ #
39
+ def initialize(sdk_key, http_config, initial_reconnect_delay, config)
40
+ @sdk_key = sdk_key
41
+ @http_config = http_config
42
+ @initial_reconnect_delay = initial_reconnect_delay
43
+ @config = config
44
+ @logger = config.logger
45
+ @name = "StreamingDataSourceV2"
46
+ @sse = nil
47
+ @stopped = Concurrent::Event.new
48
+ @diagnostic_accumulator = nil
49
+ @connection_attempt_start_time = 0
50
+ end
51
+
52
+ #
53
+ # Sets the diagnostic accumulator for streaming initialization metrics.
54
+ #
55
+ # @param diagnostic_accumulator [LaunchDarkly::Impl::DiagnosticAccumulator]
56
+ #
57
+ def set_diagnostic_accumulator(diagnostic_accumulator)
58
+ @diagnostic_accumulator = diagnostic_accumulator
59
+ end
60
+
61
+ #
62
+ # sync begins the synchronization process for the data source, yielding
63
+ # Update objects until the connection is closed or an unrecoverable error
64
+ # occurs.
65
+ #
66
+ # @param ss [LaunchDarkly::Interfaces::DataSystem::SelectorStore]
67
+ # @yieldparam update [LaunchDarkly::Interfaces::DataSystem::Update]
68
+ #
69
+ def sync(ss)
70
+ @logger.info { "[LDClient] Starting StreamingDataSourceV2 synchronizer" }
71
+ log_connection_started
72
+
73
+ change_set_builder = LaunchDarkly::Interfaces::DataSystem::ChangeSetBuilder.new
74
+ envid = nil
75
+
76
+ base_uri = @http_config.base_uri + FDV2_STREAMING_ENDPOINT
77
+ headers = Impl::Util.default_http_headers(@sdk_key, @config)
78
+ opts = {
79
+ headers: headers,
80
+ read_timeout: STREAM_READ_TIMEOUT,
81
+ logger: @logger,
82
+ socket_factory: @http_config.socket_factory,
83
+ reconnect_time: @initial_reconnect_delay,
84
+ }
85
+
86
+ @sse = SSE::Client.new(base_uri, **opts) do |client|
87
+ client.on_connect do |headers|
88
+ # Extract environment ID and check for fallback on successful connection
89
+ if headers
90
+ envid = headers[LD_ENVID_HEADER] || envid
91
+
92
+ # Check for fallback header on connection
93
+ if headers[LD_FD_FALLBACK_HEADER] == 'true'
94
+ log_connection_result(true)
95
+ yield LaunchDarkly::Interfaces::DataSystem::Update.new(
96
+ state: LaunchDarkly::Interfaces::DataSource::Status::OFF,
97
+ revert_to_fdv1: true,
98
+ environment_id: envid
99
+ )
100
+ stop
101
+ end
102
+ end
103
+ end
104
+
105
+ client.on_event do |event|
106
+ begin
107
+ update = process_message(event, change_set_builder, envid)
108
+ if update
109
+ log_connection_result(true)
110
+ @connection_attempt_start_time = 0
111
+ yield update
112
+ end
113
+ rescue JSON::ParserError => e
114
+ @logger.info { "[LDClient] Error parsing stream event; will restart stream: #{e}" }
115
+ yield LaunchDarkly::Interfaces::DataSystem::Update.new(
116
+ state: LaunchDarkly::Interfaces::DataSource::Status::INTERRUPTED,
117
+ error: LaunchDarkly::Interfaces::DataSource::ErrorInfo.new(
118
+ LaunchDarkly::Interfaces::DataSource::ErrorInfo::INVALID_DATA,
119
+ 0,
120
+ e.to_s,
121
+ Time.now
122
+ ),
123
+ environment_id: envid
124
+ )
125
+
126
+ # Re-raise the exception so the SSE implementation can catch it and restart the stream.
127
+ raise
128
+ rescue => e
129
+ @logger.info { "[LDClient] Error while handling stream event; will restart stream: #{e}" }
130
+ yield LaunchDarkly::Interfaces::DataSystem::Update.new(
131
+ state: LaunchDarkly::Interfaces::DataSource::Status::INTERRUPTED,
132
+ error: LaunchDarkly::Interfaces::DataSource::ErrorInfo.new(
133
+ LaunchDarkly::Interfaces::DataSource::ErrorInfo::UNKNOWN,
134
+ 0,
135
+ e.to_s,
136
+ Time.now
137
+ ),
138
+ environment_id: envid
139
+ )
140
+
141
+ # Re-raise the exception so the SSE implementation can catch it and restart the stream.
142
+ raise
143
+ end
144
+ end
145
+
146
+ client.on_error do |error|
147
+ log_connection_result(false)
148
+ fallback = false
149
+
150
+ # Extract envid and fallback from error headers if available
151
+ if error.respond_to?(:headers) && error.headers
152
+ envid = error.headers[LD_ENVID_HEADER] || envid
153
+
154
+ if error.headers[LD_FD_FALLBACK_HEADER] == 'true'
155
+ fallback = true
156
+ end
157
+ end
158
+
159
+ update = handle_error(error, envid, fallback)
160
+ yield update if update
161
+ end
162
+
163
+ client.query_params do
164
+ selector = ss.selector
165
+ {
166
+ "filter" => @config.payload_filter_key,
167
+ "basis" => (selector.state if selector&.defined?),
168
+ }.compact
169
+ end
170
+ end
171
+
172
+ unless @sse
173
+ @logger.error { "[LDClient] Failed to create SSE client for streaming updates" }
174
+ return
175
+ end
176
+
177
+ # Client auto-starts in background thread. Wait here until stop() is called.
178
+ @stopped.wait
179
+ end
180
+
181
+ #
182
+ # Stops the streaming synchronizer.
183
+ #
184
+ def stop
185
+ @logger.info { "[LDClient] Stopping StreamingDataSourceV2 synchronizer" }
186
+ @sse&.close
187
+ @stopped.set
188
+ end
189
+
190
+ #
191
+ # Processes a single SSE message and returns an Update if applicable.
192
+ #
193
+ # @param message [SSE::StreamEvent]
194
+ # @param change_set_builder [LaunchDarkly::Interfaces::DataSystem::ChangeSetBuilder]
195
+ # @param envid [String, nil]
196
+ # @return [LaunchDarkly::Interfaces::DataSystem::Update, nil]
197
+ #
198
+ private def process_message(message, change_set_builder, envid)
199
+ event_type = message.type
200
+
201
+ # Handle heartbeat
202
+ if event_type == LaunchDarkly::Interfaces::DataSystem::EventName::HEARTBEAT
203
+ return nil
204
+ end
205
+
206
+ @logger.debug { "[LDClient] Stream received #{event_type} message: #{message.data}" }
207
+
208
+ case event_type
209
+ when LaunchDarkly::Interfaces::DataSystem::EventName::SERVER_INTENT
210
+ server_intent = LaunchDarkly::Interfaces::DataSystem::ServerIntent.from_h(JSON.parse(message.data, symbolize_names: true))
211
+ change_set_builder.start(server_intent.payload.code)
212
+
213
+ if server_intent.payload.code == LaunchDarkly::Interfaces::DataSystem::IntentCode::TRANSFER_NONE
214
+ change_set_builder.expect_changes
215
+ return LaunchDarkly::Interfaces::DataSystem::Update.new(
216
+ state: LaunchDarkly::Interfaces::DataSource::Status::VALID,
217
+ environment_id: envid
218
+ )
219
+ end
220
+ nil
221
+
222
+ when LaunchDarkly::Interfaces::DataSystem::EventName::PUT_OBJECT
223
+ put = LaunchDarkly::Impl::DataSystem::ProtocolV2::PutObject.from_h(JSON.parse(message.data, symbolize_names: true))
224
+ change_set_builder.add_put(put.kind, put.key, put.version, put.object)
225
+ nil
226
+
227
+ when LaunchDarkly::Interfaces::DataSystem::EventName::DELETE_OBJECT
228
+ delete_object = LaunchDarkly::Impl::DataSystem::ProtocolV2::DeleteObject.from_h(JSON.parse(message.data, symbolize_names: true))
229
+ change_set_builder.add_delete(delete_object.kind, delete_object.key, delete_object.version)
230
+ nil
231
+
232
+ when LaunchDarkly::Interfaces::DataSystem::EventName::GOODBYE
233
+ goodbye = LaunchDarkly::Impl::DataSystem::ProtocolV2::Goodbye.from_h(JSON.parse(message.data, symbolize_names: true))
234
+ unless goodbye.silent
235
+ @logger.error { "[LDClient] SSE server received error: #{goodbye.reason} (catastrophe: #{goodbye.catastrophe})" }
236
+ end
237
+ nil
238
+
239
+ when LaunchDarkly::Interfaces::DataSystem::EventName::ERROR
240
+ error = LaunchDarkly::Impl::DataSystem::ProtocolV2::Error.from_h(JSON.parse(message.data, symbolize_names: true))
241
+ @logger.error { "[LDClient] Error on #{error.payload_id}: #{error.reason}" }
242
+
243
+ # Reset any previous change events but continue with last server intent
244
+ change_set_builder.reset
245
+ nil
246
+
247
+ when LaunchDarkly::Interfaces::DataSystem::EventName::PAYLOAD_TRANSFERRED
248
+ selector = LaunchDarkly::Interfaces::DataSystem::Selector.from_h(JSON.parse(message.data, symbolize_names: true))
249
+ change_set = change_set_builder.finish(selector)
250
+
251
+ LaunchDarkly::Interfaces::DataSystem::Update.new(
252
+ state: LaunchDarkly::Interfaces::DataSource::Status::VALID,
253
+ change_set: change_set,
254
+ environment_id: envid
255
+ )
256
+
257
+ else
258
+ @logger.info { "[LDClient] Unexpected event found in stream: #{event_type}" }
259
+ nil
260
+ end
261
+ end
262
+
263
+ #
264
+ # Handles errors that occur during streaming.
265
+ #
266
+ # @param error [Exception]
267
+ # @param envid [String, nil]
268
+ # @param fallback [Boolean]
269
+ # @return [LaunchDarkly::Interfaces::DataSystem::Update, nil]
270
+ #
271
+ private def handle_error(error, envid, fallback)
272
+ return nil if @stopped.set?
273
+
274
+ update = nil
275
+
276
+ case error
277
+ when SSE::Errors::HTTPStatusError
278
+ error_info = LaunchDarkly::Interfaces::DataSource::ErrorInfo.new(
279
+ LaunchDarkly::Interfaces::DataSource::ErrorInfo::ERROR_RESPONSE,
280
+ error.status,
281
+ Impl::Util.http_error_message(error.status, "stream connection", "will retry"),
282
+ Time.now
283
+ )
284
+
285
+ if fallback
286
+ update = LaunchDarkly::Interfaces::DataSystem::Update.new(
287
+ state: LaunchDarkly::Interfaces::DataSource::Status::OFF,
288
+ error: error_info,
289
+ revert_to_fdv1: true,
290
+ environment_id: envid
291
+ )
292
+ stop
293
+ return update
294
+ end
295
+
296
+ is_recoverable = Impl::Util.http_error_recoverable?(error.status)
297
+
298
+ update = LaunchDarkly::Interfaces::DataSystem::Update.new(
299
+ state: is_recoverable ? LaunchDarkly::Interfaces::DataSource::Status::INTERRUPTED : LaunchDarkly::Interfaces::DataSource::Status::OFF,
300
+ error: error_info,
301
+ environment_id: envid
302
+ )
303
+
304
+ unless is_recoverable
305
+ @logger.error { "[LDClient] #{error_info.message}" }
306
+ stop
307
+ return update
308
+ end
309
+
310
+ @logger.warn { "[LDClient] #{error_info.message}" }
311
+
312
+ when SSE::Errors::HTTPContentTypeError, SSE::Errors::HTTPProxyError, SSE::Errors::ReadTimeoutError
313
+ @logger.warn { "[LDClient] Network error on stream connection: #{error}, will retry" }
314
+
315
+ update = LaunchDarkly::Interfaces::DataSystem::Update.new(
316
+ state: LaunchDarkly::Interfaces::DataSource::Status::INTERRUPTED,
317
+ error: LaunchDarkly::Interfaces::DataSource::ErrorInfo.new(
318
+ LaunchDarkly::Interfaces::DataSource::ErrorInfo::NETWORK_ERROR,
319
+ 0,
320
+ error.to_s,
321
+ Time.now
322
+ ),
323
+ environment_id: envid
324
+ )
325
+
326
+ else
327
+ @logger.warn { "[LDClient] Unexpected error on stream connection: #{error}, will retry" }
328
+
329
+ update = LaunchDarkly::Interfaces::DataSystem::Update.new(
330
+ state: LaunchDarkly::Interfaces::DataSource::Status::INTERRUPTED,
331
+ error: LaunchDarkly::Interfaces::DataSource::ErrorInfo.new(
332
+ LaunchDarkly::Interfaces::DataSource::ErrorInfo::UNKNOWN,
333
+ 0,
334
+ error.to_s,
335
+ Time.now
336
+ ),
337
+ environment_id: envid
338
+ )
339
+ end
340
+
341
+ update
342
+ end
343
+
344
+ private def log_connection_started
345
+ @connection_attempt_start_time = Impl::Util.current_time_millis
346
+ end
347
+
348
+ private def log_connection_result(is_success)
349
+ return unless @diagnostic_accumulator
350
+ return unless @connection_attempt_start_time > 0
351
+
352
+ current_time = Impl::Util.current_time_millis
353
+ elapsed = current_time - @connection_attempt_start_time
354
+ @diagnostic_accumulator.record_stream_init(@connection_attempt_start_time, !is_success, elapsed >= 0 ? elapsed : 0)
355
+ @connection_attempt_start_time = 0
356
+ end
357
+ end
358
+
359
+ #
360
+ # Builder for a StreamingDataSource.
361
+ #
362
+ class StreamingDataSourceBuilder
363
+ include DataSourceBuilderCommon
364
+
365
+ DEFAULT_BASE_URI = "https://stream.launchdarkly.com"
366
+ DEFAULT_INITIAL_RECONNECT_DELAY = 1
367
+
368
+ def initialize
369
+ # No initialization needed - defaults applied in build via nil-check
370
+ end
371
+
372
+ #
373
+ # Sets the initial delay before reconnecting after an error.
374
+ #
375
+ # @param delay [Float] Delay in seconds
376
+ # @return [StreamingDataSourceBuilder]
377
+ #
378
+ def initial_reconnect_delay(delay)
379
+ @initial_reconnect_delay = delay
380
+ self
381
+ end
382
+
383
+ #
384
+ # Builds the StreamingDataSource with the configured parameters.
385
+ #
386
+ # @param sdk_key [String]
387
+ # @param config [LaunchDarkly::Config]
388
+ # @return [StreamingDataSource]
389
+ #
390
+ def build(sdk_key, config)
391
+ http_opts = build_http_config
392
+ StreamingDataSource.new(
393
+ sdk_key, http_opts,
394
+ @initial_reconnect_delay || DEFAULT_INITIAL_RECONNECT_DELAY,
395
+ config
396
+ )
397
+ end
398
+ end
399
+ end
400
+ end
401
+ end
@@ -1,5 +1,6 @@
1
1
  require "ldclient-rb/impl/unbounded_pool"
2
2
  require "ldclient-rb/impl/util"
3
+ require "ldclient-rb/impl/data_system/http_config_options"
3
4
 
4
5
  require "securerandom"
5
6
  require "http"
@@ -14,15 +15,21 @@ module LaunchDarkly
14
15
  CURRENT_SCHEMA_VERSION = 4
15
16
  DEFAULT_RETRY_INTERVAL = 1
16
17
 
17
- def initialize(sdk_key, config, http_client = nil, retry_interval = DEFAULT_RETRY_INTERVAL)
18
+ def initialize(sdk_key, config, retry_interval = DEFAULT_RETRY_INTERVAL)
18
19
  @sdk_key = sdk_key
19
20
  @config = config
20
- @events_uri = config.events_uri + "/bulk"
21
- @diagnostic_uri = config.events_uri + "/diagnostic"
21
+ @http_config = DataSystem::HttpConfigOptions.new(
22
+ base_uri: config.events_uri,
23
+ socket_factory: config.socket_factory,
24
+ read_timeout: config.read_timeout,
25
+ connect_timeout: config.connect_timeout
26
+ )
27
+ @events_uri = @http_config.base_uri + "/bulk"
28
+ @diagnostic_uri = @http_config.base_uri + "/diagnostic"
22
29
  @logger = config.logger
23
30
  @retry_interval = retry_interval
24
31
  @http_client_pool = UnboundedPool.new(
25
- lambda { Impl::Util.new_http_client(@config.events_uri, @config) },
32
+ lambda { Impl::Util.new_http_client(@http_config) },
26
33
  lambda { |client| client.close })
27
34
  end
28
35