diff --git a/.github/actions/ci/action.yml b/.github/actions/ci/action.yml index df40625f..c0f0c0a1 100644 --- a/.github/actions/ci/action.yml +++ b/.github/actions/ci/action.yml @@ -71,6 +71,16 @@ runs: cd packages/common dart test test/serialization/canonicalize_json_platform_test.dart -p chrome --test-randomize-ordering-seed=random + - name: Web Streaming Tests (Chrome) + shell: bash + # On web, the SDK removes the tags header from streaming requests. + # Without a supplied eventSource, it also streams with GET or polls + # instead of streaming with REPORT or POST. The Dart VM resolves the + # web-only configuration to the io branch, so these tests run on Chrome. + run: | + cd packages/common_client + dart test test/data_sources/streaming_client_web_test.dart -p chrome --test-randomize-ordering-seed=random + - name: Contract Tests (FDv1) shell: bash run: | diff --git a/packages/common_client/lib/launchdarkly_common_client.dart b/packages/common_client/lib/launchdarkly_common_client.dart index 50a01e3e..4247afd7 100644 --- a/packages/common_client/lib/launchdarkly_common_client.dart +++ b/packages/common_client/lib/launchdarkly_common_client.dart @@ -6,6 +6,10 @@ export 'src/ld_common_config.dart' AutoEnvAttributes, PollingConfig; +export 'src/data_sources/streaming_client.dart' show SseClientBuilder; +export 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart' + show SSEClient; + export 'src/config/data_system_config.dart' show DataSystemConfig, ConnectionModeId; export 'src/data_sources/fdv2/mode_definition.dart' diff --git a/packages/common_client/lib/src/config/data_system_config.dart b/packages/common_client/lib/src/config/data_system_config.dart index 44722d98..f4c9413a 100644 --- a/packages/common_client/lib/src/config/data_system_config.dart +++ b/packages/common_client/lib/src/config/data_system_config.dart @@ -95,9 +95,10 @@ final class DataSystemConfig { /// source keeps the context out of the URL the same way, with the REPORT /// method that the FDv1 endpoints accept. /// - /// The browser EventSource cannot send a POST request. On web the SDK - /// skips streaming sources when this option is set and logs a warning, - /// so a mode that would stream polls instead. + /// On web, the default streaming client cannot send a POST request. The + /// SDK then skips the streaming sources, logs a warning, and a mode that + /// would stream polls instead. Pass `SSEClient.http` as the `eventSource` + /// option of the client configuration to stream with POST on web. final bool usePost; const DataSystemConfig({ diff --git a/packages/common_client/lib/src/config/defaults/io_config.dart b/packages/common_client/lib/src/config/defaults/io_config.dart index 1fb4a911..b15e8bdf 100644 --- a/packages/common_client/lib/src/config/defaults/io_config.dart +++ b/packages/common_client/lib/src/config/defaults/io_config.dart @@ -61,8 +61,10 @@ final class DefaultDataSourceConfig { ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming; - bool get streamingReportSupported => true; - - /// The streaming transport can send a POST request with a body. + /// The default streaming client can send a POST or REPORT request with a + /// body. bool get streamingPostSupported => true; + + /// The streaming service accepts the application tags header. + bool get streamingTagsHeaderSupported => true; } diff --git a/packages/common_client/lib/src/config/defaults/js_config.dart b/packages/common_client/lib/src/config/defaults/js_config.dart index bd11c6ea..92668e26 100644 --- a/packages/common_client/lib/src/config/defaults/js_config.dart +++ b/packages/common_client/lib/src/config/defaults/js_config.dart @@ -70,8 +70,11 @@ final class DefaultDataSourceConfig { ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming; - bool get streamingReportSupported => false; - - /// The browser EventSource can only send GET requests without a body. + /// The default streaming client on web is the browser EventSource. It can + /// only send GET requests without a body. bool get streamingPostSupported => false; + + /// The CORS allow-list of the streaming service does not include the + /// application tags header. A browser blocks a request that sends it. + bool get streamingTagsHeaderSupported => false; } diff --git a/packages/common_client/lib/src/config/defaults/stub_config.dart b/packages/common_client/lib/src/config/defaults/stub_config.dart index e17dfcb9..e08d61bf 100644 --- a/packages/common_client/lib/src/config/defaults/stub_config.dart +++ b/packages/common_client/lib/src/config/defaults/stub_config.dart @@ -62,7 +62,8 @@ final class DefaultDataSourceConfig { ConnectionMode get defaultInitialConnectionMode => throw Exception('Stub implementation'); - bool get streamingReportSupported => throw Exception('Stub implementation'); - bool get streamingPostSupported => throw Exception('Stub implementation'); + + bool get streamingTagsHeaderSupported => + throw Exception('Stub implementation'); } diff --git a/packages/common_client/lib/src/data_sources/fdv2/data_system.dart b/packages/common_client/lib/src/data_sources/fdv2/data_system.dart index 0b680dc4..7469b8a6 100644 --- a/packages/common_client/lib/src/data_sources/fdv2/data_system.dart +++ b/packages/common_client/lib/src/data_sources/fdv2/data_system.dart @@ -1,13 +1,14 @@ import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart' hide ServiceEndpoints; +import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; import 'package:meta/meta.dart'; import '../../config/data_system_config.dart'; -import '../../config/defaults/default_config.dart'; import '../../config/service_endpoints.dart'; import '../../fdv2_connection_mode.dart'; import '../data_source_manager.dart'; import '../data_source_status_manager.dart'; +import '../streaming_client.dart'; import 'built_in_modes.dart'; import 'cache_initializer.dart'; import 'entry_factories.dart'; @@ -40,9 +41,13 @@ final class FDv2DataSystem { final DataSourceStatusManager _statusManager; final Map _connectionModeOverrides; final CachedFlagsReader _cachedFlagsReader; - final FDv2SseClientFactory _sseClientFactory; + final SseClientBuilder _sseClientBuilder; final HttpClientFactory? _httpClientFactory; + /// The builder that the streaming synchronizers use. + @visibleForTesting + SseClientBuilder get eventSource => _sseClientBuilder; + Selector _selector = Selector.empty; FDv2DataSystem({ @@ -55,10 +60,12 @@ final class FDv2DataSystem { required Duration defaultPollingInterval, required DataSourceStatusManager statusManager, required CachedFlagsReader cachedFlagsReader, - FDv2SseClientFactory sseClientFactory = defaultSseClientFactory, + // Builds the SSE client. When it is null, the data system uses the + // default client for the platform. Tests inject a fake. + SseClientBuilder? eventSource, HttpClientFactory? httpClientFactory, - // Whether the platform's streaming transport can send a POST request. - // Defaults to the platform's capability; tests override it. + // Whether the streaming client can send a POST request. Defaults to the + // capability of the selected client. Tests override it. bool? streamingPostSupported, }) : _credential = credential, _logger = logger, @@ -67,11 +74,11 @@ final class FDv2DataSystem { _withReasons = withReasons, _usePost = config.usePost, _streamingPostSupported = streamingPostSupported ?? - DefaultConfig.dataSourceConfig.streamingPostSupported, + streamingCustomMethodSupported(eventSource: eventSource), _defaultPollingInterval = defaultPollingInterval, _statusManager = statusManager, _cachedFlagsReader = cachedFlagsReader, - _sseClientFactory = sseClientFactory, + _sseClientBuilder = eventSource ?? SSEClient.new, _httpClientFactory = httpClientFactory, _connectionModeOverrides = config.connectionModes { if (_usePost && !_streamingPostSupported) { @@ -179,7 +186,7 @@ final class FDv2DataSystem { final synchronizerSlots = buildSynchronizerFactories( modeDefinition.synchronizers, factoryContext, - sseClientFactory: _sseClientFactory) + sseClientBuilder: _sseClientBuilder) .map((factory) => SynchronizerSlot(factory: factory)) .toList(); diff --git a/packages/common_client/lib/src/data_sources/fdv2/entry_factories.dart b/packages/common_client/lib/src/data_sources/fdv2/entry_factories.dart index f8dc8636..58deec61 100644 --- a/packages/common_client/lib/src/data_sources/fdv2/entry_factories.dart +++ b/packages/common_client/lib/src/data_sources/fdv2/entry_factories.dart @@ -6,6 +6,7 @@ import 'package:launchdarkly_event_source_client/launchdarkly_event_source_clien import '../../config/defaults/default_config.dart'; import '../../config/service_endpoints.dart'; +import '../streaming_client.dart'; import '../streaming_data_source.dart' show LDLoggerToEventSourceAdapter; import 'cache_initializer.dart' as cache_src; import 'endpoints.dart'; @@ -70,17 +71,6 @@ HttpClient _defaultHttpClientFactory(HttpProperties httpProperties) { return HttpClient(httpProperties: httpProperties); } -/// Constructs the [SSEClient] used by a streaming source. [uriProvider] -/// is re-invoked on every connection attempt so the `basis` query -/// parameter reflects the current selector. Tests inject a fake. -typedef FDv2SseClientFactory = SSEClient Function({ - required Uri Function() uriProvider, - required HttpProperties httpProperties, - required String? body, - required SseHttpMethod method, - required EventSourceLogger logger, -}); - /// FDv2 event names subscribed on the streaming connection. Includes the /// legacy `ping` bridge event. const Set _fdv2StreamEventNames = { @@ -94,23 +84,6 @@ const Set _fdv2StreamEventNames = { 'ping', }; -/// Constructs the production [SSEClient]. The default for the factory -/// builders; tests inject a fake through the same parameter. -SSEClient defaultSseClientFactory({ - required Uri Function() uriProvider, - required HttpProperties httpProperties, - required String? body, - required SseHttpMethod method, - required EventSourceLogger logger, -}) { - return SSEClient(uriProvider(), _fdv2StreamEventNames, - headers: httpProperties.baseHeaders, - body: body, - httpMethod: method, - logger: logger, - uriProvider: uriProvider); -} - /// Builds the streaming URI for the current state. Invoked per /// connection attempt so the `basis` parameter tracks the selector. Uri _buildStreamingUri({ @@ -202,7 +175,7 @@ InitializerFactory createInitializerFactoryFromEntry( SynchronizerFactory createSynchronizerFactoryFromEntry( mode.SynchronizerEntry entry, SourceFactoryContext ctx, { - FDv2SseClientFactory sseClientFactory = defaultSseClientFactory, + SseClientBuilder sseClientBuilder = SSEClient.new, }) { switch (entry) { case final mode.PollingSynchronizer e: @@ -235,13 +208,13 @@ SynchronizerFactory createSynchronizerFactoryFromEntry( basis: selectorGetter(), additionalQueryParameters: ctx.additionalQueryParameters, ); - final sseClient = sseClientFactory( - uriProvider: uriProvider, - httpProperties: ctx.httpProperties, - body: ctx.usePost ? ctx.contextJson : null, - method: ctx.usePost ? SseHttpMethod.post : SseHttpMethod.get, - logger: LDLoggerToEventSourceAdapter(ctx.logger), - ); + final sseClient = sseClientBuilder( + uriProvider(), _fdv2StreamEventNames, + headers: streamingRequestHeaders(ctx.httpProperties), + body: ctx.usePost ? ctx.contextJson : null, + httpMethod: ctx.usePost ? SseHttpMethod.post : SseHttpMethod.get, + logger: LDLoggerToEventSourceAdapter(ctx.logger), + uriProvider: uriProvider); // Legacy ping events trigger a one-shot poll. final pingPollingBase = _buildPollingBase( @@ -278,10 +251,10 @@ List buildInitializerFactories( List buildSynchronizerFactories( List entries, SourceFactoryContext ctx, { - FDv2SseClientFactory sseClientFactory = defaultSseClientFactory, + SseClientBuilder sseClientBuilder = SSEClient.new, }) { return entries .map((e) => createSynchronizerFactoryFromEntry(e, ctx, - sseClientFactory: sseClientFactory)) + sseClientBuilder: sseClientBuilder)) .toList(); } diff --git a/packages/common_client/lib/src/data_sources/streaming_client.dart b/packages/common_client/lib/src/data_sources/streaming_client.dart new file mode 100644 index 00000000..871826eb --- /dev/null +++ b/packages/common_client/lib/src/data_sources/streaming_client.dart @@ -0,0 +1,48 @@ +import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart'; +import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; + +import '../config/defaults/default_config.dart'; + +/// Builds the SSE client for a streaming connection. +/// +/// The type has the shape of the [SSEClient] constructors, so [SSEClient.new] +/// and [SSEClient.http] are builders. The SDK calls the builder once for each +/// streaming connection it needs, and closes the client when it stops +/// streaming. +typedef SseClientBuilder = SSEClient Function(Uri uri, Set eventTypes, + {required Map headers, + required String? body, + required SseHttpMethod httpMethod, + required EventSourceLogger logger, + Uri Function()? uriProvider}); + +/// Whether the streaming client can send a POST or REPORT request with a +/// body. +/// +/// The SDK treats a supplied [eventSource] as able to send a body. The +/// default client, [SSEClient.new], has the capability of the platform. This +/// is true when it is passed as the builder and when [eventSource] is null. +/// On web, the default client is the browser `EventSource`, which cannot +/// send a body. The SDK cannot recognize a function that wraps the default +/// client. +bool streamingCustomMethodSupported({required SseClientBuilder? eventSource}) => + (eventSource != null && !identical(eventSource, SSEClient.new)) || + DefaultConfig.dataSourceConfig.streamingPostSupported; + +const String _tagsHeader = 'x-launchdarkly-tags'; + +/// Returns the headers for a streaming request. +/// +/// On web, the function removes the application tags header. The CORS +/// allow-list of the streaming service does not include it, so a browser +/// blocks a request that sends it. +Map streamingRequestHeaders(HttpProperties httpProperties) { + final headers = httpProperties.baseHeaders; + if (DefaultConfig.dataSourceConfig.streamingTagsHeaderSupported) { + return headers; + } + return Map.unmodifiable({ + for (final entry in headers.entries) + if (entry.key.toLowerCase() != _tagsHeader) entry.key: entry.value, + }); +} diff --git a/packages/common_client/lib/src/data_sources/streaming_data_source.dart b/packages/common_client/lib/src/data_sources/streaming_data_source.dart index f3e5cb43..3f07470c 100644 --- a/packages/common_client/lib/src/data_sources/streaming_data_source.dart +++ b/packages/common_client/lib/src/data_sources/streaming_data_source.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart'; import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; +import 'package:meta/meta.dart'; import '../config/data_source_config.dart'; import '../config/defaults/default_config.dart'; @@ -10,6 +11,7 @@ import 'data_source.dart'; import 'data_source_status.dart'; import 'get_environment_id.dart'; import 'requestor.dart'; +import 'streaming_client.dart'; const String _pingEvent = 'ping'; const String _patchEvent = 'patch'; @@ -18,22 +20,6 @@ const String _delete = 'delete'; typedef MessageHandler = void Function(MessageEvent); typedef ErrorHandler = void Function(dynamic); -typedef SseClientFactory = SSEClient Function( - Uri uri, - HttpProperties httpProperties, - String? body, - SseHttpMethod? method, - EventSourceLogger? logger); - -SSEClient _defaultClientFactory(Uri uri, HttpProperties httpProperties, - String? body, SseHttpMethod? method, EventSourceLogger? logger) { - return SSEClient(uri, {_putEvent, _patchEvent, _delete, _pingEvent}, - headers: httpProperties.baseHeaders, - body: body, - httpMethod: method ?? SseHttpMethod.get, - logger: logger); -} - HttpClient _defaultHttpClientFactory(HttpProperties httpProperties) { return HttpClient(httpProperties: httpProperties); } @@ -43,7 +29,7 @@ final class StreamingDataSource implements DataSource { final StreamingDataSourceConfig _dataSourceConfig; - final SseClientFactory _clientFactory; + final SseClientBuilder _clientBuilder; late final Uri _uri; @@ -72,12 +58,15 @@ final class StreamingDataSource implements DataSource { /// Used to track if there has been an unrecoverable error. bool _permanentShutdown = false; - /// The [clientFactory] parameter is primarily intended for testing, but it also - /// could be used for customized SSE clients which support functionality - /// our default client support does not, or for alternative implementations - /// which are not based on SSE. - /// The [httpClientFactory] parameter is primarily intended for testing the - /// requestor used for ping events. + /// The builder that [start] uses for the SSE client. + @visibleForTesting + SseClientBuilder get eventSource => _clientBuilder; + + /// [eventSource] builds the SSE client. When it is null, the data source + /// uses the default client for the platform. Tests inject a fake client. + /// The [streamingReportSupported] parameter overrides whether the client + /// can send REPORT. Tests set it. The [httpClientFactory] parameter is for + /// tests of the requestor that serves ping events. StreamingDataSource( {required String credential, required LDContext context, @@ -86,24 +75,26 @@ final class StreamingDataSource implements DataSource { required StreamingDataSourceConfig dataSourceConfig, required PollingDataSourceConfig pollingDataSourceConfig, required HttpProperties httpProperties, - SseClientFactory clientFactory = _defaultClientFactory, + SseClientBuilder? eventSource, + bool? streamingReportSupported, HttpClientFactory? httpClientFactory}) : _logger = logger.subLogger('StreamingDataSource'), _dataSourceConfig = dataSourceConfig, - _clientFactory = clientFactory, + _clientBuilder = eventSource ?? SSEClient.new, _httpProperties = httpProperties, _credential = credential { final plainContextString = jsonEncode(LDContextSerialization.toJson(context, isEvent: false)); - if (_dataSourceConfig.useReport && - !DefaultConfig.dataSourceConfig.streamingReportSupported) { - _logger.warn( - 'REPORT is currently not supported for streaming on web targets'); - } - _useReport = _dataSourceConfig.useReport && - DefaultConfig.dataSourceConfig.streamingReportSupported; + (streamingReportSupported ?? + streamingCustomMethodSupported(eventSource: eventSource)); + + if (_dataSourceConfig.useReport && !_useReport) { + _logger + .warn('The streaming transport on this platform cannot send REPORT ' + 'requests. The SDK streams with GET instead.'); + } _contextString = _useReport ? plainContextString @@ -139,14 +130,15 @@ final class StreamingDataSource implements DataSource { } _stopped = false; _logger.debug('Establishing new streaming connection, uri: $_uri'); - _client = _clientFactory( - _uri, - _httpProperties, - _useReport ? _contextString : null, - _useReport ? SseHttpMethod.report : SseHttpMethod.get, - LDLoggerToEventSourceAdapter(_logger)); - - _subscription = _client!.stream.listen((event) async { + final client = _clientBuilder( + _uri, const {_putEvent, _patchEvent, _delete, _pingEvent}, + headers: streamingRequestHeaders(_httpProperties), + body: _useReport ? _contextString : null, + httpMethod: _useReport ? SseHttpMethod.report : SseHttpMethod.get, + logger: LDLoggerToEventSourceAdapter(_logger)); + _client = client; + + _subscription = client.stream.listen((event) async { if (_stopped) { return; } @@ -186,12 +178,10 @@ final class StreamingDataSource implements DataSource { } case OpenEvent(): _logger.debug('Received connect event, data: ${event.headers}'); - if (event.headers != null) { - _environmentId = getEnvironmentId(event.headers); - } else { - _environmentId = DefaultConfig.credentialConfig - .environmentIdFallback(_credential); - } + // A browser can hide the environment ID header, so the fallback + // also applies when the headers are present but lack it. + _environmentId = getEnvironmentId(event.headers) ?? + DefaultConfig.credentialConfig.environmentIdFallback(_credential); } }) ..onError((err) { diff --git a/packages/common_client/lib/src/ld_common_client.dart b/packages/common_client/lib/src/ld_common_client.dart index bd8c496c..fc7961d2 100644 --- a/packages/common_client/lib/src/ld_common_client.dart +++ b/packages/common_client/lib/src/ld_common_client.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:meta/meta.dart'; import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart'; import '../src/config/common_platform.dart'; @@ -81,7 +82,10 @@ final class IdentifyError implements IdentifyResult { typedef DataSourceFactoriesFn = Map Function( LDCommonConfig config, LDLogger logger, HttpProperties httpProperties); -Map _defaultFactories( +/// Builds the FDv1 streaming and polling data source factories from the +/// client configuration. +@visibleForTesting +Map defaultDataSourceFactories( LDCommonConfig config, LDLogger logger, HttpProperties httpProperties) { final useReport = config.dataSourceConfig.useReport; final withReasons = config.dataSourceConfig.evaluationReasons; @@ -100,7 +104,8 @@ Map _defaultFactories( dataSourceConfig: StreamingDataSourceConfig( useReport: useReport, withReasons: withReasons), pollingDataSourceConfig: foregroundPollingConfig, - httpProperties: httpProperties); + httpProperties: httpProperties, + eventSource: config.eventSource); } return { @@ -271,7 +276,8 @@ final class LDCommonClient { _dataSourceStatusManager = DataSourceStatusManager(), _initialUndecoratedContext = context, // Data source factories is primarily a mechanism for testing. - _dataSourceFactories = dataSourceFactories ?? _defaultFactories, + _dataSourceFactories = + dataSourceFactories ?? defaultDataSourceFactories, _eventProcessorFactory = eventProcessorFactory ?? _defaultEventProcessorFactory, _sdkData = sdkData { @@ -446,6 +452,7 @@ final class LDCommonClient { _config.dataSourceConfig.polling.pollingInterval, statusManager: _dataSourceStatusManager, cachedFlagsReader: _flagManager.readCached, + eventSource: _config.eventSource, ); _dataSourceManager.setFactories(dataSystem.buildFactories()); // FDv2 loads the cache through its pipeline and clears the held diff --git a/packages/common_client/lib/src/ld_common_config.dart b/packages/common_client/lib/src/ld_common_config.dart index 7ec741c3..c404ccfd 100644 --- a/packages/common_client/lib/src/ld_common_config.dart +++ b/packages/common_client/lib/src/ld_common_config.dart @@ -4,6 +4,7 @@ import 'dart:math'; import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart' hide ServiceEndpoints; +import 'data_sources/streaming_client.dart'; import 'hooks/hook.dart'; import 'config/data_system_config.dart'; import 'config/defaults/default_config.dart'; @@ -63,8 +64,10 @@ final class DataSourceConfig { final PollingConfig polling; /// [useReport] determines if the data source will attempt to use the - /// REPORT http method if possible. For streaming requests on the web - /// platform report is not supported. The default value is `false`. + /// REPORT http method if possible. On web, the default streaming client + /// cannot send REPORT, so the SDK streams with GET and logs a warning + /// unless [LDCommonConfig.eventSource] supplies a client that can. The + /// default value is `false`. /// This option has no effect when the FDv2 data system is enabled (a /// [DataSystemConfig] is provided); use [DataSystemConfig.usePost] in /// that case. @@ -159,6 +162,32 @@ abstract class LDCommonConfig { /// https://launchdarkly.com/docs/sdk/features/data-saving-mode final DataSystemConfig? dataSystem; + /// Builds the SSE client that the SDK uses for streaming. + /// + /// When this is null, the SDK uses the default client for the platform. On + /// web, the default client is the browser `EventSource`. It cannot send a + /// request body or report an HTTP error, so `useReport` falls back to GET + /// and `usePost` falls back to polling. Pass `SSEClient.http` to stream + /// with `fetch()` through `package:http` instead. Both methods then work + /// on web. On other platforms, the default client is already + /// `SSEClient.http`. + /// + /// The SDK treats a supplied builder as able to send a request body with + /// the POST and REPORT methods. Pass only a client that can. On web, the + /// SDK recognizes `SSEClient.new` and treats it as the default client, but + /// it cannot recognize a function that wraps the default client. + /// + /// Most applications do not need this option. The compiler removes the + /// HTTP-based client from a web build that does not reference it, so an + /// application that leaves this null does not ship that code. + /// + /// With or without this option, the SDK does not send the application tags + /// header on web streaming requests, because the CORS allow-list of the + /// streaming service does not include it. With `SSEClient.http`, the SDK + /// sends the other base headers on web streaming requests, and each one + /// must pass the CORS check of the streaming service. + final SseClientBuilder? eventSource; + LDCommonConfig(this.sdkCredential, this.autoEnvAttributes, {this.applicationInfo, HttpProperties? httpProperties, @@ -171,7 +200,8 @@ abstract class LDCommonConfig { bool? allAttributesPrivate, List? globalPrivateAttributes, List? hooks, - this.dataSystem}) + this.dataSystem, + this.eventSource}) : httpProperties = httpProperties ?? HttpProperties(), serviceEndpoints = serviceEndpoints ?? ServiceEndpoints(), events = events ?? EventsConfig(), diff --git a/packages/common_client/pubspec.yaml b/packages/common_client/pubspec.yaml index eae7de60..31318171 100644 --- a/packages/common_client/pubspec.yaml +++ b/packages/common_client/pubspec.yaml @@ -10,7 +10,7 @@ environment: dependencies: http: ^1.1.2 launchdarkly_dart_common: 1.8.2 - launchdarkly_event_source_client: 3.0.1 + launchdarkly_event_source_client: 3.1.0 crypto: ^3.0.3 meta: ^1.12.0 uuid: ">= 3.0.7 <5.0.0" diff --git a/packages/common_client/test/data_sources/fdv2/data_system_test.dart b/packages/common_client/test/data_sources/fdv2/data_system_test.dart index 723e4906..3b70c172 100644 --- a/packages/common_client/test/data_sources/fdv2/data_system_test.dart +++ b/packages/common_client/test/data_sources/fdv2/data_system_test.dart @@ -5,9 +5,11 @@ import 'package:launchdarkly_common_client/src/data_sources/data_source_status_m import 'package:launchdarkly_common_client/src/data_sources/fdv2/built_in_modes.dart'; import 'package:launchdarkly_common_client/src/data_sources/fdv2/data_system.dart'; import 'package:launchdarkly_common_client/src/data_sources/fdv2/mode_definition.dart'; +import 'package:launchdarkly_common_client/src/data_sources/streaming_client.dart'; import 'package:launchdarkly_common_client/src/fdv2_connection_mode.dart'; import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart' hide ServiceEndpoints; +import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; @@ -17,6 +19,7 @@ FDv2DataSystem makeDataSystem({ DataSystemConfig config = const DataSystemConfig(), bool? streamingPostSupported, LDLogger? logger, + SseClientBuilder? eventSource, }) => FDv2DataSystem( config: config, @@ -29,6 +32,7 @@ FDv2DataSystem makeDataSystem({ statusManager: DataSourceStatusManager(), cachedFlagsReader: (_) async => null, streamingPostSupported: streamingPostSupported, + eventSource: eventSource, ); LDContext _context() => LDContextBuilder().kind('user', 'bob').build(); @@ -99,6 +103,17 @@ void main() { expect(factories.keys, hasLength(4)); }); + group('eventSource', () { + test('uses the default SSE client without a supplied builder', () { + expect(makeDataSystem().eventSource, same(SSEClient.new)); + }); + + test('uses the supplied SSE client builder', () { + expect(makeDataSystem(eventSource: SSEClient.http).eventSource, + same(SSEClient.http)); + }); + }); + test('usePost is off by default', () { expect(const DataSystemConfig().usePost, isFalse); }); diff --git a/packages/common_client/test/data_sources/fdv2/entry_factories_test.dart b/packages/common_client/test/data_sources/fdv2/entry_factories_test.dart index 7751a3a2..13d78c2d 100644 --- a/packages/common_client/test/data_sources/fdv2/entry_factories_test.dart +++ b/packages/common_client/test/data_sources/fdv2/entry_factories_test.dart @@ -152,15 +152,16 @@ void main() { final factory = createSynchronizerFactoryFromEntry( StreamingSynchronizer(), ctx, - sseClientFactory: ({ - required Uri Function() uriProvider, - required HttpProperties httpProperties, - required String? body, - required SseHttpMethod method, - required EventSourceLogger logger, - }) { - capturedUriProvider = uriProvider; - return SSEClient.testClient(uriProvider(), const {}); + sseClientBuilder: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + uriProvider}) { + if (uriProvider case final provider?) { + capturedUriProvider = provider; + } + return SSEClient.testClient(uri, const {}); }, ); final sync = factory.create(() => selector); @@ -203,15 +204,16 @@ void main() { final factory = createSynchronizerFactoryFromEntry( StreamingSynchronizer(), ctx, - sseClientFactory: ({ - required Uri Function() uriProvider, - required HttpProperties httpProperties, - required String? body, - required SseHttpMethod method, - required EventSourceLogger logger, - }) { - capturedUriProvider = uriProvider; - return SSEClient.testClient(uriProvider(), const {}); + sseClientBuilder: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + uriProvider}) { + if (uriProvider case final provider?) { + capturedUriProvider = provider; + } + return SSEClient.testClient(uri, const {}); }, ); final sync = factory.create(() => selector); @@ -348,17 +350,18 @@ void main() { final factory = createSynchronizerFactoryFromEntry( StreamingSynchronizer(), factoryContext(usePost: usePost), - sseClientFactory: ({ - required Uri Function() uriProvider, - required HttpProperties httpProperties, - required String? body, - required SseHttpMethod method, - required EventSourceLogger logger, - }) { - capturedMethod = method; + sseClientBuilder: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + uriProvider}) { + capturedMethod = httpMethod; capturedBody = body; - capturedUriProvider = uriProvider; - return SSEClient.testClient(uriProvider(), const {}); + if (uriProvider case final provider?) { + capturedUriProvider = provider; + } + return SSEClient.testClient(uri, const {}); }, ); factory.create(_selectorGetter).close(); diff --git a/packages/common_client/test/data_sources/streaming_client_test.dart b/packages/common_client/test/data_sources/streaming_client_test.dart new file mode 100644 index 00000000..5b75c4a8 --- /dev/null +++ b/packages/common_client/test/data_sources/streaming_client_test.dart @@ -0,0 +1,33 @@ +@TestOn('vm') +library; + +import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; +import 'package:launchdarkly_common_client/src/data_sources/streaming_client.dart'; +import 'package:test/test.dart'; + +// The web behavior is in streaming_client_web_test.dart. +void main() { + group('streamingCustomMethodSupported', () { + test( + 'is true with and without a supplied builder, because the default ' + 'client is HTTP-based', () { + expect(streamingCustomMethodSupported(eventSource: null), isTrue); + expect( + streamingCustomMethodSupported(eventSource: SSEClient.new), isTrue); + expect( + streamingCustomMethodSupported(eventSource: SSEClient.http), isTrue); + }); + }); + + group('streamingRequestHeaders', () { + final properties = HttpProperties(baseHeaders: { + 'X-LaunchDarkly-Tags': 'application-id/app', + 'x-launchdarkly-user-agent': 'agent', + }); + + test('keeps every header, because the service accepts the tags header', () { + expect( + streamingRequestHeaders(properties), equals(properties.baseHeaders)); + }); + }); +} diff --git a/packages/common_client/test/data_sources/streaming_client_web_test.dart b/packages/common_client/test/data_sources/streaming_client_web_test.dart new file mode 100644 index 00000000..cea7b688 --- /dev/null +++ b/packages/common_client/test/data_sources/streaming_client_web_test.dart @@ -0,0 +1,310 @@ +@TestOn('browser') +library; + +import 'dart:async'; +import 'dart:collection'; + +import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; +import 'package:launchdarkly_common_client/src/config/data_source_config.dart'; +import 'package:launchdarkly_common_client/src/data_sources/data_source.dart'; +import 'package:launchdarkly_common_client/src/data_sources/data_source_status_manager.dart'; +import 'package:launchdarkly_common_client/src/data_sources/fdv2/data_system.dart'; +import 'package:launchdarkly_common_client/src/data_sources/fdv2/entry_factories.dart'; +import 'package:launchdarkly_common_client/src/data_sources/fdv2/selector.dart'; +import 'package:launchdarkly_common_client/src/data_sources/fdv2/source_factory_context.dart'; +import 'package:launchdarkly_common_client/src/data_sources/streaming_client.dart'; +import 'package:launchdarkly_common_client/src/data_sources/streaming_data_source.dart'; +import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:test/test.dart'; + +class MockLogAdapter extends Mock implements LDLogAdapter {} + +/// A client that replays a scripted event stream. +class _ScriptedClient implements SSEClient { + @override + final Stream stream; + + _ScriptedClient(this.stream); + + @override + Future close() async {} + + @override + void restart() {} + + @override + bool hasCapability(SSECapability capability) => true; +} + +// These tests cover the decisions the SDK makes only on web. Run them with +// `dart test test/data_sources/streaming_client_web_test.dart -p chrome`. + +typedef _Call = ({ + Uri uri, + Map headers, + String? body, + SseHttpMethod method +}); + +/// A builder that records its arguments and returns a test client. +SseClientBuilder _recording(List<_Call> calls) => (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + uriProvider}) { + calls.add((uri: uri, headers: headers, body: body, method: httpMethod)); + return SSEClient.testClient(uri, eventTypes); + }; + +void main() { + setUpAll(() { + registerFallbackValue(LDLogRecord( + level: LDLogLevel.debug, + message: '', + time: DateTime.now(), + logTag: '')); + }); + + group('streamingRequestHeaders', () { + test('removes the tags header and keeps the others', () { + final properties = HttpProperties(baseHeaders: { + 'X-LaunchDarkly-Tags': 'application-id/app', + 'x-launchdarkly-user-agent': 'agent', + }); + + final headers = streamingRequestHeaders(properties); + + expect(headers, equals({'x-launchdarkly-user-agent': 'agent'})); + expect(() => headers['a'] = 'b', throwsUnsupportedError); + }); + + test('matches the tags header without regard to case', () { + final properties = + HttpProperties(baseHeaders: {'x-launchdarkly-tags': 'a/b'}); + + expect(streamingRequestHeaders(properties), isEmpty); + }); + }); + + group('streamingCustomMethodSupported', () { + test('is false for the default client, the browser EventSource', () { + expect(streamingCustomMethodSupported(eventSource: null), isFalse); + }); + + test('is false for an explicit SSEClient.new, which is the same client', + () { + expect( + streamingCustomMethodSupported(eventSource: SSEClient.new), isFalse); + }); + + test('is true with a supplied builder', () { + expect( + streamingCustomMethodSupported(eventSource: SSEClient.http), isTrue); + }); + }); + + group('FDv2 with usePost', () { + FDv2DataSystem makeDataSystem({SseClientBuilder? eventSource}) => + FDv2DataSystem( + config: const DataSystemConfig(usePost: true), + credential: 'the-credential', + logger: LDLogger(level: LDLogLevel.none), + httpProperties: HttpProperties(), + serviceEndpoints: ServiceEndpoints(), + withReasons: false, + defaultPollingInterval: const Duration(seconds: 300), + statusManager: DataSourceStatusManager(), + cachedFlagsReader: (_) async => null, + eventSource: eventSource, + ); + + test( + 'the browser EventSource cannot POST, so the streaming entries are ' + 'dropped', () { + final definition = + makeDataSystem().resolvedDefinition(ConnectionModeId.streaming); + + expect( + definition.synchronizers.whereType(), isEmpty); + }); + + test('an explicit SSEClient.new also drops the streaming entries', () { + final definition = makeDataSystem(eventSource: SSEClient.new) + .resolvedDefinition(ConnectionModeId.streaming); + + expect( + definition.synchronizers.whereType(), isEmpty); + }); + + test('a supplied client keeps the streaming entries', () { + final definition = makeDataSystem(eventSource: SSEClient.http) + .resolvedDefinition(ConnectionModeId.streaming); + + expect(definition.synchronizers.whereType(), + isNotEmpty); + }); + }); + + group('FDv2 streaming headers', () { + test('the stream drops the tags header and keeps the others', () { + final calls = <_Call>[]; + final ctx = SourceFactoryContext.fromClientConfig( + credential: 'the-credential', + context: LDContextBuilder().kind('user', 'test').build(), + logger: LDLogger(level: LDLogLevel.none), + httpProperties: HttpProperties(baseHeaders: { + 'X-LaunchDarkly-Tags': 'a/b', + 'x-launchdarkly-user-agent': 'ua', + }), + serviceEndpoints: ServiceEndpoints(), + withReasons: false, + usePost: false, + defaultPollingInterval: const Duration(seconds: 300), + cachedFlagsReader: (_) async => null, + ); + + createSynchronizerFactoryFromEntry(StreamingSynchronizer(), ctx, + sseClientBuilder: _recording(calls)) + .create(() => Selector.empty) + .close(); + + expect(calls.single.headers, isNot(contains('X-LaunchDarkly-Tags'))); + expect(calls.single.headers, + containsPair('x-launchdarkly-user-agent', 'ua')); + }); + }); + + group('FDv1 with useReport', () { + // The recording builder stands in for the default client when + // [streamingReportSupported] is false, and for a supplied client when it + // is null. + StreamingDataSource makeDataSource(List<_Call> calls, + {bool? streamingReportSupported, LDLogger? logger}) => + StreamingDataSource( + credential: 'the-credential', + context: LDContextBuilder().kind('user', 'test').build(), + endpoints: ServiceEndpoints(), + logger: logger ?? LDLogger(level: LDLogLevel.none), + dataSourceConfig: StreamingDataSourceConfig(useReport: true), + pollingDataSourceConfig: PollingDataSourceConfig(useReport: true), + httpProperties: HttpProperties(baseHeaders: { + 'X-LaunchDarkly-Tags': 'a/b', + 'x-launchdarkly-user-agent': 'ua', + }), + eventSource: _recording(calls), + streamingReportSupported: streamingReportSupported); + + test('warns once when the stream falls back to GET', () { + final adapter = MockLogAdapter(); + when(() => adapter.log(any())).thenReturn(null); + + makeDataSource(<_Call>[], + streamingReportSupported: false, + logger: LDLogger(adapter: adapter, level: LDLogLevel.warn)); + + final records = + verify(() => adapter.log(captureAny())).captured.cast(); + expect(records, hasLength(1)); + expect(records.single.level, LDLogLevel.warn); + expect(records.single.message, contains('REPORT')); + }); + + test('warns when an explicit SSEClient.new falls back to GET', () { + final adapter = MockLogAdapter(); + when(() => adapter.log(any())).thenReturn(null); + + // The data source is not started, so no browser EventSource opens. + StreamingDataSource( + credential: 'the-credential', + context: LDContextBuilder().kind('user', 'test').build(), + endpoints: ServiceEndpoints(), + logger: LDLogger(adapter: adapter, level: LDLogLevel.warn), + dataSourceConfig: StreamingDataSourceConfig(useReport: true), + pollingDataSourceConfig: PollingDataSourceConfig(useReport: true), + httpProperties: HttpProperties(), + eventSource: SSEClient.new); + + final records = + verify(() => adapter.log(captureAny())).captured.cast(); + expect(records.single.message, contains('REPORT')); + }); + + test('does not warn with a supplied client', () { + final adapter = MockLogAdapter(); + when(() => adapter.log(any())).thenReturn(null); + + makeDataSource(<_Call>[], + logger: LDLogger(adapter: adapter, level: LDLogLevel.debug)); + + verifyNever(() => adapter.log(any())); + }); + + test('the default client streams with GET and the context in the URI', () { + final calls = <_Call>[]; + final dataSource = makeDataSource(calls, streamingReportSupported: false); + + dataSource.start(); + + expect(calls.single.method, SseHttpMethod.get); + expect(calls.single.body, isNull); + expect(calls.single.uri.path, startsWith('/eval/the-credential/')); + expect(calls.single.headers, isNot(contains('X-LaunchDarkly-Tags'))); + expect(calls.single.headers, + containsPair('x-launchdarkly-user-agent', 'ua')); + dataSource.stop(); + }); + + test('a supplied client streams with REPORT and the context in the body', + () { + final calls = <_Call>[]; + final dataSource = makeDataSource(calls); + + dataSource.start(); + + expect(calls.single.method, SseHttpMethod.report); + expect(calls.single.body, '{"key":"test","kind":"user"}'); + expect(calls.single.uri.path, '/eval/the-credential'); + expect(calls.single.headers, isNot(contains('X-LaunchDarkly-Tags'))); + expect(calls.single.headers, + containsPair('x-launchdarkly-user-agent', 'ua')); + dataSource.stop(); + }); + }); + + group('FDv1 environment ID', () { + test( + 'falls back to the client-side ID when the connection headers lack ' + 'the environment ID header', () async { + final events = StreamController(); + final dataSource = StreamingDataSource( + credential: 'the-credential', + context: LDContextBuilder().kind('user', 'test').build(), + endpoints: ServiceEndpoints(), + logger: LDLogger(level: LDLogLevel.none), + dataSourceConfig: StreamingDataSourceConfig(), + pollingDataSourceConfig: PollingDataSourceConfig(), + httpProperties: HttpProperties(), + eventSource: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + uriProvider}) => + _ScriptedClient(events.stream)); + final firstData = + dataSource.events.firstWhere((event) => event is DataEvent); + + dataSource.start(); + // The browser exposes only the headers the CORS policy allows. + events.sink.add(OpenEvent( + headers: UnmodifiableMapView({'content-type': 'text/event-stream'}))); + events.sink.add(MessageEvent('put', '{}', null)); + + expect((await firstData as DataEvent).environmentId, 'the-credential'); + dataSource.stop(); + await events.close(); + }); + }); +} diff --git a/packages/common_client/test/data_sources/streaming_data_source_test.dart b/packages/common_client/test/data_sources/streaming_data_source_test.dart index dc09068b..62e873d3 100644 --- a/packages/common_client/test/data_sources/streaming_data_source_test.dart +++ b/packages/common_client/test/data_sources/streaming_data_source_test.dart @@ -16,8 +16,11 @@ import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart' as ld_common; import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; import 'package:http/http.dart' as http; +import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; +class MockLogAdapter extends Mock implements LDLogAdapter {} + class MockSseClient implements SSEClient { final Stream mockStream; @@ -36,18 +39,17 @@ class MockSseClient implements SSEClient { bool hasCapability(SSECapability capability) => true; } -( - StreamingDataSource, - FlagManager, - DataSourceStatusManager -) makeDataSourceForTest(Stream mockStream, - {LDContext? inContext, - HttpProperties? inProperties, - bool useReport = false, - bool withReasons = false, - Duration? testingInterval, - MockClient? mockHttpClient, - Function(Uri, HttpProperties, String?, SseHttpMethod?)? factoryCallback}) { +(StreamingDataSource, FlagManager, DataSourceStatusManager) + makeDataSourceForTest(Stream mockStream, + {LDContext? inContext, + HttpProperties? inProperties, + bool useReport = false, + bool withReasons = false, + Duration? testingInterval, + MockClient? mockHttpClient, + // Receives the arguments that the builder received. + Function(Uri, Map, String?, SseHttpMethod?)? + factoryCallback}) { final context = inContext ?? LDContextBuilder().kind('user', 'test').build(); // We are not testing the data source status manager here, so we just want a // fixed time to make events easy to get. @@ -77,9 +79,13 @@ class MockSseClient implements SSEClient { ? (httpProps) => ld_common.HttpClient( client: mockHttpClient, httpProperties: httpProps) : null, - clientFactory: (Uri uri, HttpProperties properties, String? body, - SseHttpMethod? method, EventSourceLogger? logger) { - factoryCallback?.call(uri, properties, body, method); + eventSource: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + uriProvider}) { + factoryCallback?.call(uri, headers, body, httpMethod); return client; }); @@ -110,7 +116,7 @@ void main() { test('it uses the correct URL without reasons', () { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest( - controller.stream, factoryCallback: (uri, properties, body, method) { + controller.stream, factoryCallback: (uri, headers, body, method) { expect(uri.toString(), 'https://clientstream.launchdarkly.com/meval/eyJrZXkiOiJ0ZXN0Iiwia2luZCI6InVzZXIifQ=='); }); @@ -127,7 +133,7 @@ void main() { test('is includes no body when not using REPORT', () { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest( - controller.stream, factoryCallback: (uri, properties, body, method) { + controller.stream, factoryCallback: (uri, headers, body, method) { expect(method, SseHttpMethod.get); expect(body, isNull); }); @@ -144,7 +150,7 @@ void main() { test('is includes a body when using REPORT', () { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest( - controller.stream, factoryCallback: (uri, properties, body, method) { + controller.stream, factoryCallback: (uri, headers, body, method) { expect(body, '{"key":"test","kind":"user"}'); expect(method, SseHttpMethod.report); }, useReport: true); @@ -158,10 +164,27 @@ void main() { controller.sink.add(MessageEvent('put', '{}', null)); }); + test('it passes the base headers to the client', () { + final controller = StreamController(); + final (dataSource, _, _) = makeDataSourceForTest(controller.stream, + inProperties: HttpProperties(baseHeaders: { + 'X-LaunchDarkly-Tags': 'application-id/app', + 'x-custom': 'value', + }), factoryCallback: (uri, headers, body, method) { + // This platform has no CORS check, so every header is sent. + expect( + headers, containsPair('X-LaunchDarkly-Tags', 'application-id/app')); + expect(headers, containsPair('x-custom', 'value')); + }); + + dataSource.start(); + dataSource.stop(); + }); + test('it uses the correct URL without reasons with REPORT', () { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest( - controller.stream, factoryCallback: (uri, properties, body, method) { + controller.stream, factoryCallback: (uri, headers, body, method) { expect(uri.toString(), 'https://clientstream.launchdarkly.com/meval'); }, useReport: true); @@ -178,7 +201,7 @@ void main() { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest(controller.stream, withReasons: true, - factoryCallback: (uri, properties, body, method) { + factoryCallback: (uri, headers, body, method) { expect(uri.toString(), 'https://clientstream.launchdarkly.com/meval/eyJrZXkiOiJ0ZXN0Iiwia2luZCI6InVzZXIifQ==?withReasons=true'); }); @@ -196,7 +219,7 @@ void main() { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest(controller.stream, withReasons: true, - factoryCallback: (uri, properties, body, method) { + factoryCallback: (uri, headers, body, method) { expect(uri.toString(), 'https://clientstream.launchdarkly.com/meval?withReasons=true'); }, useReport: true); @@ -216,7 +239,7 @@ void main() { final controller = StreamController(onCancel: () => cancelled = true); final (dataSource, _, _) = makeDataSourceForTest(controller.stream, - withReasons: true, factoryCallback: (uri, properties, body, method) {}); + withReasons: true, factoryCallback: (uri, headers, body, method) {}); dataSource.start(); dataSource.stop(); @@ -570,4 +593,48 @@ void main() { expect(flagManager.environmentId, isNull); }); }); + + group('client builder selection', () { + StreamingDataSource make( + {SseClientBuilder? eventSource, + bool useReport = false, + LDLogger? logger}) => + StreamingDataSource( + credential: 'dummy-key', + context: LDContextBuilder().kind('user', 'test').build(), + endpoints: ServiceEndpoints(), + logger: logger ?? LDLogger(level: LDLogLevel.none), + dataSourceConfig: StreamingDataSourceConfig(useReport: useReport), + pollingDataSourceConfig: PollingDataSourceConfig(), + httpProperties: HttpProperties(), + eventSource: eventSource); + + setUpAll(() { + registerFallbackValue(LDLogRecord( + level: LDLogLevel.debug, + message: '', + time: DateTime.now(), + logTag: '')); + }); + + test('it uses the default SSE client without a supplied builder', () { + expect(make().eventSource, same(SSEClient.new)); + }); + + test('it uses the supplied SSE client builder', () { + expect( + make(eventSource: SSEClient.http).eventSource, same(SSEClient.http)); + }); + + test('it does not warn about REPORT on a platform that supports it', () { + final adapter = MockLogAdapter(); + when(() => adapter.log(any())).thenReturn(null); + + make( + useReport: true, + logger: LDLogger(adapter: adapter, level: LDLogLevel.debug)); + + verifyNever(() => adapter.log(any())); + }); + }); } diff --git a/packages/common_client/test/default_data_source_factories_test.dart b/packages/common_client/test/default_data_source_factories_test.dart new file mode 100644 index 00000000..4c3255ed --- /dev/null +++ b/packages/common_client/test/default_data_source_factories_test.dart @@ -0,0 +1,40 @@ +import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; +import 'package:launchdarkly_common_client/src/data_sources/streaming_data_source.dart'; +import 'package:launchdarkly_common_client/src/ld_common_client.dart' + show defaultDataSourceFactories; +import 'package:test/test.dart'; + +final class TestConfig extends LDCommonConfig { + TestConfig(super.sdkCredential, super.autoEnvAttributes, {super.eventSource}); +} + +void main() { + group('defaultDataSourceFactories', () { + StreamingDataSource streamingSourceFor(TestConfig config) { + final factories = defaultDataSourceFactories( + config, LDLogger(level: LDLogLevel.none), HttpProperties()); + final context = LDContextBuilder().kind('user', 'test').build(); + final source = switch (factories[ConnectionMode.streaming]) { + final factory? => factory(context), + null => fail('no streaming factory'), + }; + return source as StreamingDataSource; + } + + test('the streaming source uses the default SSE client without the option', + () { + final source = + streamingSourceFor(TestConfig('key', AutoEnvAttributes.disabled)); + + expect(source.eventSource, same(SSEClient.new)); + }); + + test('the streaming source uses the supplied SSE client builder', () { + final source = streamingSourceFor(TestConfig( + 'key', AutoEnvAttributes.disabled, + eventSource: SSEClient.http)); + + expect(source.eventSource, same(SSEClient.http)); + }); + }); +}