From 40130136c2a2aa8483baf98cb6add0d8fe99e57d Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Mon, 2 Nov 2026 15:08:11 -0500 Subject: [PATCH 1/9] feat: Add a public SSE client factory option --- .../lib/launchdarkly_common_client.dart | 10 ++ .../lib/src/config/defaults/io_config.dart | 3 + .../lib/src/config/defaults/js_config.dart | 4 + .../lib/src/config/defaults/stub_config.dart | 3 + .../src/data_sources/fdv2/data_system.dart | 13 +- .../data_sources/fdv2/entry_factories.dart | 84 ++++++------ .../src/data_sources/sse_client_factory.dart | 87 ++++++++++++ .../data_sources/streaming_data_source.dart | 126 +++++++++++------- .../lib/src/ld_common_client.dart | 4 +- .../lib/src/ld_common_config.dart | 13 +- .../fdv2/entry_factories_test.dart | 86 ++++++++---- .../data_sources/sse_client_factory_test.dart | 27 ++++ .../streaming_data_source_test.dart | 53 +++++++- .../test/event_source_factory_test.dart | 77 +++++++++++ 14 files changed, 457 insertions(+), 133 deletions(-) create mode 100644 packages/common_client/lib/src/data_sources/sse_client_factory.dart create mode 100644 packages/common_client/test/data_sources/sse_client_factory_test.dart create mode 100644 packages/common_client/test/event_source_factory_test.dart diff --git a/packages/common_client/lib/launchdarkly_common_client.dart b/packages/common_client/lib/launchdarkly_common_client.dart index 50a01e3e..253f53b4 100644 --- a/packages/common_client/lib/launchdarkly_common_client.dart +++ b/packages/common_client/lib/launchdarkly_common_client.dart @@ -6,6 +6,16 @@ export 'src/ld_common_config.dart' AutoEnvAttributes, PollingConfig; +export 'src/data_sources/sse_client_factory.dart' + show SSEClientFactory, SSEClientRequest; +export 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart' + show + SSEClient, + SSECapability, + SseHttpMethod, + SseHttpError, + EventSourceLogger; + 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/defaults/io_config.dart b/packages/common_client/lib/src/config/defaults/io_config.dart index 1fb4a911..2048f5c4 100644 --- a/packages/common_client/lib/src/config/defaults/io_config.dart +++ b/packages/common_client/lib/src/config/defaults/io_config.dart @@ -65,4 +65,7 @@ final class DefaultDataSourceConfig { /// The streaming transport can send a POST 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..9327cf64 100644 --- a/packages/common_client/lib/src/config/defaults/js_config.dart +++ b/packages/common_client/lib/src/config/defaults/js_config.dart @@ -74,4 +74,8 @@ final class DefaultDataSourceConfig { /// The browser EventSource 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..973b1e16 100644 --- a/packages/common_client/lib/src/config/defaults/stub_config.dart +++ b/packages/common_client/lib/src/config/defaults/stub_config.dart @@ -65,4 +65,7 @@ final class DefaultDataSourceConfig { 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..a4f708e5 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 @@ -8,6 +8,7 @@ import '../../config/service_endpoints.dart'; import '../../fdv2_connection_mode.dart'; import '../data_source_manager.dart'; import '../data_source_status_manager.dart'; +import '../sse_client_factory.dart'; import 'built_in_modes.dart'; import 'cache_initializer.dart'; import 'entry_factories.dart'; @@ -40,7 +41,7 @@ final class FDv2DataSystem { final DataSourceStatusManager _statusManager; final Map _connectionModeOverrides; final CachedFlagsReader _cachedFlagsReader; - final FDv2SseClientFactory _sseClientFactory; + final SSEClientFactory? _sseClientFactory; final HttpClientFactory? _httpClientFactory; Selector _selector = Selector.empty; @@ -55,10 +56,11 @@ final class FDv2DataSystem { required Duration defaultPollingInterval, required DataSourceStatusManager statusManager, required CachedFlagsReader cachedFlagsReader, - FDv2SseClientFactory sseClientFactory = defaultSseClientFactory, + SSEClientFactory? sseClientFactory, 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 transport can send a POST request. Defaults to + // the platform's capability. With a custom client, the data source checks + // each client instead. Tests override it. bool? streamingPostSupported, }) : _credential = credential, _logger = logger, @@ -67,7 +69,8 @@ final class FDv2DataSystem { _withReasons = withReasons, _usePost = config.usePost, _streamingPostSupported = streamingPostSupported ?? - DefaultConfig.dataSourceConfig.streamingPostSupported, + (sseClientFactory != null || + DefaultConfig.dataSourceConfig.streamingPostSupported), _defaultPollingInterval = defaultPollingInterval, _statusManager = statusManager, _cachedFlagsReader = cachedFlagsReader, 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..21291da1 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 '../sse_client_factory.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,21 +84,35 @@ 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, +/// Builds the [SSEClient] for a streaming source. +/// +/// When the context travels in a POST body, the client must report +/// [SSECapability.customMethod]. Without it, this logs a warning, closes the +/// client, and builds a new client that uses GET. +SSEClient _buildSseClient({ + required SSEClientFactory factory, + required bool customFactory, + required SourceFactoryContext ctx, + required Uri Function() Function(bool usePost) uriProviderFor, }) { - return SSEClient(uriProvider(), _fdv2StreamEventNames, - headers: httpProperties.baseHeaders, - body: body, - httpMethod: method, - logger: logger, - uriProvider: uriProvider); + SSEClient build(bool usePost) => factory(SSEClientRequest( + uriProvider: uriProviderFor(usePost), + eventTypes: _fdv2StreamEventNames, + headers: streamingRequestHeaders(ctx.httpProperties, + customFactory: customFactory), + body: usePost ? ctx.contextJson : null, + method: usePost ? SseHttpMethod.post : SseHttpMethod.get, + logger: LDLoggerToEventSourceAdapter(ctx.logger), + )); + + final client = build(ctx.usePost); + if (ctx.usePost && !client.hasCapability(SSECapability.customMethod)) { + ctx.logger.warn( + 'The SSE client cannot send POST requests. Streaming with GET instead.'); + client.close(); + return build(false); + } + return client; } /// Builds the streaming URI for the current state. Invoked per @@ -202,7 +206,7 @@ InitializerFactory createInitializerFactoryFromEntry( SynchronizerFactory createSynchronizerFactoryFromEntry( mode.SynchronizerEntry entry, SourceFactoryContext ctx, { - FDv2SseClientFactory sseClientFactory = defaultSseClientFactory, + SSEClientFactory? sseClientFactory, }) { switch (entry) { case final mode.PollingSynchronizer e: @@ -227,20 +231,18 @@ SynchronizerFactory createSynchronizerFactoryFromEntry( create: (SelectorGetter selectorGetter) { final endpointsResolved = mergeServiceEndpoints(ctx.serviceEndpoints, e.endpoints); - Uri uriProvider() => _buildStreamingUri( - endpoints: endpointsResolved, - contextEncoded: base64UrlEncode(utf8.encode(ctx.contextJson)), - usePost: ctx.usePost, - withReasons: ctx.withReasons, - 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 = _buildSseClient( + factory: sseClientFactory ?? defaultSseClientFactory, + customFactory: sseClientFactory != null, + ctx: ctx, + uriProviderFor: (usePost) => () => _buildStreamingUri( + endpoints: endpointsResolved, + contextEncoded: base64UrlEncode(utf8.encode(ctx.contextJson)), + usePost: usePost, + withReasons: ctx.withReasons, + basis: selectorGetter(), + additionalQueryParameters: ctx.additionalQueryParameters, + ), ); // Legacy ping events trigger a one-shot poll. @@ -278,7 +280,7 @@ List buildInitializerFactories( List buildSynchronizerFactories( List entries, SourceFactoryContext ctx, { - FDv2SseClientFactory sseClientFactory = defaultSseClientFactory, + SSEClientFactory? sseClientFactory, }) { return entries .map((e) => createSynchronizerFactoryFromEntry(e, ctx, diff --git a/packages/common_client/lib/src/data_sources/sse_client_factory.dart b/packages/common_client/lib/src/data_sources/sse_client_factory.dart new file mode 100644 index 00000000..6523636f --- /dev/null +++ b/packages/common_client/lib/src/data_sources/sse_client_factory.dart @@ -0,0 +1,87 @@ +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'; + +/// The details of a streaming connection that the SDK asks an +/// [SSEClientFactory] to create. +/// +/// The SDK adds fields to this class over time. A factory that reads only +/// the fields it needs keeps working when a field is added. +final class SSEClientRequest { + /// Returns the URI for the next connection attempt. The SDK calls this + /// before the first connection and before every reconnection, because + /// the query parameters can change between attempts. + final Uri Function() uriProvider; + + /// The names of the events that the client must emit. + final Set eventTypes; + + /// The HTTP headers for the connection request. + final Map headers; + + /// The request body, or null when the request has no body. + final String? body; + + /// The HTTP method for the connection request. A client that does not + /// report [SSECapability.customMethod] is not used with a method other + /// than `GET`. + final SseHttpMethod method; + + /// The logger for the client. + final EventSourceLogger logger; + + const SSEClientRequest({ + required this.uriProvider, + required this.eventTypes, + required this.headers, + required this.body, + required this.method, + required this.logger, + }); +} + +/// Creates the [SSEClient] that the SDK uses for streaming. +/// +/// The SDK calls the factory once for each streaming connection it needs. +/// The SDK closes the client it receives when it stops streaming. +/// +/// The SDK reads [SSEClient.hasCapability] on the returned client: +/// - Without [SSECapability.customMethod], the SDK logs a warning and +/// streams with `GET`, even when `POST` or `REPORT` is configured. +/// - Without [SSECapability.httpErrors], the SDK does not expect an +/// unrecoverable HTTP error on the stream, so every failure is retried. +/// +/// On web, the SDK removes the application tags header from the request, +/// because the CORS allow-list of the streaming service does not include it. +typedef SSEClientFactory = SSEClient Function(SSEClientRequest request); + +/// Creates the default [SSEClient] for the platform. +SSEClient defaultSseClientFactory(SSEClientRequest request) { + return SSEClient(request.uriProvider(), request.eventTypes, + headers: request.headers, + body: request.body, + httpMethod: request.method, + logger: request.logger, + uriProvider: request.uriProvider); +} + +const String _tagsHeader = 'x-launchdarkly-tags'; + +/// Returns the headers for a streaming request. +/// +/// When the application supplied its own client ([customFactory]) on a +/// platform where the service rejects the tags header, the tags header is +/// removed. The default client on that platform sends no headers. +Map streamingRequestHeaders(HttpProperties httpProperties, + {required bool customFactory}) { + final headers = httpProperties.baseHeaders; + if (!customFactory || + DefaultConfig.dataSourceConfig.streamingTagsHeaderSupported) { + return headers; + } + return { + 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..c65f25fe 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 @@ -10,6 +10,7 @@ import 'data_source.dart'; import 'data_source_status.dart'; import 'get_environment_id.dart'; import 'requestor.dart'; +import 'sse_client_factory.dart'; const String _pingEvent = 'ping'; const String _patchEvent = 'patch'; @@ -18,22 +19,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,20 +28,35 @@ final class StreamingDataSource implements DataSource { final StreamingDataSourceConfig _dataSourceConfig; - final SseClientFactory _clientFactory; + final SSEClientFactory _clientFactory; + + /// Whether the application supplied the SSE client factory. + final bool _customFactory; + + /// The configured request method, before the capabilities of the client + /// are known. + late final bool _wantReport; + + late final String _plainContextString; + + late final ServiceEndpoints _endpoints; + + late final PollingDataSourceConfig _pollingDataSourceConfig; - late final Uri _uri; + late final HttpClientFactory _httpClientFactory; + + late Uri _uri; late final HttpProperties _httpProperties; - late final String _contextString; + late String _contextString; bool _stopped = false; StreamSubscription? _subscription; final StreamController _dataController = StreamController(); - late final bool _useReport; + late bool _useReport; SSEClient? _client; @@ -64,7 +64,7 @@ final class StreamingDataSource implements DataSource { final String _credential; - late final Requestor _requestor; + late Requestor _requestor; @override Stream get events => _dataController.stream; @@ -72,10 +72,9 @@ 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 [clientFactory] parameter supplies a customized SSE client. When it + /// is given, the data source sends a REPORT request if the client reports + /// [SSECapability.customMethod], whatever the platform default is. /// The [httpClientFactory] parameter is primarily intended for testing the /// requestor used for ping events. StreamingDataSource( @@ -86,34 +85,48 @@ final class StreamingDataSource implements DataSource { required StreamingDataSourceConfig dataSourceConfig, required PollingDataSourceConfig pollingDataSourceConfig, required HttpProperties httpProperties, - SseClientFactory clientFactory = _defaultClientFactory, + SSEClientFactory? clientFactory, HttpClientFactory? httpClientFactory}) : _logger = logger.subLogger('StreamingDataSource'), _dataSourceConfig = dataSourceConfig, - _clientFactory = clientFactory, + _clientFactory = clientFactory ?? defaultSseClientFactory, + _customFactory = clientFactory != null, _httpProperties = httpProperties, _credential = credential { - final plainContextString = + _plainContextString = jsonEncode(LDContextSerialization.toJson(context, isEvent: false)); + _endpoints = endpoints; + _pollingDataSourceConfig = pollingDataSourceConfig; + _httpClientFactory = httpClientFactory ?? _defaultHttpClientFactory; + // With a custom client, the capabilities of the client decide in start. + // Without one, the platform decides. if (_dataSourceConfig.useReport && + !_customFactory && !DefaultConfig.dataSourceConfig.streamingReportSupported) { _logger.warn( 'REPORT is currently not supported for streaming on web targets'); } - _useReport = _dataSourceConfig.useReport && - DefaultConfig.dataSourceConfig.streamingReportSupported; + _wantReport = _dataSourceConfig.useReport && + (_customFactory || + DefaultConfig.dataSourceConfig.streamingReportSupported); + + _configureRequest(_wantReport); + } - _contextString = _useReport - ? plainContextString - : base64UrlEncode(utf8.encode(plainContextString)); + /// Sets the URI and the ping requestor for the request method. + void _configureRequest(bool useReport) { + _useReport = useReport; + _contextString = useReport + ? _plainContextString + : base64UrlEncode(utf8.encode(_plainContextString)); - final path = _useReport - ? _dataSourceConfig.streamingReportPath(credential, _contextString) - : _dataSourceConfig.streamingGetPath(credential, _contextString); + final path = useReport + ? _dataSourceConfig.streamingReportPath(_credential, _contextString) + : _dataSourceConfig.streamingGetPath(_credential, _contextString); - String completeUrl = appendPath(endpoints.streaming, path); + String completeUrl = appendPath(_endpoints.streaming, path); if (_dataSourceConfig.withReasons) { completeUrl = '$completeUrl?withReasons=true'; @@ -122,14 +135,26 @@ final class StreamingDataSource implements DataSource { _uri = Uri.parse(completeUrl); _requestor = Requestor( - logger: logger, + logger: _logger, contextString: _contextString, - method: _useReport ? RequestMethod.report : RequestMethod.get, - httpProperties: httpProperties, - dataSourceConfig: pollingDataSourceConfig, - endpoints: endpoints, + method: useReport ? RequestMethod.report : RequestMethod.get, + httpProperties: _httpProperties, + dataSourceConfig: _pollingDataSourceConfig, + endpoints: _endpoints, credential: _credential, - httpClientFactory: httpClientFactory ?? _defaultHttpClientFactory); + httpClientFactory: _httpClientFactory); + } + + SSEClient _buildClient() { + final headers = + streamingRequestHeaders(_httpProperties, customFactory: _customFactory); + return _clientFactory(SSEClientRequest( + uriProvider: () => _uri, + eventTypes: const {_putEvent, _patchEvent, _delete, _pingEvent}, + headers: headers, + body: _useReport ? _contextString : null, + method: _useReport ? SseHttpMethod.report : SseHttpMethod.get, + logger: LDLoggerToEventSourceAdapter(_logger))); } @override @@ -139,12 +164,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)); + var client = _buildClient(); + if (_wantReport && !client.hasCapability(SSECapability.customMethod)) { + _logger.warn( + 'The SSE client cannot send REPORT requests. Streaming with GET instead.'); + client.close(); + _configureRequest(false); + client = _buildClient(); + } + _client = client; _subscription = _client!.stream.listen((event) async { if (_stopped) { diff --git a/packages/common_client/lib/src/ld_common_client.dart b/packages/common_client/lib/src/ld_common_client.dart index bd8c496c..2c7d0de8 100644 --- a/packages/common_client/lib/src/ld_common_client.dart +++ b/packages/common_client/lib/src/ld_common_client.dart @@ -100,7 +100,8 @@ Map _defaultFactories( dataSourceConfig: StreamingDataSourceConfig( useReport: useReport, withReasons: withReasons), pollingDataSourceConfig: foregroundPollingConfig, - httpProperties: httpProperties); + httpProperties: httpProperties, + clientFactory: config.eventSourceFactory); } return { @@ -446,6 +447,7 @@ final class LDCommonClient { _config.dataSourceConfig.polling.pollingInterval, statusManager: _dataSourceStatusManager, cachedFlagsReader: _flagManager.readCached, + sseClientFactory: _config.eventSourceFactory, ); _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..a77c81ee 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/sse_client_factory.dart'; import 'hooks/hook.dart'; import 'config/data_system_config.dart'; import 'config/defaults/default_config.dart'; @@ -159,6 +160,15 @@ abstract class LDCommonConfig { /// https://launchdarkly.com/docs/sdk/features/data-saving-mode final DataSystemConfig? dataSystem; + /// Supplies the SSE client that the SDK uses for streaming. When it is not + /// set, the SDK uses the default client for the platform. + /// + /// This option is for applications with a specific need. For example, on + /// web the default client is the browser `EventSource`. It cannot send a + /// request body or report an HTTP error. A factory that returns + /// `SSEClient.http` removes these limits. Most applications do not need it. + final SSEClientFactory? eventSourceFactory; + LDCommonConfig(this.sdkCredential, this.autoEnvAttributes, {this.applicationInfo, HttpProperties? httpProperties, @@ -171,7 +181,8 @@ abstract class LDCommonConfig { bool? allAttributesPrivate, List? globalPrivateAttributes, List? hooks, - this.dataSystem}) + this.dataSystem, + this.eventSourceFactory}) : httpProperties = httpProperties ?? HttpProperties(), serviceEndpoints = serviceEndpoints ?? ServiceEndpoints(), events = events ?? EventsConfig(), 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..8a029dab 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,9 @@ 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 {}); + sseClientFactory: (request) { + capturedUriProvider = request.uriProvider; + return SSEClient.testClient(request.uriProvider(), const {}); }, ); final sync = factory.create(() => selector); @@ -203,15 +197,9 @@ 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 {}); + sseClientFactory: (request) { + capturedUriProvider = request.uriProvider; + return SSEClient.testClient(request.uriProvider(), const {}); }, ); final sync = factory.create(() => selector); @@ -348,17 +336,11 @@ 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; - capturedBody = body; - capturedUriProvider = uriProvider; - return SSEClient.testClient(uriProvider(), const {}); + sseClientFactory: (request) { + capturedMethod = request.method; + capturedBody = request.body; + capturedUriProvider = request.uriProvider; + return SSEClient.testClient(request.uriProvider(), const {}); }, ); factory.create(_selectorGetter).close(); @@ -369,6 +351,52 @@ void main() { ); } + test( + 'the streaming connection falls back to GET when the client cannot ' + 'send POST', () { + final created = <({SseHttpMethod method, String? body, Uri uri})>[]; + final clients = []; + final factory = createSynchronizerFactoryFromEntry( + StreamingSynchronizer(), + factoryContext(usePost: true), + sseClientFactory: (request) { + created.add(( + method: request.method, + body: request.body, + uri: request.uriProvider() + )); + final client = SSEClient.testClient(request.uriProvider(), const {}, + capabilities: const {SSECapability.requestHeaders}); + clients.add(client); + return client; + }, + ); + factory.create(_selectorGetter).close(); + + expect(created, hasLength(2)); + expect(created.first.method, equals(SseHttpMethod.post)); + expect(created.last.method, equals(SseHttpMethod.get)); + expect(created.last.body, isNull); + expect(created.last.uri.path, startsWith('/sdk/stream/eval/')); + expect(clients.first.isClosed, isTrue); + }); + + test('the streaming connection keeps POST when the client can send it', () { + var created = 0; + final factory = createSynchronizerFactoryFromEntry( + StreamingSynchronizer(), + factoryContext(usePost: true), + sseClientFactory: (request) { + created++; + return SSEClient.testClient(request.uriProvider(), const {}, + capabilities: const {SSECapability.customMethod}); + }, + ); + factory.create(_selectorGetter).close(); + + expect(created, equals(1)); + }); + test('the streaming connection uses POST with the context as the body', () { final connection = connectStream(usePost: true); diff --git a/packages/common_client/test/data_sources/sse_client_factory_test.dart b/packages/common_client/test/data_sources/sse_client_factory_test.dart new file mode 100644 index 00000000..9ea82db6 --- /dev/null +++ b/packages/common_client/test/data_sources/sse_client_factory_test.dart @@ -0,0 +1,27 @@ +import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; +import 'package:launchdarkly_common_client/src/data_sources/sse_client_factory.dart'; +import 'package:test/test.dart'; + +void main() { + group('streamingRequestHeaders', () { + final properties = HttpProperties(baseHeaders: { + 'X-LaunchDarkly-Tags': 'application-id/app', + 'x-launchdarkly-user-agent': 'agent', + }); + + test('keeps every header when the platform accepts the tags header', () { + // The test platform is not web, so the service accepts the header. + expect( + streamingRequestHeaders(properties, customFactory: true), + equals({ + 'X-LaunchDarkly-Tags': 'application-id/app', + 'x-launchdarkly-user-agent': 'agent', + })); + }); + + test('keeps every header when no custom factory is set', () { + expect(streamingRequestHeaders(properties, customFactory: false), + equals(properties.baseHeaders)); + }); + }); +} 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..3b397a18 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 @@ -20,11 +20,15 @@ import 'package:test/test.dart'; class MockSseClient implements SSEClient { final Stream mockStream; + final bool supportsCustomMethod; + bool closed = false; - MockSseClient(this.mockStream); + MockSseClient(this.mockStream, {this.supportsCustomMethod = true}); @override - Future close() async {} + Future close() async { + closed = true; + } @override void restart() {} @@ -33,7 +37,8 @@ class MockSseClient implements SSEClient { Stream get stream => mockStream; @override - bool hasCapability(SSECapability capability) => true; + bool hasCapability(SSECapability capability) => + capability != SSECapability.customMethod || supportsCustomMethod; } ( @@ -47,6 +52,8 @@ class MockSseClient implements SSEClient { bool withReasons = false, Duration? testingInterval, MockClient? mockHttpClient, + bool supportsCustomMethod = true, + MockSseClient? clientOverride, Function(Uri, HttpProperties, 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 @@ -56,7 +63,8 @@ class MockSseClient implements SSEClient { final logger = LDLogger(); final properties = inProperties ?? HttpProperties(); - final client = MockSseClient(mockStream); + final client = clientOverride ?? + MockSseClient(mockStream, supportsCustomMethod: supportsCustomMethod); const sdkKey = 'dummy-key'; final flagManager = FlagManager(sdkKey: sdkKey, logger: logger, maxCachedContexts: 5); @@ -77,9 +85,9 @@ 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); + clientFactory: (request) { + factoryCallback?.call( + request.uriProvider(), properties, request.body, request.method); return client; }); @@ -158,6 +166,37 @@ void main() { controller.sink.add(MessageEvent('put', '{}', null)); }); + test('it falls back to GET when the client cannot send REPORT', () { + final calls = <(Uri, String?, SseHttpMethod?)>[]; + final controller = StreamController(); + final (dataSource, _, _) = makeDataSourceForTest(controller.stream, + factoryCallback: (uri, properties, body, method) => + calls.add((uri, body, method)), + useReport: true, + supportsCustomMethod: false); + + dataSource.start(); + + expect(calls, hasLength(2)); + expect(calls.first.$3, SseHttpMethod.report); + expect(calls.last.$3, SseHttpMethod.get); + expect(calls.last.$2, isNull); + expect(calls.last.$1.toString(), + 'https://clientstream.launchdarkly.com/meval/eyJrZXkiOiJ0ZXN0Iiwia2luZCI6InVzZXIifQ=='); + }); + + test('it keeps REPORT when the client can send it', () { + final calls = []; + final controller = StreamController(); + final (dataSource, _, _) = makeDataSourceForTest(controller.stream, + factoryCallback: (uri, properties, body, method) => calls.add(method), + useReport: true); + + dataSource.start(); + + expect(calls, [SseHttpMethod.report]); + }); + test('it uses the correct URL without reasons with REPORT', () { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest( diff --git a/packages/common_client/test/event_source_factory_test.dart b/packages/common_client/test/event_source_factory_test.dart new file mode 100644 index 00000000..0aee3126 --- /dev/null +++ b/packages/common_client/test/event_source_factory_test.dart @@ -0,0 +1,77 @@ +import 'dart:async'; + +import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; +import 'package:test/test.dart'; + +import 'mock_eventprocessor.dart'; + +final class _TestConfig extends LDCommonConfig { + _TestConfig(super.sdkCredential, super.autoEnvAttributes, + {super.dataSystem, super.eventSourceFactory, super.serviceEndpoints}); +} + +LDCommonClient _makeClient(LDCommonConfig config) => LDCommonClient( + config, + CommonPlatform(), + LDContextBuilder().kind('user', 'bob').build(), + DiagnosticSdkData(name: '', version: ''), + eventProcessorFactory: ({ + required allAttributesPrivate, + required analyticsEventsPath, + required client, + required diagnosticEventsPath, + required diagnosticRecordingInterval, + diagnosticsManager, + required endpoints, + required eventCapacity, + required flushInterval, + required globalPrivateAttributes, + required indexEvents, + required logger, + }) => + MockEventProcessor()); + +void main() { + // The streaming endpoint is unreachable so a test never leaves the machine. + final endpoints = ServiceEndpoints.custom( + polling: 'http://localhost:1', + streaming: 'http://localhost:1', + events: 'http://localhost:1'); + + Future> startAndCollect( + LDCommonConfig Function(SSEClientFactory factory) makeConfig) async { + final requests = []; + final client = _makeClient(makeConfig((request) { + requests.add(request); + return SSEClient.testClient(request.uriProvider(), request.eventTypes); + })); + unawaited(client.start()); + // Streaming starts after the identify that start performs. + await Future.delayed(const Duration(milliseconds: 200)); + await client.close(); + return requests; + } + + test('the FDv1 streaming data source uses the configured factory', () async { + final requests = await startAndCollect((factory) => _TestConfig( + 'client-side-id', AutoEnvAttributes.disabled, + serviceEndpoints: endpoints, eventSourceFactory: factory)); + + expect(requests, isNotEmpty); + expect(requests.first.eventTypes, containsAll(['put', 'patch', 'delete'])); + }); + + test('the FDv2 streaming data source uses the configured factory', () async { + final requests = await startAndCollect( + (factory) => _TestConfig('client-side-id', AutoEnvAttributes.disabled, + serviceEndpoints: endpoints, + dataSystem: DataSystemConfig(connectionModes: { + ConnectionModeId.streaming: const ModeDefinition( + initializers: [], synchronizers: [StreamingSynchronizer()]), + }), + eventSourceFactory: factory)); + + expect(requests, isNotEmpty); + expect(requests.first.eventTypes, contains('server-intent')); + }); +} From 68f6d10a1098c8c227c828b19dd22ab0eece9a37 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Wed, 4 Nov 2026 14:43:34 -0500 Subject: [PATCH 2/9] fix: Keep the ping poll method after the SSE fallback and contain SSE client failures --- .github/actions/ci/action.yml | 9 + .../lib/launchdarkly_common_client.dart | 5 +- .../lib/src/config/defaults/io_config.dart | 2 - .../lib/src/config/defaults/js_config.dart | 2 - .../lib/src/config/defaults/stub_config.dart | 2 - .../data_sources/fdv2/entry_factories.dart | 64 ++---- .../src/data_sources/sse_client_factory.dart | 87 ++++++-- .../data_sources/streaming_data_source.dart | 189 +++++++++--------- .../data_sources/sse_client_factory_test.dart | 18 +- .../sse_client_factory_web_test.dart | 99 +++++++++ .../streaming_data_source_test.dart | 114 ++++++++++- .../test/event_source_factory_test.dart | 6 +- 12 files changed, 417 insertions(+), 180 deletions(-) create mode 100644 packages/common_client/test/data_sources/sse_client_factory_web_test.dart diff --git a/.github/actions/ci/action.yml b/.github/actions/ci/action.yml index df40625f..5552f24f 100644 --- a/.github/actions/ci/action.yml +++ b/.github/actions/ci/action.yml @@ -71,6 +71,15 @@ 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 + # The SSE client factory makes decisions that only apply on web: it + # removes the tags header and keeps streaming with a custom client. + # The Dart VM cannot run that code, so these tests run on Chrome. + run: | + cd packages/common_client + dart test test/data_sources/sse_client_factory_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 253f53b4..8ed0478c 100644 --- a/packages/common_client/lib/launchdarkly_common_client.dart +++ b/packages/common_client/lib/launchdarkly_common_client.dart @@ -14,7 +14,10 @@ export 'package:launchdarkly_event_source_client/launchdarkly_event_source_clien SSECapability, SseHttpMethod, SseHttpError, - EventSourceLogger; + EventSourceLogger, + Event, + MessageEvent, + OpenEvent; export 'src/config/data_system_config.dart' show DataSystemConfig, ConnectionModeId; 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 2048f5c4..7ff8105d 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,6 @@ final class DefaultDataSourceConfig { ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming; - bool get streamingReportSupported => true; - /// The streaming transport can send a POST request with a body. bool get streamingPostSupported => 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 9327cf64..4663f395 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,6 @@ final class DefaultDataSourceConfig { ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming; - bool get streamingReportSupported => false; - /// The browser EventSource can only send GET requests without a body. bool get streamingPostSupported => 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 973b1e16..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,8 +62,6 @@ 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 => 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 21291da1..18e033e9 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 @@ -84,37 +84,6 @@ const Set _fdv2StreamEventNames = { 'ping', }; -/// Builds the [SSEClient] for a streaming source. -/// -/// When the context travels in a POST body, the client must report -/// [SSECapability.customMethod]. Without it, this logs a warning, closes the -/// client, and builds a new client that uses GET. -SSEClient _buildSseClient({ - required SSEClientFactory factory, - required bool customFactory, - required SourceFactoryContext ctx, - required Uri Function() Function(bool usePost) uriProviderFor, -}) { - SSEClient build(bool usePost) => factory(SSEClientRequest( - uriProvider: uriProviderFor(usePost), - eventTypes: _fdv2StreamEventNames, - headers: streamingRequestHeaders(ctx.httpProperties, - customFactory: customFactory), - body: usePost ? ctx.contextJson : null, - method: usePost ? SseHttpMethod.post : SseHttpMethod.get, - logger: LDLoggerToEventSourceAdapter(ctx.logger), - )); - - final client = build(ctx.usePost); - if (ctx.usePost && !client.hasCapability(SSECapability.customMethod)) { - ctx.logger.warn( - 'The SSE client cannot send POST requests. Streaming with GET instead.'); - client.close(); - return build(false); - } - return client; -} - /// Builds the streaming URI for the current state. Invoked per /// connection attempt so the `basis` parameter tracks the selector. Uri _buildStreamingUri({ @@ -231,18 +200,27 @@ SynchronizerFactory createSynchronizerFactoryFromEntry( create: (SelectorGetter selectorGetter) { final endpointsResolved = mergeServiceEndpoints(ctx.serviceEndpoints, e.endpoints); - final sseClient = _buildSseClient( - factory: sseClientFactory ?? defaultSseClientFactory, - customFactory: sseClientFactory != null, - ctx: ctx, - uriProviderFor: (usePost) => () => _buildStreamingUri( - endpoints: endpointsResolved, - contextEncoded: base64UrlEncode(utf8.encode(ctx.contextJson)), - usePost: usePost, - withReasons: ctx.withReasons, - basis: selectorGetter(), - additionalQueryParameters: ctx.additionalQueryParameters, - ), + // A client without the custom method capability streams with GET. + // The ping poll below keeps the configured method. + final (sseClient, _) = createSseClient( + factory: sseClientFactory, + useCustomMethod: ctx.usePost, + logger: ctx.logger, + requestFor: (usePost) => SSEClientRequest( + uriProvider: () => _buildStreamingUri( + endpoints: endpointsResolved, + contextEncoded: base64UrlEncode(utf8.encode(ctx.contextJson)), + usePost: usePost, + withReasons: ctx.withReasons, + basis: selectorGetter(), + additionalQueryParameters: ctx.additionalQueryParameters, + ), + eventTypes: _fdv2StreamEventNames, + headers: streamingRequestHeaders(ctx.httpProperties), + body: usePost ? ctx.contextJson : null, + method: usePost ? SseHttpMethod.post : SseHttpMethod.get, + logger: LDLoggerToEventSourceAdapter(ctx.logger), + ), ); // Legacy ping events trigger a one-shot poll. diff --git a/packages/common_client/lib/src/data_sources/sse_client_factory.dart b/packages/common_client/lib/src/data_sources/sse_client_factory.dart index 6523636f..360663ca 100644 --- a/packages/common_client/lib/src/data_sources/sse_client_factory.dart +++ b/packages/common_client/lib/src/data_sources/sse_client_factory.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart'; import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; @@ -12,20 +14,22 @@ final class SSEClientRequest { /// Returns the URI for the next connection attempt. The SDK calls this /// before the first connection and before every reconnection, because /// the query parameters can change between attempts. + /// + /// With `GET`, the URI carries the evaluation context. Do not log it. final Uri Function() uriProvider; /// The names of the events that the client must emit. final Set eventTypes; - /// The HTTP headers for the connection request. + /// The HTTP headers for the connection request. They carry the SDK + /// credential. Do not log them. final Map headers; - /// The request body, or null when the request has no body. + /// The request body, or null when the request has no body. With `POST` or + /// `REPORT`, the body is the evaluation context. final String? body; - /// The HTTP method for the connection request. A client that does not - /// report [SSECapability.customMethod] is not used with a method other - /// than `GET`. + /// The HTTP method for the connection request. final SseHttpMethod method; /// The logger for the client. @@ -43,14 +47,17 @@ final class SSEClientRequest { /// Creates the [SSEClient] that the SDK uses for streaming. /// -/// The SDK calls the factory once for each streaming connection it needs. -/// The SDK closes the client it receives when it stops streaming. +/// The SDK calls the factory when it opens a streaming connection. When the +/// configured method is `POST` or `REPORT`, the SDK reads +/// [SSEClient.hasCapability] on the client it receives. Without +/// [SSECapability.customMethod], the SDK logs a warning, closes that client, +/// and calls the factory a second time with a `GET` request. The `GET` +/// request carries the evaluation context in the URI. +/// +/// Without [SSECapability.httpErrors], the SDK does not expect an +/// unrecoverable HTTP error on the stream, so every failure is retried. /// -/// The SDK reads [SSEClient.hasCapability] on the returned client: -/// - Without [SSECapability.customMethod], the SDK logs a warning and -/// streams with `GET`, even when `POST` or `REPORT` is configured. -/// - Without [SSECapability.httpErrors], the SDK does not expect an -/// unrecoverable HTTP error on the stream, so every failure is retried. +/// The SDK closes the client when it stops streaming. /// /// On web, the SDK removes the application tags header from the request, /// because the CORS allow-list of the streaming service does not include it. @@ -66,22 +73,60 @@ SSEClient defaultSseClientFactory(SSEClientRequest request) { uriProvider: request.uriProvider); } +/// Builds the client for a streaming connection. +/// +/// [requestFor] builds the request. Its argument says whether the request +/// uses the configured custom method, `POST` or `REPORT`. When +/// [useCustomMethod] is set and the client does not report +/// [SSECapability.customMethod], this logs a warning, closes that client, +/// and builds a `GET` client instead. +/// +/// Returns the client and whether it uses the custom method. +(SSEClient, bool) createSseClient({ + required SSEClientFactory? factory, + required SSEClientRequest Function(bool useCustomMethod) requestFor, + required bool useCustomMethod, + required LDLogger logger, +}) { + final build = factory ?? defaultSseClientFactory; + final request = requestFor(useCustomMethod); + final client = build(request); + if (!useCustomMethod || client.hasCapability(SSECapability.customMethod)) { + return (client, useCustomMethod); + } + logger.warn('The SSE client cannot send ${request.method} requests. ' + 'Streaming with GET instead.'); + closeSseClient(client, logger); + return (build(requestFor(false)), false); +} + +/// Closes [client]. A custom client can fail to close. The failure is +/// logged and does not reach the caller. +void closeSseClient(SSEClient client, LDLogger logger) { + void report(Object err) { + logger.warn('The SSE client failed to close: $err'); + } + + try { + unawaited(client.close().catchError(report)); + } catch (err) { + report(err); + } +} + const String _tagsHeader = 'x-launchdarkly-tags'; /// Returns the headers for a streaming request. /// -/// When the application supplied its own client ([customFactory]) on a -/// platform where the service rejects the tags header, the tags header is -/// removed. The default client on that platform sends no headers. -Map streamingRequestHeaders(HttpProperties httpProperties, - {required bool customFactory}) { +/// On a platform where the streaming service rejects the application tags +/// header, the tags header is removed. +Map streamingRequestHeaders(HttpProperties httpProperties) { final headers = httpProperties.baseHeaders; - if (!customFactory || - DefaultConfig.dataSourceConfig.streamingTagsHeaderSupported) { + if (DefaultConfig.dataSourceConfig.streamingTagsHeaderSupported) { return headers; } - return { + 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 c65f25fe..a8b239c2 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 @@ -28,53 +28,40 @@ final class StreamingDataSource implements DataSource { final StreamingDataSourceConfig _dataSourceConfig; - final SSEClientFactory _clientFactory; + final SSEClientFactory? _clientFactory; - /// Whether the application supplied the SSE client factory. - final bool _customFactory; + final String _plainContextString; - /// The configured request method, before the capabilities of the client - /// are known. - late final bool _wantReport; + final ServiceEndpoints _endpoints; - late final String _plainContextString; + final HttpProperties _httpProperties; - late final ServiceEndpoints _endpoints; - - late final PollingDataSourceConfig _pollingDataSourceConfig; - - late final HttpClientFactory _httpClientFactory; - - late Uri _uri; + final String _credential; - late final HttpProperties _httpProperties; + /// Polls for all flags when the stream sends a ping. Its method follows + /// the polling configuration, not the method of the stream. + final Requestor _requestor; - late String _contextString; bool _stopped = false; StreamSubscription? _subscription; final StreamController _dataController = StreamController(); - late bool _useReport; - SSEClient? _client; String? _environmentId; - final String _credential; - - late Requestor _requestor; - @override Stream get events => _dataController.stream; /// Used to track if there has been an unrecoverable error. bool _permanentShutdown = false; - /// The [clientFactory] parameter supplies a customized SSE client. When it - /// is given, the data source sends a REPORT request if the client reports - /// [SSECapability.customMethod], whatever the platform default is. + /// The [clientFactory] parameter supplies the SSE client. When it is not + /// set, the default client for the platform is used. When the + /// configuration asks for REPORT and the client does not report + /// [SSECapability.customMethod], the stream uses GET instead. /// The [httpClientFactory] parameter is primarily intended for testing the /// requestor used for ping events. StreamingDataSource( @@ -87,74 +74,92 @@ final class StreamingDataSource implements DataSource { required HttpProperties httpProperties, SSEClientFactory? clientFactory, HttpClientFactory? httpClientFactory}) - : _logger = logger.subLogger('StreamingDataSource'), + : this._( + credential: credential, + endpoints: endpoints, + logger: logger.subLogger('StreamingDataSource'), + dataSourceConfig: dataSourceConfig, + pollingDataSourceConfig: pollingDataSourceConfig, + httpProperties: httpProperties, + clientFactory: clientFactory, + httpClientFactory: httpClientFactory ?? _defaultHttpClientFactory, + plainContextString: jsonEncode( + LDContextSerialization.toJson(context, isEvent: false))); + + StreamingDataSource._( + {required String credential, + required ServiceEndpoints endpoints, + required LDLogger logger, + required StreamingDataSourceConfig dataSourceConfig, + required PollingDataSourceConfig pollingDataSourceConfig, + required HttpProperties httpProperties, + required SSEClientFactory? clientFactory, + required HttpClientFactory httpClientFactory, + required String plainContextString}) + : _logger = logger, _dataSourceConfig = dataSourceConfig, - _clientFactory = clientFactory ?? defaultSseClientFactory, - _customFactory = clientFactory != null, + _clientFactory = clientFactory, _httpProperties = httpProperties, - _credential = credential { - _plainContextString = - jsonEncode(LDContextSerialization.toJson(context, isEvent: false)); - _endpoints = endpoints; - _pollingDataSourceConfig = pollingDataSourceConfig; - _httpClientFactory = httpClientFactory ?? _defaultHttpClientFactory; - - // With a custom client, the capabilities of the client decide in start. - // Without one, the platform decides. - if (_dataSourceConfig.useReport && - !_customFactory && - !DefaultConfig.dataSourceConfig.streamingReportSupported) { - _logger.warn( - 'REPORT is currently not supported for streaming on web targets'); - } - - _wantReport = _dataSourceConfig.useReport && - (_customFactory || - DefaultConfig.dataSourceConfig.streamingReportSupported); - - _configureRequest(_wantReport); - } - - /// Sets the URI and the ping requestor for the request method. - void _configureRequest(bool useReport) { - _useReport = useReport; - _contextString = useReport + _credential = credential, + _endpoints = endpoints, + _plainContextString = plainContextString, + _requestor = Requestor( + logger: logger, + contextString: pollingDataSourceConfig.useReport + ? plainContextString + : base64UrlEncode(utf8.encode(plainContextString)), + method: pollingDataSourceConfig.useReport + ? RequestMethod.report + : RequestMethod.get, + httpProperties: httpProperties, + dataSourceConfig: pollingDataSourceConfig, + endpoints: endpoints, + credential: credential, + httpClientFactory: httpClientFactory); + + /// The streaming URI for the request method. + Uri _uriFor(bool useReport) { + final contextString = useReport ? _plainContextString : base64UrlEncode(utf8.encode(_plainContextString)); - final path = useReport - ? _dataSourceConfig.streamingReportPath(_credential, _contextString) - : _dataSourceConfig.streamingGetPath(_credential, _contextString); - - String completeUrl = appendPath(_endpoints.streaming, path); + ? _dataSourceConfig.streamingReportPath(_credential, contextString) + : _dataSourceConfig.streamingGetPath(_credential, contextString); + var completeUrl = appendPath(_endpoints.streaming, path); if (_dataSourceConfig.withReasons) { completeUrl = '$completeUrl?withReasons=true'; } - - _uri = Uri.parse(completeUrl); - - _requestor = Requestor( - logger: _logger, - contextString: _contextString, - method: useReport ? RequestMethod.report : RequestMethod.get, - httpProperties: _httpProperties, - dataSourceConfig: _pollingDataSourceConfig, - endpoints: _endpoints, - credential: _credential, - httpClientFactory: _httpClientFactory); + return Uri.parse(completeUrl); } - SSEClient _buildClient() { - final headers = - streamingRequestHeaders(_httpProperties, customFactory: _customFactory); - return _clientFactory(SSEClientRequest( - uriProvider: () => _uri, - eventTypes: const {_putEvent, _patchEvent, _delete, _pingEvent}, - headers: headers, - body: _useReport ? _contextString : null, - method: _useReport ? SseHttpMethod.report : SseHttpMethod.get, - logger: LDLoggerToEventSourceAdapter(_logger))); + SSEClientRequest _requestFor(bool useReport) => SSEClientRequest( + uriProvider: () => _uriFor(useReport), + eventTypes: const {_putEvent, _patchEvent, _delete, _pingEvent}, + headers: streamingRequestHeaders(_httpProperties), + body: useReport ? _plainContextString : null, + method: useReport ? SseHttpMethod.report : SseHttpMethod.get, + logger: LDLoggerToEventSourceAdapter(_logger)); + + /// Builds the client, or returns null after a failure. A failure shuts + /// the data source down. The factory is application code, so it can throw. + (SSEClient, bool)? _buildClient() { + try { + return createSseClient( + factory: _clientFactory, + requestFor: _requestFor, + useCustomMethod: _dataSourceConfig.useReport, + logger: _logger); + } catch (err) { + _permanentShutdown = true; + _logger.error('The SSE client factory failed: "$err", Shutting down.'); + // The event must be added before calling stop, because stop closes + // the controller and adding an event after that throws a StateError. + _dataController.sink.add(StatusEvent( + ErrorKind.unknown, null, 'The SSE client factory failed')); + stop(); + return null; + } } @override @@ -163,18 +168,16 @@ final class StreamingDataSource implements DataSource { return; } _stopped = false; - _logger.debug('Establishing new streaming connection, uri: $_uri'); - var client = _buildClient(); - if (_wantReport && !client.hasCapability(SSECapability.customMethod)) { - _logger.warn( - 'The SSE client cannot send REPORT requests. Streaming with GET instead.'); - client.close(); - _configureRequest(false); - client = _buildClient(); + final built = _buildClient(); + if (built == null) { + return; } + final (client, useReport) = built; + _logger.debug( + 'Establishing new streaming connection, uri: ${_uriFor(useReport)}'); _client = client; - _subscription = _client!.stream.listen((event) async { + _subscription = client.stream.listen((event) async { if (_stopped) { return; } @@ -254,6 +257,10 @@ final class StreamingDataSource implements DataSource { // to the method documentation. _subscription?.cancel(); _subscription = null; + if (_client case final client?) { + closeSseClient(client, _logger); + _client = null; + } _stopped = true; _dataController.close(); } diff --git a/packages/common_client/test/data_sources/sse_client_factory_test.dart b/packages/common_client/test/data_sources/sse_client_factory_test.dart index 9ea82db6..5f55d03e 100644 --- a/packages/common_client/test/data_sources/sse_client_factory_test.dart +++ b/packages/common_client/test/data_sources/sse_client_factory_test.dart @@ -1,7 +1,11 @@ +@TestOn('vm') +library; + import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; import 'package:launchdarkly_common_client/src/data_sources/sse_client_factory.dart'; import 'package:test/test.dart'; +// The web behavior is in sse_client_factory_web_test.dart. void main() { group('streamingRequestHeaders', () { final properties = HttpProperties(baseHeaders: { @@ -9,19 +13,9 @@ void main() { 'x-launchdarkly-user-agent': 'agent', }); - test('keeps every header when the platform accepts the tags header', () { - // The test platform is not web, so the service accepts the header. + test('keeps every header, because the service accepts the tags header', () { expect( - streamingRequestHeaders(properties, customFactory: true), - equals({ - 'X-LaunchDarkly-Tags': 'application-id/app', - 'x-launchdarkly-user-agent': 'agent', - })); - }); - - test('keeps every header when no custom factory is set', () { - expect(streamingRequestHeaders(properties, customFactory: false), - equals(properties.baseHeaders)); + streamingRequestHeaders(properties), equals(properties.baseHeaders)); }); }); } diff --git a/packages/common_client/test/data_sources/sse_client_factory_web_test.dart b/packages/common_client/test/data_sources/sse_client_factory_web_test.dart new file mode 100644 index 00000000..e8529115 --- /dev/null +++ b/packages/common_client/test/data_sources/sse_client_factory_web_test.dart @@ -0,0 +1,99 @@ +@TestOn('browser') +library; + +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_status_manager.dart'; +import 'package:launchdarkly_common_client/src/data_sources/fdv2/data_system.dart'; +import 'package:launchdarkly_common_client/src/data_sources/sse_client_factory.dart'; +import 'package:launchdarkly_common_client/src/data_sources/streaming_data_source.dart'; +import 'package:test/test.dart'; + +// These tests cover the decisions the SDK makes only on web. Run them with +// `dart test test/data_sources/sse_client_factory_web_test.dart -p chrome`. + +/// A client with every capability, like `SSEClient.http`. +SSEClient _httpCapableClient(SSEClientRequest request) => + SSEClient.testClient(request.uriProvider(), request.eventTypes); + +void main() { + 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('FDv2 with usePost', () { + FDv2DataSystem makeDataSystem({SSEClientFactory? factory}) => + 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, + sseClientFactory: factory, + ); + + test('the default client cannot POST, so the streaming entries are dropped', + () { + final definition = + makeDataSystem().resolvedDefinition(ConnectionModeId.streaming); + + expect( + definition.synchronizers.whereType(), isEmpty); + }); + + test('a custom client keeps the streaming entries', () { + final definition = makeDataSystem(factory: _httpCapableClient) + .resolvedDefinition(ConnectionModeId.streaming); + + expect(definition.synchronizers.whereType(), + isNotEmpty); + }); + }); + + group('FDv1 with useReport', () { + test('a custom client that can send REPORT streams with REPORT', () { + final requests = []; + final dataSource = StreamingDataSource( + credential: 'the-credential', + context: LDContextBuilder().kind('user', 'test').build(), + endpoints: ServiceEndpoints(), + logger: LDLogger(level: LDLogLevel.none), + dataSourceConfig: StreamingDataSourceConfig(useReport: true), + pollingDataSourceConfig: PollingDataSourceConfig(useReport: true), + httpProperties: + HttpProperties(baseHeaders: {'X-LaunchDarkly-Tags': 'a/b'}), + clientFactory: (request) { + requests.add(request); + return _httpCapableClient(request); + }); + + dataSource.start(); + + expect(requests.single.method, SseHttpMethod.report); + expect(requests.single.body, '{"key":"test","kind":"user"}'); + expect(requests.single.headers, isNot(contains('X-LaunchDarkly-Tags'))); + dataSource.stop(); + }); + }); +} 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 3b397a18..71534523 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 @@ -14,10 +14,12 @@ import 'package:launchdarkly_common_client/src/data_sources/streaming_data_sourc import 'package:launchdarkly_common_client/src/flag_manager/flag_manager.dart'; 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; final bool supportsCustomMethod; @@ -53,18 +55,18 @@ class MockSseClient implements SSEClient { Duration? testingInterval, MockClient? mockHttpClient, bool supportsCustomMethod = true, - MockSseClient? clientOverride, + // Receives every client the factory creates. + List? createdClients, + LDLogger? inLogger, Function(Uri, HttpProperties, 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. final statusManager = DataSourceStatusManager(stamper: () => DateTime(1)); - final logger = LDLogger(); + final logger = inLogger ?? LDLogger(); final properties = inProperties ?? HttpProperties(); - final client = clientOverride ?? - MockSseClient(mockStream, supportsCustomMethod: supportsCustomMethod); const sdkKey = 'dummy-key'; final flagManager = FlagManager(sdkKey: sdkKey, logger: logger, maxCachedContexts: 5); @@ -88,6 +90,9 @@ class MockSseClient implements SSEClient { clientFactory: (request) { factoryCallback?.call( request.uriProvider(), properties, request.body, request.method); + final client = MockSseClient(mockStream, + supportsCustomMethod: supportsCustomMethod); + createdClients?.add(client); return client; }); @@ -114,6 +119,14 @@ class MockSseClient implements SSEClient { } void main() { + setUpAll(() { + registerFallbackValue(LDLogRecord( + level: LDLogLevel.debug, + message: '', + time: DateTime.now(), + logTag: '')); + }); + group('parameters are correctly calculated for the stream subscription', () { test('it uses the correct URL without reasons', () { final controller = StreamController(); @@ -168,10 +181,12 @@ void main() { test('it falls back to GET when the client cannot send REPORT', () { final calls = <(Uri, String?, SseHttpMethod?)>[]; + final clients = []; final controller = StreamController(); final (dataSource, _, _) = makeDataSourceForTest(controller.stream, factoryCallback: (uri, properties, body, method) => calls.add((uri, body, method)), + createdClients: clients, useReport: true, supportsCustomMethod: false); @@ -183,6 +198,28 @@ void main() { expect(calls.last.$2, isNull); expect(calls.last.$1.toString(), 'https://clientstream.launchdarkly.com/meval/eyJrZXkiOiJ0ZXN0Iiwia2luZCI6InVzZXIifQ=='); + expect(clients.first.closed, isTrue, + reason: 'the REPORT client is closed'); + expect(clients.last.closed, isFalse, reason: 'the GET client is in use'); + }); + + test('it logs a warning when it falls back to GET', () { + final adapter = MockLogAdapter(); + final controller = StreamController(); + final (dataSource, _, _) = makeDataSourceForTest(controller.stream, + inLogger: LDLogger(adapter: adapter), + useReport: true, + supportsCustomMethod: false); + + dataSource.start(); + + final records = verify(() => adapter.log(captureAny())) + .captured + .cast() + .where((record) => record.level == LDLogLevel.warn); + expect(records.map((record) => record.message), [ + 'The SSE client cannot send REPORT requests. Streaming with GET instead.' + ]); }); test('it keeps REPORT when the client can send it', () { @@ -197,6 +234,73 @@ void main() { expect(calls, [SseHttpMethod.report]); }); + test('a ping poll keeps the configured REPORT method after the fallback', + () async { + // The polling request method follows the polling configuration. The + // stream fallback does not change it. A GET on the REPORT polling path + // would carry no context. + final pollRequests = []; + final innerHttpClient = MockClient((request) async { + pollRequests.add(request); + return http.Response('{}', 200); + }); + final controller = StreamController(); + final (dataSource, _, _) = makeDataSourceForTest(controller.stream, + mockHttpClient: innerHttpClient, + useReport: true, + supportsCustomMethod: false); + + dataSource.start(); + controller.sink.add(MessageEvent('ping', '', null)); + await Future.delayed(Duration(milliseconds: 50)); + + expect(pollRequests, hasLength(1)); + expect(pollRequests.single.method, 'REPORT'); + expect(pollRequests.single.url.path, '/msdk/evalx/context'); + expect(pollRequests.single.body, '{"key":"test","kind":"user"}'); + }); + + test('it closes the client when it stops', () { + final clients = []; + final controller = StreamController(); + final (dataSource, _, _) = + makeDataSourceForTest(controller.stream, createdClients: clients); + + dataSource.start(); + dataSource.stop(); + + expect(clients.single.closed, isTrue); + }); + + test('it shuts down when the client factory throws', () async { + final adapter = MockLogAdapter(); + final dataSource = StreamingDataSource( + credential: 'dummy-key', + context: LDContextBuilder().kind('user', 'test').build(), + endpoints: ServiceEndpoints(), + logger: LDLogger(adapter: adapter), + dataSourceConfig: StreamingDataSourceConfig(), + pollingDataSourceConfig: PollingDataSourceConfig(), + httpProperties: HttpProperties(), + clientFactory: (request) => throw StateError('no client')); + final events = []; + dataSource.events.listen(events.add); + + dataSource.start(); + await Future.delayed(Duration.zero); + + expect(events, hasLength(1)); + expect(events.single, isA()); + expect((events.single as StatusEvent).kind, ErrorKind.unknown); + final errors = verify(() => adapter.log(captureAny())) + .captured + .cast() + .where((record) => record.level == LDLogLevel.error); + expect(errors.map((record) => record.message), [ + 'The SSE client factory failed: "Bad state: no client", Shutting down.' + ]); + }); + test('it uses the correct URL without reasons with REPORT', () { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest( diff --git a/packages/common_client/test/event_source_factory_test.dart b/packages/common_client/test/event_source_factory_test.dart index 0aee3126..d956a853 100644 --- a/packages/common_client/test/event_source_factory_test.dart +++ b/packages/common_client/test/event_source_factory_test.dart @@ -41,13 +41,17 @@ void main() { Future> startAndCollect( LDCommonConfig Function(SSEClientFactory factory) makeConfig) async { final requests = []; + final firstRequest = Completer(); final client = _makeClient(makeConfig((request) { requests.add(request); + if (!firstRequest.isCompleted) { + firstRequest.complete(); + } return SSEClient.testClient(request.uriProvider(), request.eventTypes); })); unawaited(client.start()); // Streaming starts after the identify that start performs. - await Future.delayed(const Duration(milliseconds: 200)); + await firstRequest.future.timeout(const Duration(seconds: 5)); await client.close(); return requests; } From 46e05b144625b2628891e1f88be14a1c3f837076 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Thu, 5 Nov 2026 11:57:17 -0500 Subject: [PATCH 3/9] refactor: Replace the SSE client factory with useHttpStreamingOnWeb --- .github/actions/ci/action.yml | 9 +- .../lib/launchdarkly_common_client.dart | 13 -- .../lib/src/config/defaults/io_config.dart | 3 +- .../lib/src/config/defaults/js_config.dart | 3 +- .../src/data_sources/fdv2/data_system.dart | 32 +-- .../data_sources/fdv2/entry_factories.dart | 31 ++- .../src/data_sources/sse_client_factory.dart | 132 ------------ .../src/data_sources/streaming_client.dart | 46 +++++ .../data_sources/streaming_data_source.dart | 98 ++++----- .../lib/src/ld_common_client.dart | 4 +- .../lib/src/ld_common_config.dart | 22 +- .../fdv2/entry_factories_test.dart | 83 +++----- .../data_sources/sse_client_factory_test.dart | 21 -- .../sse_client_factory_web_test.dart | 99 --------- .../data_sources/streaming_client_test.dart | 43 ++++ .../streaming_client_web_test.dart | 194 ++++++++++++++++++ .../streaming_data_source_test.dart | 147 ++----------- .../test/event_source_factory_test.dart | 81 -------- 18 files changed, 417 insertions(+), 644 deletions(-) delete mode 100644 packages/common_client/lib/src/data_sources/sse_client_factory.dart create mode 100644 packages/common_client/lib/src/data_sources/streaming_client.dart delete mode 100644 packages/common_client/test/data_sources/sse_client_factory_test.dart delete mode 100644 packages/common_client/test/data_sources/sse_client_factory_web_test.dart create mode 100644 packages/common_client/test/data_sources/streaming_client_test.dart create mode 100644 packages/common_client/test/data_sources/streaming_client_web_test.dart delete mode 100644 packages/common_client/test/event_source_factory_test.dart diff --git a/.github/actions/ci/action.yml b/.github/actions/ci/action.yml index 5552f24f..65b044ca 100644 --- a/.github/actions/ci/action.yml +++ b/.github/actions/ci/action.yml @@ -73,12 +73,13 @@ runs: - name: Web Streaming Tests (Chrome) shell: bash - # The SSE client factory makes decisions that only apply on web: it - # removes the tags header and keeps streaming with a custom client. - # The Dart VM cannot run that code, so these tests run on Chrome. + # The streaming client selection makes decisions that only apply on + # web: it removes the tags header and falls back to GET or polling + # without useHttpStreamingOnWeb. The Dart VM cannot run that code, so + # these tests run on Chrome. run: | cd packages/common_client - dart test test/data_sources/sse_client_factory_web_test.dart -p chrome --test-randomize-ordering-seed=random + dart test test/data_sources/streaming_client_web_test.dart -p chrome --test-randomize-ordering-seed=random - name: Contract Tests (FDv1) shell: bash diff --git a/packages/common_client/lib/launchdarkly_common_client.dart b/packages/common_client/lib/launchdarkly_common_client.dart index 8ed0478c..50a01e3e 100644 --- a/packages/common_client/lib/launchdarkly_common_client.dart +++ b/packages/common_client/lib/launchdarkly_common_client.dart @@ -6,19 +6,6 @@ export 'src/ld_common_config.dart' AutoEnvAttributes, PollingConfig; -export 'src/data_sources/sse_client_factory.dart' - show SSEClientFactory, SSEClientRequest; -export 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart' - show - SSEClient, - SSECapability, - SseHttpMethod, - SseHttpError, - EventSourceLogger, - Event, - MessageEvent, - OpenEvent; - 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/defaults/io_config.dart b/packages/common_client/lib/src/config/defaults/io_config.dart index 7ff8105d..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,7 +61,8 @@ final class DefaultDataSourceConfig { ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming; - /// 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. 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 4663f395..e9b5674d 100644 --- a/packages/common_client/lib/src/config/defaults/js_config.dart +++ b/packages/common_client/lib/src/config/defaults/js_config.dart @@ -70,7 +70,8 @@ final class DefaultDataSourceConfig { ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming; - /// The browser EventSource can only send GET requests without a body. + /// The browser EventSource can only send GET requests without a body. The + /// HTTP-based client can send POST and REPORT. bool get streamingPostSupported => false; /// The CORS allow-list of the streaming service does not include the 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 a4f708e5..3334214c 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 @@ -3,12 +3,11 @@ import 'package:launchdarkly_dart_common/launchdarkly_dart_common.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 '../sse_client_factory.dart'; +import '../streaming_client.dart'; import 'built_in_modes.dart'; import 'cache_initializer.dart'; import 'entry_factories.dart'; @@ -41,7 +40,7 @@ final class FDv2DataSystem { final DataSourceStatusManager _statusManager; final Map _connectionModeOverrides; final CachedFlagsReader _cachedFlagsReader; - final SSEClientFactory? _sseClientFactory; + final SseClientBuilder _sseClientBuilder; final HttpClientFactory? _httpClientFactory; Selector _selector = Selector.empty; @@ -56,11 +55,13 @@ final class FDv2DataSystem { required Duration defaultPollingInterval, required DataSourceStatusManager statusManager, required CachedFlagsReader cachedFlagsReader, - SSEClientFactory? sseClientFactory, + // Selects the HTTP-based SSE client on web. + bool useHttpStreamingOnWeb = false, + // Builds the SSE client. Tests inject a fake. + SseClientBuilder? sseClientBuilder, HttpClientFactory? httpClientFactory, - // Whether the streaming transport can send a POST request. Defaults to - // the platform's capability. With a custom client, the data source checks - // each client instead. 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, @@ -69,19 +70,20 @@ final class FDv2DataSystem { _withReasons = withReasons, _usePost = config.usePost, _streamingPostSupported = streamingPostSupported ?? - (sseClientFactory != null || - DefaultConfig.dataSourceConfig.streamingPostSupported), + streamingCustomMethodSupported( + useHttpStreamingOnWeb: useHttpStreamingOnWeb), _defaultPollingInterval = defaultPollingInterval, _statusManager = statusManager, _cachedFlagsReader = cachedFlagsReader, - _sseClientFactory = sseClientFactory, + _sseClientBuilder = sseClientBuilder ?? + sseClientBuilderFor(useHttpStreamingOnWeb: useHttpStreamingOnWeb), _httpClientFactory = httpClientFactory, _connectionModeOverrides = config.connectionModes { if (_usePost && !_streamingPostSupported) { - _logger.warn( - 'The streaming transport on this platform cannot send POST requests. ' - 'Streaming sources are skipped while usePost is set, so the SDK ' - 'polls instead.'); + _logger + .warn('The browser EventSource cannot send POST requests. Streaming ' + 'sources are skipped while usePost is set, so the SDK polls ' + 'instead. Set useHttpStreamingOnWeb to stream with POST on web.'); } } @@ -182,7 +184,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 18e033e9..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,7 +6,7 @@ import 'package:launchdarkly_event_source_client/launchdarkly_event_source_clien import '../../config/defaults/default_config.dart'; import '../../config/service_endpoints.dart'; -import '../sse_client_factory.dart'; +import '../streaming_client.dart'; import '../streaming_data_source.dart' show LDLoggerToEventSourceAdapter; import 'cache_initializer.dart' as cache_src; import 'endpoints.dart'; @@ -175,7 +175,7 @@ InitializerFactory createInitializerFactoryFromEntry( SynchronizerFactory createSynchronizerFactoryFromEntry( mode.SynchronizerEntry entry, SourceFactoryContext ctx, { - SSEClientFactory? sseClientFactory, + SseClientBuilder sseClientBuilder = SSEClient.new, }) { switch (entry) { case final mode.PollingSynchronizer e: @@ -200,28 +200,21 @@ SynchronizerFactory createSynchronizerFactoryFromEntry( create: (SelectorGetter selectorGetter) { final endpointsResolved = mergeServiceEndpoints(ctx.serviceEndpoints, e.endpoints); - // A client without the custom method capability streams with GET. - // The ping poll below keeps the configured method. - final (sseClient, _) = createSseClient( - factory: sseClientFactory, - useCustomMethod: ctx.usePost, - logger: ctx.logger, - requestFor: (usePost) => SSEClientRequest( - uriProvider: () => _buildStreamingUri( + Uri uriProvider() => _buildStreamingUri( endpoints: endpointsResolved, contextEncoded: base64UrlEncode(utf8.encode(ctx.contextJson)), - usePost: usePost, + usePost: ctx.usePost, withReasons: ctx.withReasons, basis: selectorGetter(), additionalQueryParameters: ctx.additionalQueryParameters, - ), - eventTypes: _fdv2StreamEventNames, + ); + final sseClient = sseClientBuilder( + uriProvider(), _fdv2StreamEventNames, headers: streamingRequestHeaders(ctx.httpProperties), - body: usePost ? ctx.contextJson : null, - method: usePost ? SseHttpMethod.post : SseHttpMethod.get, + 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( @@ -258,10 +251,10 @@ List buildInitializerFactories( List buildSynchronizerFactories( List entries, SourceFactoryContext ctx, { - SSEClientFactory? sseClientFactory, + 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/sse_client_factory.dart b/packages/common_client/lib/src/data_sources/sse_client_factory.dart deleted file mode 100644 index 360663ca..00000000 --- a/packages/common_client/lib/src/data_sources/sse_client_factory.dart +++ /dev/null @@ -1,132 +0,0 @@ -import 'dart:async'; - -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'; - -/// The details of a streaming connection that the SDK asks an -/// [SSEClientFactory] to create. -/// -/// The SDK adds fields to this class over time. A factory that reads only -/// the fields it needs keeps working when a field is added. -final class SSEClientRequest { - /// Returns the URI for the next connection attempt. The SDK calls this - /// before the first connection and before every reconnection, because - /// the query parameters can change between attempts. - /// - /// With `GET`, the URI carries the evaluation context. Do not log it. - final Uri Function() uriProvider; - - /// The names of the events that the client must emit. - final Set eventTypes; - - /// The HTTP headers for the connection request. They carry the SDK - /// credential. Do not log them. - final Map headers; - - /// The request body, or null when the request has no body. With `POST` or - /// `REPORT`, the body is the evaluation context. - final String? body; - - /// The HTTP method for the connection request. - final SseHttpMethod method; - - /// The logger for the client. - final EventSourceLogger logger; - - const SSEClientRequest({ - required this.uriProvider, - required this.eventTypes, - required this.headers, - required this.body, - required this.method, - required this.logger, - }); -} - -/// Creates the [SSEClient] that the SDK uses for streaming. -/// -/// The SDK calls the factory when it opens a streaming connection. When the -/// configured method is `POST` or `REPORT`, the SDK reads -/// [SSEClient.hasCapability] on the client it receives. Without -/// [SSECapability.customMethod], the SDK logs a warning, closes that client, -/// and calls the factory a second time with a `GET` request. The `GET` -/// request carries the evaluation context in the URI. -/// -/// Without [SSECapability.httpErrors], the SDK does not expect an -/// unrecoverable HTTP error on the stream, so every failure is retried. -/// -/// The SDK closes the client when it stops streaming. -/// -/// On web, the SDK removes the application tags header from the request, -/// because the CORS allow-list of the streaming service does not include it. -typedef SSEClientFactory = SSEClient Function(SSEClientRequest request); - -/// Creates the default [SSEClient] for the platform. -SSEClient defaultSseClientFactory(SSEClientRequest request) { - return SSEClient(request.uriProvider(), request.eventTypes, - headers: request.headers, - body: request.body, - httpMethod: request.method, - logger: request.logger, - uriProvider: request.uriProvider); -} - -/// Builds the client for a streaming connection. -/// -/// [requestFor] builds the request. Its argument says whether the request -/// uses the configured custom method, `POST` or `REPORT`. When -/// [useCustomMethod] is set and the client does not report -/// [SSECapability.customMethod], this logs a warning, closes that client, -/// and builds a `GET` client instead. -/// -/// Returns the client and whether it uses the custom method. -(SSEClient, bool) createSseClient({ - required SSEClientFactory? factory, - required SSEClientRequest Function(bool useCustomMethod) requestFor, - required bool useCustomMethod, - required LDLogger logger, -}) { - final build = factory ?? defaultSseClientFactory; - final request = requestFor(useCustomMethod); - final client = build(request); - if (!useCustomMethod || client.hasCapability(SSECapability.customMethod)) { - return (client, useCustomMethod); - } - logger.warn('The SSE client cannot send ${request.method} requests. ' - 'Streaming with GET instead.'); - closeSseClient(client, logger); - return (build(requestFor(false)), false); -} - -/// Closes [client]. A custom client can fail to close. The failure is -/// logged and does not reach the caller. -void closeSseClient(SSEClient client, LDLogger logger) { - void report(Object err) { - logger.warn('The SSE client failed to close: $err'); - } - - try { - unawaited(client.close().catchError(report)); - } catch (err) { - report(err); - } -} - -const String _tagsHeader = 'x-launchdarkly-tags'; - -/// Returns the headers for a streaming request. -/// -/// On a platform where the streaming service rejects the application tags -/// header, the tags header is removed. -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_client.dart b/packages/common_client/lib/src/data_sources/streaming_client.dart new file mode 100644 index 00000000..f54e90b4 --- /dev/null +++ b/packages/common_client/lib/src/data_sources/streaming_client.dart @@ -0,0 +1,46 @@ +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. Tests inject a fake. +typedef SseClientBuilder = SSEClient Function(Uri uri, Set eventTypes, + {required Map headers, + required String? body, + required SseHttpMethod httpMethod, + required EventSourceLogger logger, + required Uri Function() uriProvider}); + +/// Returns the builder for the configuration. +/// +/// With [useHttpStreamingOnWeb], the SDK streams with the HTTP-based client +/// on every platform. Without it, the SDK uses the default client for the +/// platform. On platforms other than web, both are the HTTP-based client. +SseClientBuilder sseClientBuilderFor({required bool useHttpStreamingOnWeb}) => + useHttpStreamingOnWeb ? SSEClient.http : SSEClient.new; + +/// Whether the streaming client can send a POST or REPORT request with a +/// body. The browser `EventSource` cannot. The HTTP-based client can. +bool streamingCustomMethodSupported({required bool useHttpStreamingOnWeb}) => + useHttpStreamingOnWeb || + DefaultConfig.dataSourceConfig.streamingPostSupported; + +const String _tagsHeader = 'x-launchdarkly-tags'; + +/// Returns the headers for a streaming request. +/// +/// On a platform where the streaming service rejects the application tags +/// header, the tags header is removed. +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 a8b239c2..39abef08 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 @@ -10,7 +10,7 @@ import 'data_source.dart'; import 'data_source_status.dart'; import 'get_environment_id.dart'; import 'requestor.dart'; -import 'sse_client_factory.dart'; +import 'streaming_client.dart'; const String _pingEvent = 'ping'; const String _patchEvent = 'patch'; @@ -28,7 +28,10 @@ final class StreamingDataSource implements DataSource { final StreamingDataSourceConfig _dataSourceConfig; - final SSEClientFactory? _clientFactory; + final SseClientBuilder _clientBuilder; + + /// Whether the stream uses REPORT. False when the client cannot send it. + final bool _useReport; final String _plainContextString; @@ -58,12 +61,10 @@ final class StreamingDataSource implements DataSource { /// Used to track if there has been an unrecoverable error. bool _permanentShutdown = false; - /// The [clientFactory] parameter supplies the SSE client. When it is not - /// set, the default client for the platform is used. When the - /// configuration asks for REPORT and the client does not report - /// [SSECapability.customMethod], the stream uses GET instead. - /// The [httpClientFactory] parameter is primarily intended for testing the - /// requestor used for ping events. + /// [useHttpStreamingOnWeb] selects the HTTP-based SSE client on web. The + /// [clientBuilder] parameter is for tests, which inject a fake client. The + /// [httpClientFactory] parameter is for tests of the requestor that serves + /// ping events. StreamingDataSource( {required String credential, required LDContext context, @@ -72,7 +73,8 @@ final class StreamingDataSource implements DataSource { required StreamingDataSourceConfig dataSourceConfig, required PollingDataSourceConfig pollingDataSourceConfig, required HttpProperties httpProperties, - SSEClientFactory? clientFactory, + bool useHttpStreamingOnWeb = false, + SseClientBuilder? clientBuilder, HttpClientFactory? httpClientFactory}) : this._( credential: credential, @@ -81,7 +83,12 @@ final class StreamingDataSource implements DataSource { dataSourceConfig: dataSourceConfig, pollingDataSourceConfig: pollingDataSourceConfig, httpProperties: httpProperties, - clientFactory: clientFactory, + clientBuilder: clientBuilder ?? + sseClientBuilderFor( + useHttpStreamingOnWeb: useHttpStreamingOnWeb), + useReport: dataSourceConfig.useReport && + streamingCustomMethodSupported( + useHttpStreamingOnWeb: useHttpStreamingOnWeb), httpClientFactory: httpClientFactory ?? _defaultHttpClientFactory, plainContextString: jsonEncode( LDContextSerialization.toJson(context, isEvent: false))); @@ -93,12 +100,14 @@ final class StreamingDataSource implements DataSource { required StreamingDataSourceConfig dataSourceConfig, required PollingDataSourceConfig pollingDataSourceConfig, required HttpProperties httpProperties, - required SSEClientFactory? clientFactory, + required SseClientBuilder clientBuilder, + required bool useReport, required HttpClientFactory httpClientFactory, required String plainContextString}) : _logger = logger, _dataSourceConfig = dataSourceConfig, - _clientFactory = clientFactory, + _clientBuilder = clientBuilder, + _useReport = useReport, _httpProperties = httpProperties, _credential = credential, _endpoints = endpoints, @@ -115,14 +124,20 @@ final class StreamingDataSource implements DataSource { dataSourceConfig: pollingDataSourceConfig, endpoints: endpoints, credential: credential, - httpClientFactory: httpClientFactory); + httpClientFactory: httpClientFactory) { + if (dataSourceConfig.useReport && !_useReport) { + _logger.warn('The browser EventSource cannot send REPORT requests. ' + 'Streaming with GET instead. Set useHttpStreamingOnWeb to stream ' + 'with REPORT on web.'); + } + } /// The streaming URI for the request method. - Uri _uriFor(bool useReport) { - final contextString = useReport + Uri _buildUri() { + final contextString = _useReport ? _plainContextString : base64UrlEncode(utf8.encode(_plainContextString)); - final path = useReport + final path = _useReport ? _dataSourceConfig.streamingReportPath(_credential, contextString) : _dataSourceConfig.streamingGetPath(_credential, contextString); @@ -133,48 +148,21 @@ final class StreamingDataSource implements DataSource { return Uri.parse(completeUrl); } - SSEClientRequest _requestFor(bool useReport) => SSEClientRequest( - uriProvider: () => _uriFor(useReport), - eventTypes: const {_putEvent, _patchEvent, _delete, _pingEvent}, - headers: streamingRequestHeaders(_httpProperties), - body: useReport ? _plainContextString : null, - method: useReport ? SseHttpMethod.report : SseHttpMethod.get, - logger: LDLoggerToEventSourceAdapter(_logger)); - - /// Builds the client, or returns null after a failure. A failure shuts - /// the data source down. The factory is application code, so it can throw. - (SSEClient, bool)? _buildClient() { - try { - return createSseClient( - factory: _clientFactory, - requestFor: _requestFor, - useCustomMethod: _dataSourceConfig.useReport, - logger: _logger); - } catch (err) { - _permanentShutdown = true; - _logger.error('The SSE client factory failed: "$err", Shutting down.'); - // The event must be added before calling stop, because stop closes - // the controller and adding an event after that throws a StateError. - _dataController.sink.add(StatusEvent( - ErrorKind.unknown, null, 'The SSE client factory failed')); - stop(); - return null; - } - } - @override void start() { if (_subscription != null || _permanentShutdown || _stopped) { return; } _stopped = false; - final built = _buildClient(); - if (built == null) { - return; - } - final (client, useReport) = built; - _logger.debug( - 'Establishing new streaming connection, uri: ${_uriFor(useReport)}'); + final uri = _buildUri(); + _logger.debug('Establishing new streaming connection, uri: $uri'); + final client = _clientBuilder( + uri, const {_putEvent, _patchEvent, _delete, _pingEvent}, + headers: streamingRequestHeaders(_httpProperties), + body: _useReport ? _plainContextString : null, + httpMethod: _useReport ? SseHttpMethod.report : SseHttpMethod.get, + logger: LDLoggerToEventSourceAdapter(_logger), + uriProvider: _buildUri); _client = client; _subscription = client.stream.listen((event) async { @@ -257,10 +245,8 @@ final class StreamingDataSource implements DataSource { // to the method documentation. _subscription?.cancel(); _subscription = null; - if (_client case final client?) { - closeSseClient(client, _logger); - _client = null; - } + _client?.close(); + _client = null; _stopped = true; _dataController.close(); } diff --git a/packages/common_client/lib/src/ld_common_client.dart b/packages/common_client/lib/src/ld_common_client.dart index 2c7d0de8..0f869734 100644 --- a/packages/common_client/lib/src/ld_common_client.dart +++ b/packages/common_client/lib/src/ld_common_client.dart @@ -101,7 +101,7 @@ Map _defaultFactories( useReport: useReport, withReasons: withReasons), pollingDataSourceConfig: foregroundPollingConfig, httpProperties: httpProperties, - clientFactory: config.eventSourceFactory); + useHttpStreamingOnWeb: config.useHttpStreamingOnWeb); } return { @@ -447,7 +447,7 @@ final class LDCommonClient { _config.dataSourceConfig.polling.pollingInterval, statusManager: _dataSourceStatusManager, cachedFlagsReader: _flagManager.readCached, - sseClientFactory: _config.eventSourceFactory, + useHttpStreamingOnWeb: _config.useHttpStreamingOnWeb, ); _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 a77c81ee..677b94e4 100644 --- a/packages/common_client/lib/src/ld_common_config.dart +++ b/packages/common_client/lib/src/ld_common_config.dart @@ -4,7 +4,6 @@ import 'dart:math'; import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart' hide ServiceEndpoints; -import 'data_sources/sse_client_factory.dart'; import 'hooks/hook.dart'; import 'config/data_system_config.dart'; import 'config/defaults/default_config.dart'; @@ -160,14 +159,19 @@ abstract class LDCommonConfig { /// https://launchdarkly.com/docs/sdk/features/data-saving-mode final DataSystemConfig? dataSystem; - /// Supplies the SSE client that the SDK uses for streaming. When it is not - /// set, the SDK uses the default client for the platform. + /// Streams with the HTTP-based SSE client on web. /// - /// This option is for applications with a specific need. For example, on - /// web the default client is the browser `EventSource`. It cannot send a - /// request body or report an HTTP error. A factory that returns - /// `SSEClient.http` removes these limits. Most applications do not need it. - final SSEClientFactory? eventSourceFactory; + /// On web, the default streaming 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. With this option, the + /// SDK streams with `fetch()` through `package:http` instead, and both + /// methods work on web. The option has no effect on other platforms, where + /// the default client is already HTTP-based. + /// + /// Most applications do not need this option. On web, the SDK does not + /// send the application tags header on streaming requests, because the + /// CORS allow-list of the streaming service does not include it. + final bool useHttpStreamingOnWeb; LDCommonConfig(this.sdkCredential, this.autoEnvAttributes, {this.applicationInfo, @@ -182,7 +186,7 @@ abstract class LDCommonConfig { List? globalPrivateAttributes, List? hooks, this.dataSystem, - this.eventSourceFactory}) + this.useHttpStreamingOnWeb = false}) : httpProperties = httpProperties ?? HttpProperties(), serviceEndpoints = serviceEndpoints ?? ServiceEndpoints(), events = events ?? EventsConfig(), 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 8a029dab..8ff8feec 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,9 +152,14 @@ void main() { final factory = createSynchronizerFactoryFromEntry( StreamingSynchronizer(), ctx, - sseClientFactory: (request) { - capturedUriProvider = request.uriProvider; - return SSEClient.testClient(request.uriProvider(), const {}); + sseClientBuilder: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + required uriProvider}) { + capturedUriProvider = uriProvider; + return SSEClient.testClient(uri, const {}); }, ); final sync = factory.create(() => selector); @@ -197,9 +202,14 @@ void main() { final factory = createSynchronizerFactoryFromEntry( StreamingSynchronizer(), ctx, - sseClientFactory: (request) { - capturedUriProvider = request.uriProvider; - return SSEClient.testClient(request.uriProvider(), const {}); + sseClientBuilder: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + required uriProvider}) { + capturedUriProvider = uriProvider; + return SSEClient.testClient(uri, const {}); }, ); final sync = factory.create(() => selector); @@ -336,11 +346,16 @@ void main() { final factory = createSynchronizerFactoryFromEntry( StreamingSynchronizer(), factoryContext(usePost: usePost), - sseClientFactory: (request) { - capturedMethod = request.method; - capturedBody = request.body; - capturedUriProvider = request.uriProvider; - return SSEClient.testClient(request.uriProvider(), const {}); + sseClientBuilder: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + required uriProvider}) { + capturedMethod = httpMethod; + capturedBody = body; + capturedUriProvider = uriProvider; + return SSEClient.testClient(uri, const {}); }, ); factory.create(_selectorGetter).close(); @@ -351,52 +366,6 @@ void main() { ); } - test( - 'the streaming connection falls back to GET when the client cannot ' - 'send POST', () { - final created = <({SseHttpMethod method, String? body, Uri uri})>[]; - final clients = []; - final factory = createSynchronizerFactoryFromEntry( - StreamingSynchronizer(), - factoryContext(usePost: true), - sseClientFactory: (request) { - created.add(( - method: request.method, - body: request.body, - uri: request.uriProvider() - )); - final client = SSEClient.testClient(request.uriProvider(), const {}, - capabilities: const {SSECapability.requestHeaders}); - clients.add(client); - return client; - }, - ); - factory.create(_selectorGetter).close(); - - expect(created, hasLength(2)); - expect(created.first.method, equals(SseHttpMethod.post)); - expect(created.last.method, equals(SseHttpMethod.get)); - expect(created.last.body, isNull); - expect(created.last.uri.path, startsWith('/sdk/stream/eval/')); - expect(clients.first.isClosed, isTrue); - }); - - test('the streaming connection keeps POST when the client can send it', () { - var created = 0; - final factory = createSynchronizerFactoryFromEntry( - StreamingSynchronizer(), - factoryContext(usePost: true), - sseClientFactory: (request) { - created++; - return SSEClient.testClient(request.uriProvider(), const {}, - capabilities: const {SSECapability.customMethod}); - }, - ); - factory.create(_selectorGetter).close(); - - expect(created, equals(1)); - }); - test('the streaming connection uses POST with the context as the body', () { final connection = connectStream(usePost: true); diff --git a/packages/common_client/test/data_sources/sse_client_factory_test.dart b/packages/common_client/test/data_sources/sse_client_factory_test.dart deleted file mode 100644 index 5f55d03e..00000000 --- a/packages/common_client/test/data_sources/sse_client_factory_test.dart +++ /dev/null @@ -1,21 +0,0 @@ -@TestOn('vm') -library; - -import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; -import 'package:launchdarkly_common_client/src/data_sources/sse_client_factory.dart'; -import 'package:test/test.dart'; - -// The web behavior is in sse_client_factory_web_test.dart. -void main() { - 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/sse_client_factory_web_test.dart b/packages/common_client/test/data_sources/sse_client_factory_web_test.dart deleted file mode 100644 index e8529115..00000000 --- a/packages/common_client/test/data_sources/sse_client_factory_web_test.dart +++ /dev/null @@ -1,99 +0,0 @@ -@TestOn('browser') -library; - -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_status_manager.dart'; -import 'package:launchdarkly_common_client/src/data_sources/fdv2/data_system.dart'; -import 'package:launchdarkly_common_client/src/data_sources/sse_client_factory.dart'; -import 'package:launchdarkly_common_client/src/data_sources/streaming_data_source.dart'; -import 'package:test/test.dart'; - -// These tests cover the decisions the SDK makes only on web. Run them with -// `dart test test/data_sources/sse_client_factory_web_test.dart -p chrome`. - -/// A client with every capability, like `SSEClient.http`. -SSEClient _httpCapableClient(SSEClientRequest request) => - SSEClient.testClient(request.uriProvider(), request.eventTypes); - -void main() { - 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('FDv2 with usePost', () { - FDv2DataSystem makeDataSystem({SSEClientFactory? factory}) => - 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, - sseClientFactory: factory, - ); - - test('the default client cannot POST, so the streaming entries are dropped', - () { - final definition = - makeDataSystem().resolvedDefinition(ConnectionModeId.streaming); - - expect( - definition.synchronizers.whereType(), isEmpty); - }); - - test('a custom client keeps the streaming entries', () { - final definition = makeDataSystem(factory: _httpCapableClient) - .resolvedDefinition(ConnectionModeId.streaming); - - expect(definition.synchronizers.whereType(), - isNotEmpty); - }); - }); - - group('FDv1 with useReport', () { - test('a custom client that can send REPORT streams with REPORT', () { - final requests = []; - final dataSource = StreamingDataSource( - credential: 'the-credential', - context: LDContextBuilder().kind('user', 'test').build(), - endpoints: ServiceEndpoints(), - logger: LDLogger(level: LDLogLevel.none), - dataSourceConfig: StreamingDataSourceConfig(useReport: true), - pollingDataSourceConfig: PollingDataSourceConfig(useReport: true), - httpProperties: - HttpProperties(baseHeaders: {'X-LaunchDarkly-Tags': 'a/b'}), - clientFactory: (request) { - requests.add(request); - return _httpCapableClient(request); - }); - - dataSource.start(); - - expect(requests.single.method, SseHttpMethod.report); - expect(requests.single.body, '{"key":"test","kind":"user"}'); - expect(requests.single.headers, isNot(contains('X-LaunchDarkly-Tags'))); - dataSource.stop(); - }); - }); -} 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..306daa6f --- /dev/null +++ b/packages/common_client/test/data_sources/streaming_client_test.dart @@ -0,0 +1,43 @@ +@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:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; +import 'package:test/test.dart'; + +// The web behavior is in streaming_client_web_test.dart. +void main() { + group('sseClientBuilderFor', () { + test('selects the default client without the option', () { + expect(sseClientBuilderFor(useHttpStreamingOnWeb: false), SSEClient.new); + }); + + test('selects the HTTP client with the option', () { + expect(sseClientBuilderFor(useHttpStreamingOnWeb: true), SSEClient.http); + }); + }); + + group('streamingCustomMethodSupported', () { + test( + 'is true with and without the option, because the default client ' + 'is HTTP-based', () { + expect( + streamingCustomMethodSupported(useHttpStreamingOnWeb: false), isTrue); + expect( + streamingCustomMethodSupported(useHttpStreamingOnWeb: true), 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..1e2b3183 --- /dev/null +++ b/packages/common_client/test/data_sources/streaming_client_web_test.dart @@ -0,0 +1,194 @@ +@TestOn('browser') +library; + +import 'dart:async'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +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_status_manager.dart'; +import 'package:launchdarkly_common_client/src/data_sources/fdv2/data_system.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_dart_common/launchdarkly_dart_common.dart' + as ld_common; +import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; +import 'package:test/test.dart'; + +// 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. Events +/// on [source] reach the data source through the client. +SseClientBuilder _recording(List<_Call> calls, {Stream? source}) => + (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + required uriProvider}) { + calls.add((uri: uri, headers: headers, body: body, method: httpMethod)); + return SSEClient.testClient(uri, eventTypes, sourceStream: source); + }; + +void main() { + 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('sseClientBuilderFor', () { + test('selects the browser EventSource without the option', () { + expect(sseClientBuilderFor(useHttpStreamingOnWeb: false), SSEClient.new); + }); + + test('selects the HTTP client with the option', () { + expect(sseClientBuilderFor(useHttpStreamingOnWeb: true), SSEClient.http); + }); + }); + + group('streamingCustomMethodSupported', () { + test('is false for the browser EventSource', () { + expect(streamingCustomMethodSupported(useHttpStreamingOnWeb: false), + isFalse); + }); + + test('is true with the HTTP client', () { + expect( + streamingCustomMethodSupported(useHttpStreamingOnWeb: true), isTrue); + }); + }); + + group('FDv2 with usePost', () { + FDv2DataSystem makeDataSystem({bool useHttpStreamingOnWeb = false}) => + 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, + useHttpStreamingOnWeb: useHttpStreamingOnWeb, + ); + + test( + 'the browser EventSource cannot POST, so the streaming entries are ' + 'dropped', () { + final definition = + makeDataSystem().resolvedDefinition(ConnectionModeId.streaming); + + expect( + definition.synchronizers.whereType(), isEmpty); + }); + + test('the HTTP client keeps the streaming entries', () { + final definition = makeDataSystem(useHttpStreamingOnWeb: true) + .resolvedDefinition(ConnectionModeId.streaming); + + expect(definition.synchronizers.whereType(), + isNotEmpty); + }); + }); + + group('FDv1 with useReport', () { + StreamingDataSource makeDataSource(List<_Call> calls, + {bool useHttpStreamingOnWeb = false, + Stream? source, + MockClient? httpClient}) => + StreamingDataSource( + credential: 'the-credential', + context: LDContextBuilder().kind('user', 'test').build(), + endpoints: ServiceEndpoints(), + logger: LDLogger(level: LDLogLevel.none), + dataSourceConfig: StreamingDataSourceConfig(useReport: true), + pollingDataSourceConfig: PollingDataSourceConfig(useReport: true), + httpProperties: + HttpProperties(baseHeaders: {'X-LaunchDarkly-Tags': 'a/b'}), + useHttpStreamingOnWeb: useHttpStreamingOnWeb, + clientBuilder: _recording(calls, source: source), + httpClientFactory: httpClient == null + ? null + : (properties) => ld_common.HttpClient( + client: httpClient, httpProperties: properties)); + + test('the browser EventSource streams with GET and the context in the URI', + () { + final calls = <_Call>[]; + final dataSource = makeDataSource(calls); + + 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'))); + dataSource.stop(); + }); + + test('the HTTP client streams with REPORT and the context in the body', () { + final calls = <_Call>[]; + final dataSource = makeDataSource(calls, useHttpStreamingOnWeb: true); + + 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'))); + dataSource.stop(); + }); + + test('a ping poll keeps REPORT when the stream falls back to GET', + () async { + // A GET on the REPORT polling path would carry no context. + final pollRequests = []; + final httpClient = MockClient((request) async { + pollRequests.add(request); + return http.Response('{}', 200); + }); + final source = StreamController(); + final calls = <_Call>[]; + final dataSource = + makeDataSource(calls, source: source.stream, httpClient: httpClient); + + dataSource.start(); + source.add(const MessageEvent('ping', '', null)); + await Future.delayed(const Duration(milliseconds: 50)); + + expect(calls.single.method, SseHttpMethod.get); + expect(pollRequests, hasLength(1)); + expect(pollRequests.single.method, 'REPORT'); + expect(pollRequests.single.url.path, '/sdk/evalx/the-credential/context'); + expect(pollRequests.single.body, '{"key":"test","kind":"user"}'); + dataSource.stop(); + await source.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 71534523..6623a48a 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 @@ -14,18 +14,15 @@ import 'package:launchdarkly_common_client/src/data_sources/streaming_data_sourc import 'package:launchdarkly_common_client/src/flag_manager/flag_manager.dart'; 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; - final bool supportsCustomMethod; bool closed = false; - MockSseClient(this.mockStream, {this.supportsCustomMethod = true}); + MockSseClient(this.mockStream); @override Future close() async { @@ -39,8 +36,7 @@ class MockSseClient implements SSEClient { Stream get stream => mockStream; @override - bool hasCapability(SSECapability capability) => - capability != SSECapability.customMethod || supportsCustomMethod; + bool hasCapability(SSECapability capability) => true; } ( @@ -54,17 +50,15 @@ class MockSseClient implements SSEClient { bool withReasons = false, Duration? testingInterval, MockClient? mockHttpClient, - bool supportsCustomMethod = true, - // Receives every client the factory creates. + // Receives every client the builder creates. List? createdClients, - LDLogger? inLogger, Function(Uri, HttpProperties, 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. final statusManager = DataSourceStatusManager(stamper: () => DateTime(1)); - final logger = inLogger ?? LDLogger(); + final logger = LDLogger(); final properties = inProperties ?? HttpProperties(); const sdkKey = 'dummy-key'; @@ -87,11 +81,14 @@ class MockSseClient implements SSEClient { ? (httpProps) => ld_common.HttpClient( client: mockHttpClient, httpProperties: httpProps) : null, - clientFactory: (request) { - factoryCallback?.call( - request.uriProvider(), properties, request.body, request.method); - final client = MockSseClient(mockStream, - supportsCustomMethod: supportsCustomMethod); + clientBuilder: (uri, eventTypes, + {required headers, + required body, + required httpMethod, + required logger, + required uriProvider}) { + factoryCallback?.call(uri, properties, body, httpMethod); + final client = MockSseClient(mockStream); createdClients?.add(client); return client; }); @@ -119,14 +116,6 @@ class MockSseClient implements SSEClient { } void main() { - setUpAll(() { - registerFallbackValue(LDLogRecord( - level: LDLogLevel.debug, - message: '', - time: DateTime.now(), - logTag: '')); - }); - group('parameters are correctly calculated for the stream subscription', () { test('it uses the correct URL without reasons', () { final controller = StreamController(); @@ -179,87 +168,6 @@ void main() { controller.sink.add(MessageEvent('put', '{}', null)); }); - test('it falls back to GET when the client cannot send REPORT', () { - final calls = <(Uri, String?, SseHttpMethod?)>[]; - final clients = []; - final controller = StreamController(); - final (dataSource, _, _) = makeDataSourceForTest(controller.stream, - factoryCallback: (uri, properties, body, method) => - calls.add((uri, body, method)), - createdClients: clients, - useReport: true, - supportsCustomMethod: false); - - dataSource.start(); - - expect(calls, hasLength(2)); - expect(calls.first.$3, SseHttpMethod.report); - expect(calls.last.$3, SseHttpMethod.get); - expect(calls.last.$2, isNull); - expect(calls.last.$1.toString(), - 'https://clientstream.launchdarkly.com/meval/eyJrZXkiOiJ0ZXN0Iiwia2luZCI6InVzZXIifQ=='); - expect(clients.first.closed, isTrue, - reason: 'the REPORT client is closed'); - expect(clients.last.closed, isFalse, reason: 'the GET client is in use'); - }); - - test('it logs a warning when it falls back to GET', () { - final adapter = MockLogAdapter(); - final controller = StreamController(); - final (dataSource, _, _) = makeDataSourceForTest(controller.stream, - inLogger: LDLogger(adapter: adapter), - useReport: true, - supportsCustomMethod: false); - - dataSource.start(); - - final records = verify(() => adapter.log(captureAny())) - .captured - .cast() - .where((record) => record.level == LDLogLevel.warn); - expect(records.map((record) => record.message), [ - 'The SSE client cannot send REPORT requests. Streaming with GET instead.' - ]); - }); - - test('it keeps REPORT when the client can send it', () { - final calls = []; - final controller = StreamController(); - final (dataSource, _, _) = makeDataSourceForTest(controller.stream, - factoryCallback: (uri, properties, body, method) => calls.add(method), - useReport: true); - - dataSource.start(); - - expect(calls, [SseHttpMethod.report]); - }); - - test('a ping poll keeps the configured REPORT method after the fallback', - () async { - // The polling request method follows the polling configuration. The - // stream fallback does not change it. A GET on the REPORT polling path - // would carry no context. - final pollRequests = []; - final innerHttpClient = MockClient((request) async { - pollRequests.add(request); - return http.Response('{}', 200); - }); - final controller = StreamController(); - final (dataSource, _, _) = makeDataSourceForTest(controller.stream, - mockHttpClient: innerHttpClient, - useReport: true, - supportsCustomMethod: false); - - dataSource.start(); - controller.sink.add(MessageEvent('ping', '', null)); - await Future.delayed(Duration(milliseconds: 50)); - - expect(pollRequests, hasLength(1)); - expect(pollRequests.single.method, 'REPORT'); - expect(pollRequests.single.url.path, '/msdk/evalx/context'); - expect(pollRequests.single.body, '{"key":"test","kind":"user"}'); - }); - test('it closes the client when it stops', () { final clients = []; final controller = StreamController(); @@ -272,35 +180,6 @@ void main() { expect(clients.single.closed, isTrue); }); - test('it shuts down when the client factory throws', () async { - final adapter = MockLogAdapter(); - final dataSource = StreamingDataSource( - credential: 'dummy-key', - context: LDContextBuilder().kind('user', 'test').build(), - endpoints: ServiceEndpoints(), - logger: LDLogger(adapter: adapter), - dataSourceConfig: StreamingDataSourceConfig(), - pollingDataSourceConfig: PollingDataSourceConfig(), - httpProperties: HttpProperties(), - clientFactory: (request) => throw StateError('no client')); - final events = []; - dataSource.events.listen(events.add); - - dataSource.start(); - await Future.delayed(Duration.zero); - - expect(events, hasLength(1)); - expect(events.single, isA()); - expect((events.single as StatusEvent).kind, ErrorKind.unknown); - final errors = verify(() => adapter.log(captureAny())) - .captured - .cast() - .where((record) => record.level == LDLogLevel.error); - expect(errors.map((record) => record.message), [ - 'The SSE client factory failed: "Bad state: no client", Shutting down.' - ]); - }); - test('it uses the correct URL without reasons with REPORT', () { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest( diff --git a/packages/common_client/test/event_source_factory_test.dart b/packages/common_client/test/event_source_factory_test.dart deleted file mode 100644 index d956a853..00000000 --- a/packages/common_client/test/event_source_factory_test.dart +++ /dev/null @@ -1,81 +0,0 @@ -import 'dart:async'; - -import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; -import 'package:test/test.dart'; - -import 'mock_eventprocessor.dart'; - -final class _TestConfig extends LDCommonConfig { - _TestConfig(super.sdkCredential, super.autoEnvAttributes, - {super.dataSystem, super.eventSourceFactory, super.serviceEndpoints}); -} - -LDCommonClient _makeClient(LDCommonConfig config) => LDCommonClient( - config, - CommonPlatform(), - LDContextBuilder().kind('user', 'bob').build(), - DiagnosticSdkData(name: '', version: ''), - eventProcessorFactory: ({ - required allAttributesPrivate, - required analyticsEventsPath, - required client, - required diagnosticEventsPath, - required diagnosticRecordingInterval, - diagnosticsManager, - required endpoints, - required eventCapacity, - required flushInterval, - required globalPrivateAttributes, - required indexEvents, - required logger, - }) => - MockEventProcessor()); - -void main() { - // The streaming endpoint is unreachable so a test never leaves the machine. - final endpoints = ServiceEndpoints.custom( - polling: 'http://localhost:1', - streaming: 'http://localhost:1', - events: 'http://localhost:1'); - - Future> startAndCollect( - LDCommonConfig Function(SSEClientFactory factory) makeConfig) async { - final requests = []; - final firstRequest = Completer(); - final client = _makeClient(makeConfig((request) { - requests.add(request); - if (!firstRequest.isCompleted) { - firstRequest.complete(); - } - return SSEClient.testClient(request.uriProvider(), request.eventTypes); - })); - unawaited(client.start()); - // Streaming starts after the identify that start performs. - await firstRequest.future.timeout(const Duration(seconds: 5)); - await client.close(); - return requests; - } - - test('the FDv1 streaming data source uses the configured factory', () async { - final requests = await startAndCollect((factory) => _TestConfig( - 'client-side-id', AutoEnvAttributes.disabled, - serviceEndpoints: endpoints, eventSourceFactory: factory)); - - expect(requests, isNotEmpty); - expect(requests.first.eventTypes, containsAll(['put', 'patch', 'delete'])); - }); - - test('the FDv2 streaming data source uses the configured factory', () async { - final requests = await startAndCollect( - (factory) => _TestConfig('client-side-id', AutoEnvAttributes.disabled, - serviceEndpoints: endpoints, - dataSystem: DataSystemConfig(connectionModes: { - ConnectionModeId.streaming: const ModeDefinition( - initializers: [], synchronizers: [StreamingSynchronizer()]), - }), - eventSourceFactory: factory)); - - expect(requests, isNotEmpty); - expect(requests.first.eventTypes, contains('server-intent')); - }); -} From 61e45d4f7cb0f3c49a5ad25dc9f1de44d03fdbcc Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Thu, 5 Nov 2026 16:39:58 -0500 Subject: [PATCH 4/9] refactor: keep the original streaming shape and split out extra bug fixes --- .../src/data_sources/fdv2/data_system.dart | 8 +- .../src/data_sources/streaming_client.dart | 2 +- .../data_sources/streaming_data_source.dart | 130 +++++++----------- .../fdv2/entry_factories_test.dart | 18 ++- .../streaming_client_web_test.dart | 52 +------ .../streaming_data_source_test.dart | 24 +--- 6 files changed, 74 insertions(+), 160 deletions(-) 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 3334214c..c46f2f8b 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 @@ -80,10 +80,10 @@ final class FDv2DataSystem { _httpClientFactory = httpClientFactory, _connectionModeOverrides = config.connectionModes { if (_usePost && !_streamingPostSupported) { - _logger - .warn('The browser EventSource cannot send POST requests. Streaming ' - 'sources are skipped while usePost is set, so the SDK polls ' - 'instead. Set useHttpStreamingOnWeb to stream with POST on web.'); + _logger.warn( + 'The streaming transport on this platform cannot send POST requests. ' + 'Streaming sources are skipped while usePost is set, so the SDK ' + 'polls instead.'); } } diff --git a/packages/common_client/lib/src/data_sources/streaming_client.dart b/packages/common_client/lib/src/data_sources/streaming_client.dart index f54e90b4..b5a35a0d 100644 --- a/packages/common_client/lib/src/data_sources/streaming_client.dart +++ b/packages/common_client/lib/src/data_sources/streaming_client.dart @@ -12,7 +12,7 @@ typedef SseClientBuilder = SSEClient Function(Uri uri, Set eventTypes, required String? body, required SseHttpMethod httpMethod, required EventSourceLogger logger, - required Uri Function() uriProvider}); + Uri Function()? uriProvider}); /// Returns the builder for the configuration. /// 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 39abef08..31a71943 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 @@ -30,31 +30,27 @@ final class StreamingDataSource implements DataSource { final SseClientBuilder _clientBuilder; - /// Whether the stream uses REPORT. False when the client cannot send it. - final bool _useReport; + late final Uri _uri; - final String _plainContextString; - - final ServiceEndpoints _endpoints; - - final HttpProperties _httpProperties; - - final String _credential; - - /// Polls for all flags when the stream sends a ping. Its method follows - /// the polling configuration, not the method of the stream. - final Requestor _requestor; + late final HttpProperties _httpProperties; + late final String _contextString; bool _stopped = false; StreamSubscription? _subscription; final StreamController _dataController = StreamController(); + late final bool _useReport; + SSEClient? _client; String? _environmentId; + final String _credential; + + late final Requestor _requestor; + @override Stream get events => _dataController.stream; @@ -76,76 +72,50 @@ final class StreamingDataSource implements DataSource { bool useHttpStreamingOnWeb = false, SseClientBuilder? clientBuilder, HttpClientFactory? httpClientFactory}) - : this._( - credential: credential, - endpoints: endpoints, - logger: logger.subLogger('StreamingDataSource'), - dataSourceConfig: dataSourceConfig, - pollingDataSourceConfig: pollingDataSourceConfig, - httpProperties: httpProperties, - clientBuilder: clientBuilder ?? - sseClientBuilderFor( - useHttpStreamingOnWeb: useHttpStreamingOnWeb), - useReport: dataSourceConfig.useReport && - streamingCustomMethodSupported( - useHttpStreamingOnWeb: useHttpStreamingOnWeb), - httpClientFactory: httpClientFactory ?? _defaultHttpClientFactory, - plainContextString: jsonEncode( - LDContextSerialization.toJson(context, isEvent: false))); - - StreamingDataSource._( - {required String credential, - required ServiceEndpoints endpoints, - required LDLogger logger, - required StreamingDataSourceConfig dataSourceConfig, - required PollingDataSourceConfig pollingDataSourceConfig, - required HttpProperties httpProperties, - required SseClientBuilder clientBuilder, - required bool useReport, - required HttpClientFactory httpClientFactory, - required String plainContextString}) - : _logger = logger, + : _logger = logger.subLogger('StreamingDataSource'), _dataSourceConfig = dataSourceConfig, - _clientBuilder = clientBuilder, - _useReport = useReport, + _clientBuilder = clientBuilder ?? + sseClientBuilderFor(useHttpStreamingOnWeb: useHttpStreamingOnWeb), _httpProperties = httpProperties, - _credential = credential, - _endpoints = endpoints, - _plainContextString = plainContextString, - _requestor = Requestor( - logger: logger, - contextString: pollingDataSourceConfig.useReport - ? plainContextString - : base64UrlEncode(utf8.encode(plainContextString)), - method: pollingDataSourceConfig.useReport - ? RequestMethod.report - : RequestMethod.get, - httpProperties: httpProperties, - dataSourceConfig: pollingDataSourceConfig, - endpoints: endpoints, - credential: credential, - httpClientFactory: httpClientFactory) { - if (dataSourceConfig.useReport && !_useReport) { - _logger.warn('The browser EventSource cannot send REPORT requests. ' - 'Streaming with GET instead. Set useHttpStreamingOnWeb to stream ' - 'with REPORT on web.'); + _credential = credential { + final plainContextString = + jsonEncode(LDContextSerialization.toJson(context, isEvent: false)); + + _useReport = _dataSourceConfig.useReport && + streamingCustomMethodSupported( + useHttpStreamingOnWeb: useHttpStreamingOnWeb); + + if (_dataSourceConfig.useReport && !_useReport) { + _logger + .warn('The streaming transport on this platform cannot send REPORT ' + 'requests. Streaming with GET instead.'); } - } - /// The streaming URI for the request method. - Uri _buildUri() { - final contextString = _useReport - ? _plainContextString - : base64UrlEncode(utf8.encode(_plainContextString)); + _contextString = _useReport + ? plainContextString + : base64UrlEncode(utf8.encode(plainContextString)); + final path = _useReport - ? _dataSourceConfig.streamingReportPath(_credential, contextString) - : _dataSourceConfig.streamingGetPath(_credential, contextString); + ? _dataSourceConfig.streamingReportPath(credential, _contextString) + : _dataSourceConfig.streamingGetPath(credential, _contextString); + + String completeUrl = appendPath(endpoints.streaming, path); - var completeUrl = appendPath(_endpoints.streaming, path); if (_dataSourceConfig.withReasons) { completeUrl = '$completeUrl?withReasons=true'; } - return Uri.parse(completeUrl); + + _uri = Uri.parse(completeUrl); + + _requestor = Requestor( + logger: logger, + contextString: _contextString, + method: _useReport ? RequestMethod.report : RequestMethod.get, + httpProperties: httpProperties, + dataSourceConfig: pollingDataSourceConfig, + endpoints: endpoints, + credential: _credential, + httpClientFactory: httpClientFactory ?? _defaultHttpClientFactory); } @override @@ -154,15 +124,13 @@ final class StreamingDataSource implements DataSource { return; } _stopped = false; - final uri = _buildUri(); - _logger.debug('Establishing new streaming connection, uri: $uri'); + _logger.debug('Establishing new streaming connection, uri: $_uri'); final client = _clientBuilder( - uri, const {_putEvent, _patchEvent, _delete, _pingEvent}, + _uri, const {_putEvent, _patchEvent, _delete, _pingEvent}, headers: streamingRequestHeaders(_httpProperties), - body: _useReport ? _plainContextString : null, + body: _useReport ? _contextString : null, httpMethod: _useReport ? SseHttpMethod.report : SseHttpMethod.get, - logger: LDLoggerToEventSourceAdapter(_logger), - uriProvider: _buildUri); + logger: LDLoggerToEventSourceAdapter(_logger)); _client = client; _subscription = client.stream.listen((event) async { @@ -245,8 +213,6 @@ final class StreamingDataSource implements DataSource { // to the method documentation. _subscription?.cancel(); _subscription = null; - _client?.close(); - _client = null; _stopped = true; _dataController.close(); } 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 8ff8feec..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 @@ -157,8 +157,10 @@ void main() { required body, required httpMethod, required logger, - required uriProvider}) { - capturedUriProvider = uriProvider; + uriProvider}) { + if (uriProvider case final provider?) { + capturedUriProvider = provider; + } return SSEClient.testClient(uri, const {}); }, ); @@ -207,8 +209,10 @@ void main() { required body, required httpMethod, required logger, - required uriProvider}) { - capturedUriProvider = uriProvider; + uriProvider}) { + if (uriProvider case final provider?) { + capturedUriProvider = provider; + } return SSEClient.testClient(uri, const {}); }, ); @@ -351,10 +355,12 @@ void main() { required body, required httpMethod, required logger, - required uriProvider}) { + uriProvider}) { capturedMethod = httpMethod; capturedBody = body; - capturedUriProvider = uriProvider; + if (uriProvider case final provider?) { + capturedUriProvider = provider; + } return SSEClient.testClient(uri, const {}); }, ); 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 index 1e2b3183..f0268e1b 100644 --- a/packages/common_client/test/data_sources/streaming_client_web_test.dart +++ b/packages/common_client/test/data_sources/streaming_client_web_test.dart @@ -1,18 +1,12 @@ @TestOn('browser') library; -import 'dart:async'; - -import 'package:http/http.dart' as http; -import 'package:http/testing.dart'; 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_status_manager.dart'; import 'package:launchdarkly_common_client/src/data_sources/fdv2/data_system.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_dart_common/launchdarkly_dart_common.dart' - as ld_common; import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; import 'package:test/test.dart'; @@ -26,17 +20,15 @@ typedef _Call = ({ SseHttpMethod method }); -/// A builder that records its arguments and returns a test client. Events -/// on [source] reach the data source through the client. -SseClientBuilder _recording(List<_Call> calls, {Stream? source}) => - (uri, eventTypes, +/// 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, - required uriProvider}) { + uriProvider}) { calls.add((uri: uri, headers: headers, body: body, method: httpMethod)); - return SSEClient.testClient(uri, eventTypes, sourceStream: source); + return SSEClient.testClient(uri, eventTypes); }; void main() { @@ -119,9 +111,7 @@ void main() { group('FDv1 with useReport', () { StreamingDataSource makeDataSource(List<_Call> calls, - {bool useHttpStreamingOnWeb = false, - Stream? source, - MockClient? httpClient}) => + {bool useHttpStreamingOnWeb = false}) => StreamingDataSource( credential: 'the-credential', context: LDContextBuilder().kind('user', 'test').build(), @@ -132,11 +122,7 @@ void main() { httpProperties: HttpProperties(baseHeaders: {'X-LaunchDarkly-Tags': 'a/b'}), useHttpStreamingOnWeb: useHttpStreamingOnWeb, - clientBuilder: _recording(calls, source: source), - httpClientFactory: httpClient == null - ? null - : (properties) => ld_common.HttpClient( - client: httpClient, httpProperties: properties)); + clientBuilder: _recording(calls)); test('the browser EventSource streams with GET and the context in the URI', () { @@ -164,31 +150,5 @@ void main() { expect(calls.single.headers, isNot(contains('X-LaunchDarkly-Tags'))); dataSource.stop(); }); - - test('a ping poll keeps REPORT when the stream falls back to GET', - () async { - // A GET on the REPORT polling path would carry no context. - final pollRequests = []; - final httpClient = MockClient((request) async { - pollRequests.add(request); - return http.Response('{}', 200); - }); - final source = StreamController(); - final calls = <_Call>[]; - final dataSource = - makeDataSource(calls, source: source.stream, httpClient: httpClient); - - dataSource.start(); - source.add(const MessageEvent('ping', '', null)); - await Future.delayed(const Duration(milliseconds: 50)); - - expect(calls.single.method, SseHttpMethod.get); - expect(pollRequests, hasLength(1)); - expect(pollRequests.single.method, 'REPORT'); - expect(pollRequests.single.url.path, '/sdk/evalx/the-credential/context'); - expect(pollRequests.single.body, '{"key":"test","kind":"user"}'); - dataSource.stop(); - await source.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 6623a48a..1bd7a939 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 @@ -20,14 +20,11 @@ import 'package:test/test.dart'; class MockSseClient implements SSEClient { final Stream mockStream; - bool closed = false; MockSseClient(this.mockStream); @override - Future close() async { - closed = true; - } + Future close() async {} @override void restart() {} @@ -50,8 +47,6 @@ class MockSseClient implements SSEClient { bool withReasons = false, Duration? testingInterval, MockClient? mockHttpClient, - // Receives every client the builder creates. - List? createdClients, Function(Uri, HttpProperties, 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 @@ -61,6 +56,7 @@ class MockSseClient implements SSEClient { final logger = LDLogger(); final properties = inProperties ?? HttpProperties(); + final client = MockSseClient(mockStream); const sdkKey = 'dummy-key'; final flagManager = FlagManager(sdkKey: sdkKey, logger: logger, maxCachedContexts: 5); @@ -86,10 +82,8 @@ class MockSseClient implements SSEClient { required body, required httpMethod, required logger, - required uriProvider}) { + uriProvider}) { factoryCallback?.call(uri, properties, body, httpMethod); - final client = MockSseClient(mockStream); - createdClients?.add(client); return client; }); @@ -168,18 +162,6 @@ void main() { controller.sink.add(MessageEvent('put', '{}', null)); }); - test('it closes the client when it stops', () { - final clients = []; - final controller = StreamController(); - final (dataSource, _, _) = - makeDataSourceForTest(controller.stream, createdClients: clients); - - dataSource.start(); - dataSource.stop(); - - expect(clients.single.closed, isTrue); - }); - test('it uses the correct URL without reasons with REPORT', () { final controller = StreamController(); final (dataSource, _, statusManager) = makeDataSourceForTest( From 28ccd5df07f39b45da81b5a8ebac8968feff7f51 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Thu, 5 Nov 2026 17:46:49 -0500 Subject: [PATCH 5/9] test: adding more test for streaming with the custom eventsource --- .github/actions/ci/action.yml | 8 +- .../lib/src/config/data_system_config.dart | 7 +- .../lib/src/config/defaults/js_config.dart | 4 +- .../src/data_sources/fdv2/data_system.dart | 4 + .../src/data_sources/streaming_client.dart | 5 +- .../data_sources/streaming_data_source.dart | 7 +- .../lib/src/ld_common_client.dart | 9 +- .../lib/src/ld_common_config.dart | 14 ++- .../data_sources/fdv2/data_system_test.dart | 14 +++ .../streaming_client_web_test.dart | 82 +++++++++++++- .../streaming_data_source_test.dart | 103 ++++++++++++++---- .../default_data_source_factories_test.dart | 42 +++++++ 12 files changed, 256 insertions(+), 43 deletions(-) create mode 100644 packages/common_client/test/default_data_source_factories_test.dart diff --git a/.github/actions/ci/action.yml b/.github/actions/ci/action.yml index 65b044ca..220f2f61 100644 --- a/.github/actions/ci/action.yml +++ b/.github/actions/ci/action.yml @@ -73,10 +73,10 @@ runs: - name: Web Streaming Tests (Chrome) shell: bash - # The streaming client selection makes decisions that only apply on - # web: it removes the tags header and falls back to GET or polling - # without useHttpStreamingOnWeb. The Dart VM cannot run that code, so - # these tests run on Chrome. + # On web, the SDK removes the tags header from streaming requests. + # Without useHttpStreamingOnWeb, 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 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..19f748b6 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. Set `useHttpStreamingOnWeb` on the client + /// configuration to stream with POST on web. final bool usePost; const DataSystemConfig({ 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 e9b5674d..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,8 @@ final class DefaultDataSourceConfig { ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming; - /// The browser EventSource can only send GET requests without a body. The - /// HTTP-based client can send POST and REPORT. + /// 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 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 c46f2f8b..1d0fb7b2 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 @@ -43,6 +43,10 @@ final class FDv2DataSystem { final SseClientBuilder _sseClientBuilder; final HttpClientFactory? _httpClientFactory; + /// The builder that the streaming synchronizers use. + @visibleForTesting + SseClientBuilder get sseClientBuilder => _sseClientBuilder; + Selector _selector = Selector.empty; FDv2DataSystem({ diff --git a/packages/common_client/lib/src/data_sources/streaming_client.dart b/packages/common_client/lib/src/data_sources/streaming_client.dart index b5a35a0d..5fb13368 100644 --- a/packages/common_client/lib/src/data_sources/streaming_client.dart +++ b/packages/common_client/lib/src/data_sources/streaming_client.dart @@ -32,8 +32,9 @@ const String _tagsHeader = 'x-launchdarkly-tags'; /// Returns the headers for a streaming request. /// -/// On a platform where the streaming service rejects the application tags -/// header, the tags header is removed. +/// 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) { 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 31a71943..45bad64d 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'; @@ -57,6 +58,10 @@ final class StreamingDataSource implements DataSource { /// Used to track if there has been an unrecoverable error. bool _permanentShutdown = false; + /// The builder that [start] uses for the SSE client. + @visibleForTesting + SseClientBuilder get clientBuilder => _clientBuilder; + /// [useHttpStreamingOnWeb] selects the HTTP-based SSE client on web. The /// [clientBuilder] parameter is for tests, which inject a fake client. The /// [httpClientFactory] parameter is for tests of the requestor that serves @@ -88,7 +93,7 @@ final class StreamingDataSource implements DataSource { if (_dataSourceConfig.useReport && !_useReport) { _logger .warn('The streaming transport on this platform cannot send REPORT ' - 'requests. Streaming with GET instead.'); + 'requests. The SDK streams with GET instead.'); } _contextString = _useReport diff --git a/packages/common_client/lib/src/ld_common_client.dart b/packages/common_client/lib/src/ld_common_client.dart index 0f869734..0cbbefb4 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; @@ -272,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 { diff --git a/packages/common_client/lib/src/ld_common_config.dart b/packages/common_client/lib/src/ld_common_config.dart index 677b94e4..b414dd0f 100644 --- a/packages/common_client/lib/src/ld_common_config.dart +++ b/packages/common_client/lib/src/ld_common_config.dart @@ -63,8 +63,9 @@ 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 [useHttpStreamingOnWeb] is set. 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. @@ -168,9 +169,12 @@ abstract class LDCommonConfig { /// methods work on web. The option has no effect on other platforms, where /// the default client is already HTTP-based. /// - /// Most applications do not need this option. On web, the SDK does not - /// send the application tags header on streaming requests, because the - /// CORS allow-list of the streaming service does not include it. + /// Most applications do not need this option. With or without it, 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 this option, the SDK sends the other base headers on + /// web streaming requests, and each one must pass the CORS check of the + /// streaming service. final bool useHttpStreamingOnWeb; LDCommonConfig(this.sdkCredential, this.autoEnvAttributes, 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..328213b7 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 @@ -8,6 +8,7 @@ import 'package:launchdarkly_common_client/src/data_sources/fdv2/mode_definition 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 +18,7 @@ FDv2DataSystem makeDataSystem({ DataSystemConfig config = const DataSystemConfig(), bool? streamingPostSupported, LDLogger? logger, + bool useHttpStreamingOnWeb = false, }) => FDv2DataSystem( config: config, @@ -29,6 +31,7 @@ FDv2DataSystem makeDataSystem({ statusManager: DataSourceStatusManager(), cachedFlagsReader: (_) async => null, streamingPostSupported: streamingPostSupported, + useHttpStreamingOnWeb: useHttpStreamingOnWeb, ); LDContext _context() => LDContextBuilder().kind('user', 'bob').build(); @@ -99,6 +102,17 @@ void main() { expect(factories.keys, hasLength(4)); }); + group('useHttpStreamingOnWeb', () { + test('selects the default SSE client without the option', () { + expect(makeDataSystem().sseClientBuilder, same(SSEClient.new)); + }); + + test('selects the HTTP SSE client with the option', () { + expect(makeDataSystem(useHttpStreamingOnWeb: true).sseClientBuilder, + same(SSEClient.http)); + }); + }); + test('usePost is off by default', () { expect(const DataSystemConfig().usePost, isFalse); }); 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 index f0268e1b..2fb07029 100644 --- a/packages/common_client/test/data_sources/streaming_client_web_test.dart +++ b/packages/common_client/test/data_sources/streaming_client_web_test.dart @@ -5,11 +5,17 @@ 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_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 {} + // 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`. @@ -32,6 +38,14 @@ SseClientBuilder _recording(List<_Call> calls) => (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: { @@ -109,21 +123,77 @@ void main() { }); }); + 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', () { StreamingDataSource makeDataSource(List<_Call> calls, - {bool useHttpStreamingOnWeb = false}) => + {bool useHttpStreamingOnWeb = false, LDLogger? logger}) => StreamingDataSource( credential: 'the-credential', context: LDContextBuilder().kind('user', 'test').build(), endpoints: ServiceEndpoints(), - logger: LDLogger(level: LDLogLevel.none), + logger: logger ?? LDLogger(level: LDLogLevel.none), dataSourceConfig: StreamingDataSourceConfig(useReport: true), pollingDataSourceConfig: PollingDataSourceConfig(useReport: true), - httpProperties: - HttpProperties(baseHeaders: {'X-LaunchDarkly-Tags': 'a/b'}), + httpProperties: HttpProperties(baseHeaders: { + 'X-LaunchDarkly-Tags': 'a/b', + 'x-launchdarkly-user-agent': 'ua', + }), useHttpStreamingOnWeb: useHttpStreamingOnWeb, clientBuilder: _recording(calls)); + test('warns once when the stream falls back to GET', () { + final adapter = MockLogAdapter(); + when(() => adapter.log(any())).thenReturn(null); + + makeDataSource(<_Call>[], + 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('does not warn with the HTTP client', () { + final adapter = MockLogAdapter(); + when(() => adapter.log(any())).thenReturn(null); + + makeDataSource(<_Call>[], + useHttpStreamingOnWeb: true, + logger: LDLogger(adapter: adapter, level: LDLogLevel.debug)); + + verifyNever(() => adapter.log(any())); + }); + test('the browser EventSource streams with GET and the context in the URI', () { final calls = <_Call>[]; @@ -135,6 +205,8 @@ void main() { 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(); }); @@ -148,6 +220,8 @@ void main() { 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(); }); }); 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 1bd7a939..418bde4e 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. @@ -83,7 +85,7 @@ class MockSseClient implements SSEClient { required httpMethod, required logger, uriProvider}) { - factoryCallback?.call(uri, properties, body, httpMethod); + factoryCallback?.call(uri, headers, body, httpMethod); return client; }); @@ -114,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=='); }); @@ -131,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); }); @@ -148,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); @@ -162,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); @@ -182,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'); }); @@ -200,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); @@ -220,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(); @@ -574,4 +593,48 @@ void main() { expect(flagManager.environmentId, isNull); }); }); + + group('client builder selection', () { + StreamingDataSource make( + {bool useHttpStreamingOnWeb = false, + 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(), + useHttpStreamingOnWeb: useHttpStreamingOnWeb); + + setUpAll(() { + registerFallbackValue(LDLogRecord( + level: LDLogLevel.debug, + message: '', + time: DateTime.now(), + logTag: '')); + }); + + test('it uses the default SSE client without the option', () { + expect(make().clientBuilder, same(SSEClient.new)); + }); + + test('it uses the HTTP SSE client with the option', () { + expect(make(useHttpStreamingOnWeb: true).clientBuilder, + 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..dab9724e --- /dev/null +++ b/packages/common_client/test/default_data_source_factories_test.dart @@ -0,0 +1,42 @@ +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:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; +import 'package:test/test.dart'; + +final class TestConfig extends LDCommonConfig { + TestConfig(super.sdkCredential, super.autoEnvAttributes, + {super.useHttpStreamingOnWeb}); +} + +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.clientBuilder, same(SSEClient.new)); + }); + + test('the streaming source uses the HTTP SSE client with the option', () { + final source = streamingSourceFor(TestConfig( + 'key', AutoEnvAttributes.disabled, + useHttpStreamingOnWeb: true)); + + expect(source.clientBuilder, same(SSEClient.http)); + }); + }); +} From 5bd78b6eab934f3f21a67cce1430e990d27dc0a2 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Fri, 6 Nov 2026 16:50:33 -0500 Subject: [PATCH 6/9] fix: Use the client-side ID as the environment ID when the stream headers lack it on web --- .../data_sources/streaming_data_source.dart | 10 ++-- .../streaming_client_web_test.dart | 57 +++++++++++++++++++ 2 files changed, 61 insertions(+), 6 deletions(-) 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 45bad64d..a37f6f1e 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 @@ -178,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/test/data_sources/streaming_client_web_test.dart b/packages/common_client/test/data_sources/streaming_client_web_test.dart index 2fb07029..cef61dbf 100644 --- a/packages/common_client/test/data_sources/streaming_client_web_test.dart +++ b/packages/common_client/test/data_sources/streaming_client_web_test.dart @@ -1,8 +1,12 @@ @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'; @@ -16,6 +20,23 @@ 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`. @@ -225,4 +246,40 @@ void main() { 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(), + useHttpStreamingOnWeb: true, + clientBuilder: (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(); + }); + }); } From 80365afc17379a81892fa953b4b701e9f2b95030 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Mon, 9 Nov 2026 09:15:50 -0500 Subject: [PATCH 7/9] refactor: replace useHttpsStreamingOnWeb with an eventSource option that supplies the SSE client --- .github/actions/ci/action.yml | 2 +- .../lib/launchdarkly_common_client.dart | 4 ++ .../lib/src/config/data_system_config.dart | 4 +- .../src/data_sources/fdv2/data_system.dart | 16 +++--- .../src/data_sources/streaming_client.dart | 22 ++++---- .../data_sources/streaming_data_source.dart | 22 ++++---- .../lib/src/ld_common_client.dart | 4 +- .../lib/src/ld_common_config.dart | 41 ++++++++------ .../data_sources/fdv2/data_system_test.dart | 15 +++--- .../data_sources/streaming_client_test.dart | 20 ++----- .../streaming_client_web_test.dart | 53 ++++++++----------- .../streaming_data_source_test.dart | 16 +++--- .../default_data_source_factories_test.dart | 12 ++--- 13 files changed, 109 insertions(+), 122 deletions(-) diff --git a/.github/actions/ci/action.yml b/.github/actions/ci/action.yml index 220f2f61..c0f0c0a1 100644 --- a/.github/actions/ci/action.yml +++ b/.github/actions/ci/action.yml @@ -74,7 +74,7 @@ runs: - name: Web Streaming Tests (Chrome) shell: bash # On web, the SDK removes the tags header from streaming requests. - # Without useHttpStreamingOnWeb, it also streams with GET or polls + # 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: | 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 19f748b6..f4c9413a 100644 --- a/packages/common_client/lib/src/config/data_system_config.dart +++ b/packages/common_client/lib/src/config/data_system_config.dart @@ -97,8 +97,8 @@ final class DataSystemConfig { /// /// 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. Set `useHttpStreamingOnWeb` on the client - /// configuration to stream with POST on web. + /// 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/data_sources/fdv2/data_system.dart b/packages/common_client/lib/src/data_sources/fdv2/data_system.dart index 1d0fb7b2..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,5 +1,6 @@ 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'; @@ -45,7 +46,7 @@ final class FDv2DataSystem { /// The builder that the streaming synchronizers use. @visibleForTesting - SseClientBuilder get sseClientBuilder => _sseClientBuilder; + SseClientBuilder get eventSource => _sseClientBuilder; Selector _selector = Selector.empty; @@ -59,10 +60,9 @@ final class FDv2DataSystem { required Duration defaultPollingInterval, required DataSourceStatusManager statusManager, required CachedFlagsReader cachedFlagsReader, - // Selects the HTTP-based SSE client on web. - bool useHttpStreamingOnWeb = false, - // Builds the SSE client. Tests inject a fake. - SseClientBuilder? sseClientBuilder, + // 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 streaming client can send a POST request. Defaults to the // capability of the selected client. Tests override it. @@ -74,13 +74,11 @@ final class FDv2DataSystem { _withReasons = withReasons, _usePost = config.usePost, _streamingPostSupported = streamingPostSupported ?? - streamingCustomMethodSupported( - useHttpStreamingOnWeb: useHttpStreamingOnWeb), + streamingCustomMethodSupported(eventSource: eventSource), _defaultPollingInterval = defaultPollingInterval, _statusManager = statusManager, _cachedFlagsReader = cachedFlagsReader, - _sseClientBuilder = sseClientBuilder ?? - sseClientBuilderFor(useHttpStreamingOnWeb: useHttpStreamingOnWeb), + _sseClientBuilder = eventSource ?? SSEClient.new, _httpClientFactory = httpClientFactory, _connectionModeOverrides = config.connectionModes { if (_usePost && !_streamingPostSupported) { diff --git a/packages/common_client/lib/src/data_sources/streaming_client.dart b/packages/common_client/lib/src/data_sources/streaming_client.dart index 5fb13368..a8dc9483 100644 --- a/packages/common_client/lib/src/data_sources/streaming_client.dart +++ b/packages/common_client/lib/src/data_sources/streaming_client.dart @@ -6,7 +6,9 @@ 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. Tests inject a fake. +/// 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, @@ -14,18 +16,14 @@ typedef SseClientBuilder = SSEClient Function(Uri uri, Set eventTypes, required EventSourceLogger logger, Uri Function()? uriProvider}); -/// Returns the builder for the configuration. -/// -/// With [useHttpStreamingOnWeb], the SDK streams with the HTTP-based client -/// on every platform. Without it, the SDK uses the default client for the -/// platform. On platforms other than web, both are the HTTP-based client. -SseClientBuilder sseClientBuilderFor({required bool useHttpStreamingOnWeb}) => - useHttpStreamingOnWeb ? SSEClient.http : SSEClient.new; - /// Whether the streaming client can send a POST or REPORT request with a -/// body. The browser `EventSource` cannot. The HTTP-based client can. -bool streamingCustomMethodSupported({required bool useHttpStreamingOnWeb}) => - useHttpStreamingOnWeb || +/// body. +/// +/// The SDK treats a supplied [eventSource] as able to. Without one, the SDK +/// uses the default client for the platform. On web, that is the browser +/// `EventSource`, which cannot. +bool streamingCustomMethodSupported({required SseClientBuilder? eventSource}) => + eventSource != null || DefaultConfig.dataSourceConfig.streamingPostSupported; const String _tagsHeader = 'x-launchdarkly-tags'; 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 a37f6f1e..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 @@ -60,12 +60,13 @@ final class StreamingDataSource implements DataSource { /// The builder that [start] uses for the SSE client. @visibleForTesting - SseClientBuilder get clientBuilder => _clientBuilder; + SseClientBuilder get eventSource => _clientBuilder; - /// [useHttpStreamingOnWeb] selects the HTTP-based SSE client on web. The - /// [clientBuilder] parameter is for tests, which inject a fake client. The - /// [httpClientFactory] parameter is for tests of the requestor that serves - /// ping events. + /// [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, @@ -74,21 +75,20 @@ final class StreamingDataSource implements DataSource { required StreamingDataSourceConfig dataSourceConfig, required PollingDataSourceConfig pollingDataSourceConfig, required HttpProperties httpProperties, - bool useHttpStreamingOnWeb = false, - SseClientBuilder? clientBuilder, + SseClientBuilder? eventSource, + bool? streamingReportSupported, HttpClientFactory? httpClientFactory}) : _logger = logger.subLogger('StreamingDataSource'), _dataSourceConfig = dataSourceConfig, - _clientBuilder = clientBuilder ?? - sseClientBuilderFor(useHttpStreamingOnWeb: useHttpStreamingOnWeb), + _clientBuilder = eventSource ?? SSEClient.new, _httpProperties = httpProperties, _credential = credential { final plainContextString = jsonEncode(LDContextSerialization.toJson(context, isEvent: false)); _useReport = _dataSourceConfig.useReport && - streamingCustomMethodSupported( - useHttpStreamingOnWeb: useHttpStreamingOnWeb); + (streamingReportSupported ?? + streamingCustomMethodSupported(eventSource: eventSource)); if (_dataSourceConfig.useReport && !_useReport) { _logger diff --git a/packages/common_client/lib/src/ld_common_client.dart b/packages/common_client/lib/src/ld_common_client.dart index 0cbbefb4..fc7961d2 100644 --- a/packages/common_client/lib/src/ld_common_client.dart +++ b/packages/common_client/lib/src/ld_common_client.dart @@ -105,7 +105,7 @@ Map defaultDataSourceFactories( useReport: useReport, withReasons: withReasons), pollingDataSourceConfig: foregroundPollingConfig, httpProperties: httpProperties, - useHttpStreamingOnWeb: config.useHttpStreamingOnWeb); + eventSource: config.eventSource); } return { @@ -452,7 +452,7 @@ final class LDCommonClient { _config.dataSourceConfig.polling.pollingInterval, statusManager: _dataSourceStatusManager, cachedFlagsReader: _flagManager.readCached, - useHttpStreamingOnWeb: _config.useHttpStreamingOnWeb, + 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 b414dd0f..1d87347b 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'; @@ -65,7 +66,8 @@ final class DataSourceConfig { /// [useReport] determines if the data source will attempt to use the /// 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 [useHttpStreamingOnWeb] is set. The default value is `false`. + /// 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. @@ -160,22 +162,29 @@ abstract class LDCommonConfig { /// https://launchdarkly.com/docs/sdk/features/data-saving-mode final DataSystemConfig? dataSystem; - /// Streams with the HTTP-based SSE client on web. + /// Builds the SSE client that the SDK uses for streaming. /// - /// On web, the default streaming 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. With this option, the - /// SDK streams with `fetch()` through `package:http` instead, and both - /// methods work on web. The option has no effect on other platforms, where - /// the default client is already HTTP-based. + /// 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`. /// - /// Most applications do not need this option. With or without it, 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 this option, the SDK sends the other base headers on - /// web streaming requests, and each one must pass the CORS check of the - /// streaming service. - final bool useHttpStreamingOnWeb; + /// The SDK treats a supplied builder as able to send a request body with + /// the POST and REPORT methods. + /// + /// 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, @@ -190,7 +199,7 @@ abstract class LDCommonConfig { List? globalPrivateAttributes, List? hooks, this.dataSystem, - this.useHttpStreamingOnWeb = false}) + this.eventSource}) : httpProperties = httpProperties ?? HttpProperties(), serviceEndpoints = serviceEndpoints ?? ServiceEndpoints(), events = events ?? EventsConfig(), 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 328213b7..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,6 +5,7 @@ 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; @@ -18,7 +19,7 @@ FDv2DataSystem makeDataSystem({ DataSystemConfig config = const DataSystemConfig(), bool? streamingPostSupported, LDLogger? logger, - bool useHttpStreamingOnWeb = false, + SseClientBuilder? eventSource, }) => FDv2DataSystem( config: config, @@ -31,7 +32,7 @@ FDv2DataSystem makeDataSystem({ statusManager: DataSourceStatusManager(), cachedFlagsReader: (_) async => null, streamingPostSupported: streamingPostSupported, - useHttpStreamingOnWeb: useHttpStreamingOnWeb, + eventSource: eventSource, ); LDContext _context() => LDContextBuilder().kind('user', 'bob').build(); @@ -102,13 +103,13 @@ void main() { expect(factories.keys, hasLength(4)); }); - group('useHttpStreamingOnWeb', () { - test('selects the default SSE client without the option', () { - expect(makeDataSystem().sseClientBuilder, same(SSEClient.new)); + group('eventSource', () { + test('uses the default SSE client without a supplied builder', () { + expect(makeDataSystem().eventSource, same(SSEClient.new)); }); - test('selects the HTTP SSE client with the option', () { - expect(makeDataSystem(useHttpStreamingOnWeb: true).sseClientBuilder, + test('uses the supplied SSE client builder', () { + expect(makeDataSystem(eventSource: SSEClient.http).eventSource, same(SSEClient.http)); }); }); diff --git a/packages/common_client/test/data_sources/streaming_client_test.dart b/packages/common_client/test/data_sources/streaming_client_test.dart index 306daa6f..4b3e8c43 100644 --- a/packages/common_client/test/data_sources/streaming_client_test.dart +++ b/packages/common_client/test/data_sources/streaming_client_test.dart @@ -3,29 +3,17 @@ library; import 'package:launchdarkly_common_client/launchdarkly_common_client.dart'; import 'package:launchdarkly_common_client/src/data_sources/streaming_client.dart'; -import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; import 'package:test/test.dart'; // The web behavior is in streaming_client_web_test.dart. void main() { - group('sseClientBuilderFor', () { - test('selects the default client without the option', () { - expect(sseClientBuilderFor(useHttpStreamingOnWeb: false), SSEClient.new); - }); - - test('selects the HTTP client with the option', () { - expect(sseClientBuilderFor(useHttpStreamingOnWeb: true), SSEClient.http); - }); - }); - group('streamingCustomMethodSupported', () { test( - 'is true with and without the option, because the default client ' - 'is HTTP-based', () { - expect( - streamingCustomMethodSupported(useHttpStreamingOnWeb: false), isTrue); + 'is true with and without a supplied builder, because the default ' + 'client is HTTP-based', () { + expect(streamingCustomMethodSupported(eventSource: null), isTrue); expect( - streamingCustomMethodSupported(useHttpStreamingOnWeb: true), isTrue); + streamingCustomMethodSupported(eventSource: SSEClient.http), isTrue); }); }); 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 index cef61dbf..d2387f32 100644 --- a/packages/common_client/test/data_sources/streaming_client_web_test.dart +++ b/packages/common_client/test/data_sources/streaming_client_web_test.dart @@ -88,30 +88,19 @@ void main() { }); }); - group('sseClientBuilderFor', () { - test('selects the browser EventSource without the option', () { - expect(sseClientBuilderFor(useHttpStreamingOnWeb: false), SSEClient.new); - }); - - test('selects the HTTP client with the option', () { - expect(sseClientBuilderFor(useHttpStreamingOnWeb: true), SSEClient.http); - }); - }); - group('streamingCustomMethodSupported', () { - test('is false for the browser EventSource', () { - expect(streamingCustomMethodSupported(useHttpStreamingOnWeb: false), - isFalse); + test('is false for the default client, the browser EventSource', () { + expect(streamingCustomMethodSupported(eventSource: null), isFalse); }); - test('is true with the HTTP client', () { + test('is true with a supplied builder', () { expect( - streamingCustomMethodSupported(useHttpStreamingOnWeb: true), isTrue); + streamingCustomMethodSupported(eventSource: SSEClient.http), isTrue); }); }); group('FDv2 with usePost', () { - FDv2DataSystem makeDataSystem({bool useHttpStreamingOnWeb = false}) => + FDv2DataSystem makeDataSystem({SseClientBuilder? eventSource}) => FDv2DataSystem( config: const DataSystemConfig(usePost: true), credential: 'the-credential', @@ -122,7 +111,7 @@ void main() { defaultPollingInterval: const Duration(seconds: 300), statusManager: DataSourceStatusManager(), cachedFlagsReader: (_) async => null, - useHttpStreamingOnWeb: useHttpStreamingOnWeb, + eventSource: eventSource, ); test( @@ -135,8 +124,8 @@ void main() { definition.synchronizers.whereType(), isEmpty); }); - test('the HTTP client keeps the streaming entries', () { - final definition = makeDataSystem(useHttpStreamingOnWeb: true) + test('a supplied client keeps the streaming entries', () { + final definition = makeDataSystem(eventSource: SSEClient.http) .resolvedDefinition(ConnectionModeId.streaming); expect(definition.synchronizers.whereType(), @@ -174,8 +163,11 @@ void main() { }); 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 useHttpStreamingOnWeb = false, LDLogger? logger}) => + {bool? streamingReportSupported, LDLogger? logger}) => StreamingDataSource( credential: 'the-credential', context: LDContextBuilder().kind('user', 'test').build(), @@ -187,14 +179,15 @@ void main() { 'X-LaunchDarkly-Tags': 'a/b', 'x-launchdarkly-user-agent': 'ua', }), - useHttpStreamingOnWeb: useHttpStreamingOnWeb, - clientBuilder: _recording(calls)); + 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 = @@ -204,21 +197,19 @@ void main() { expect(records.single.message, contains('REPORT')); }); - test('does not warn with the HTTP client', () { + test('does not warn with a supplied client', () { final adapter = MockLogAdapter(); when(() => adapter.log(any())).thenReturn(null); makeDataSource(<_Call>[], - useHttpStreamingOnWeb: true, logger: LDLogger(adapter: adapter, level: LDLogLevel.debug)); verifyNever(() => adapter.log(any())); }); - test('the browser EventSource streams with GET and the context in the URI', - () { + test('the default client streams with GET and the context in the URI', () { final calls = <_Call>[]; - final dataSource = makeDataSource(calls); + final dataSource = makeDataSource(calls, streamingReportSupported: false); dataSource.start(); @@ -231,9 +222,10 @@ void main() { dataSource.stop(); }); - test('the HTTP client streams with REPORT and the context in the body', () { + test('a supplied client streams with REPORT and the context in the body', + () { final calls = <_Call>[]; - final dataSource = makeDataSource(calls, useHttpStreamingOnWeb: true); + final dataSource = makeDataSource(calls); dataSource.start(); @@ -260,8 +252,7 @@ void main() { dataSourceConfig: StreamingDataSourceConfig(), pollingDataSourceConfig: PollingDataSourceConfig(), httpProperties: HttpProperties(), - useHttpStreamingOnWeb: true, - clientBuilder: (uri, eventTypes, + eventSource: (uri, eventTypes, {required headers, required body, required httpMethod, 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 418bde4e..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 @@ -79,7 +79,7 @@ class MockSseClient implements SSEClient { ? (httpProps) => ld_common.HttpClient( client: mockHttpClient, httpProperties: httpProps) : null, - clientBuilder: (uri, eventTypes, + eventSource: (uri, eventTypes, {required headers, required body, required httpMethod, @@ -596,7 +596,7 @@ void main() { group('client builder selection', () { StreamingDataSource make( - {bool useHttpStreamingOnWeb = false, + {SseClientBuilder? eventSource, bool useReport = false, LDLogger? logger}) => StreamingDataSource( @@ -607,7 +607,7 @@ void main() { dataSourceConfig: StreamingDataSourceConfig(useReport: useReport), pollingDataSourceConfig: PollingDataSourceConfig(), httpProperties: HttpProperties(), - useHttpStreamingOnWeb: useHttpStreamingOnWeb); + eventSource: eventSource); setUpAll(() { registerFallbackValue(LDLogRecord( @@ -617,13 +617,13 @@ void main() { logTag: '')); }); - test('it uses the default SSE client without the option', () { - expect(make().clientBuilder, same(SSEClient.new)); + test('it uses the default SSE client without a supplied builder', () { + expect(make().eventSource, same(SSEClient.new)); }); - test('it uses the HTTP SSE client with the option', () { - expect(make(useHttpStreamingOnWeb: true).clientBuilder, - same(SSEClient.http)); + 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', () { diff --git a/packages/common_client/test/default_data_source_factories_test.dart b/packages/common_client/test/default_data_source_factories_test.dart index dab9724e..4c3255ed 100644 --- a/packages/common_client/test/default_data_source_factories_test.dart +++ b/packages/common_client/test/default_data_source_factories_test.dart @@ -2,12 +2,10 @@ 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:launchdarkly_event_source_client/launchdarkly_event_source_client.dart'; import 'package:test/test.dart'; final class TestConfig extends LDCommonConfig { - TestConfig(super.sdkCredential, super.autoEnvAttributes, - {super.useHttpStreamingOnWeb}); + TestConfig(super.sdkCredential, super.autoEnvAttributes, {super.eventSource}); } void main() { @@ -28,15 +26,15 @@ void main() { final source = streamingSourceFor(TestConfig('key', AutoEnvAttributes.disabled)); - expect(source.clientBuilder, same(SSEClient.new)); + expect(source.eventSource, same(SSEClient.new)); }); - test('the streaming source uses the HTTP SSE client with the option', () { + test('the streaming source uses the supplied SSE client builder', () { final source = streamingSourceFor(TestConfig( 'key', AutoEnvAttributes.disabled, - useHttpStreamingOnWeb: true)); + eventSource: SSEClient.http)); - expect(source.clientBuilder, same(SSEClient.http)); + expect(source.eventSource, same(SSEClient.http)); }); }); } From c55a9a8f4855fea10b66c25b11e68e6f83a18cd9 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Mon, 9 Nov 2026 10:44:32 -0500 Subject: [PATCH 8/9] fix: Fall back to GET on web when the app passes SSEClient.new with useReport or usePost --- .../src/data_sources/streaming_client.dart | 11 +++--- .../lib/src/ld_common_config.dart | 4 ++- .../data_sources/streaming_client_test.dart | 2 ++ .../streaming_client_web_test.dart | 34 +++++++++++++++++++ 4 files changed, 46 insertions(+), 5 deletions(-) diff --git a/packages/common_client/lib/src/data_sources/streaming_client.dart b/packages/common_client/lib/src/data_sources/streaming_client.dart index a8dc9483..871826eb 100644 --- a/packages/common_client/lib/src/data_sources/streaming_client.dart +++ b/packages/common_client/lib/src/data_sources/streaming_client.dart @@ -19,11 +19,14 @@ typedef SseClientBuilder = SSEClient Function(Uri uri, Set eventTypes, /// Whether the streaming client can send a POST or REPORT request with a /// body. /// -/// The SDK treats a supplied [eventSource] as able to. Without one, the SDK -/// uses the default client for the platform. On web, that is the browser -/// `EventSource`, which cannot. +/// 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 || + (eventSource != null && !identical(eventSource, SSEClient.new)) || DefaultConfig.dataSourceConfig.streamingPostSupported; const String _tagsHeader = 'x-launchdarkly-tags'; diff --git a/packages/common_client/lib/src/ld_common_config.dart b/packages/common_client/lib/src/ld_common_config.dart index 1d87347b..c404ccfd 100644 --- a/packages/common_client/lib/src/ld_common_config.dart +++ b/packages/common_client/lib/src/ld_common_config.dart @@ -173,7 +173,9 @@ abstract class LDCommonConfig { /// `SSEClient.http`. /// /// The SDK treats a supplied builder as able to send a request body with - /// the POST and REPORT methods. + /// 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 diff --git a/packages/common_client/test/data_sources/streaming_client_test.dart b/packages/common_client/test/data_sources/streaming_client_test.dart index 4b3e8c43..5b75c4a8 100644 --- a/packages/common_client/test/data_sources/streaming_client_test.dart +++ b/packages/common_client/test/data_sources/streaming_client_test.dart @@ -12,6 +12,8 @@ void main() { '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); }); 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 index d2387f32..cea7b688 100644 --- a/packages/common_client/test/data_sources/streaming_client_web_test.dart +++ b/packages/common_client/test/data_sources/streaming_client_web_test.dart @@ -93,6 +93,12 @@ void main() { 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); @@ -124,6 +130,14 @@ void main() { 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); @@ -197,6 +211,26 @@ void main() { 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); From 1cfae3d2cb6c293c820cf7da7e5d46b8f5776be5 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Tue, 10 Nov 2026 15:43:42 -0500 Subject: [PATCH 9/9] chore: Update launchdarkly_event_source_client to version 3.1.0 --- packages/common_client/pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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"