Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/actions/ci/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ runs:
cd packages/common
dart test test/serialization/canonicalize_json_platform_test.dart -p chrome --test-randomize-ordering-seed=random

- name: Web Streaming Tests (Chrome)
shell: bash
# On web, the SDK removes the tags header from streaming requests.
# Without a supplied eventSource, it also streams with GET or polls
# instead of streaming with REPORT or POST. The Dart VM resolves the
# web-only configuration to the io branch, so these tests run on Chrome.
run: |
cd packages/common_client
dart test test/data_sources/streaming_client_web_test.dart -p chrome --test-randomize-ordering-seed=random

- name: Contract Tests (FDv1)
shell: bash
run: |
Expand Down
4 changes: 4 additions & 0 deletions packages/common_client/lib/launchdarkly_common_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,10 @@ final class DataSystemConfig {
/// source keeps the context out of the URL the same way, with the REPORT
/// method that the FDv1 endpoints accept.
///
/// The browser EventSource cannot send a POST request. On web the SDK
/// skips streaming sources when this option is set and logs a warning,
/// so a mode that would stream polls instead.
/// On web, the default streaming client cannot send a POST request. The
/// SDK then skips the streaming sources, logs a warning, and a mode that
/// would stream polls instead. Pass `SSEClient.http` as the `eventSource`
/// option of the client configuration to stream with POST on web.
final bool usePost;

const DataSystemConfig({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,10 @@ final class DefaultDataSourceConfig {

ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming;

bool get streamingReportSupported => true;

/// The streaming transport can send a POST request with a body.
/// The default streaming client can send a POST or REPORT request with a
/// body.
bool get streamingPostSupported => true;

/// The streaming service accepts the application tags header.
bool get streamingTagsHeaderSupported => true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,11 @@ final class DefaultDataSourceConfig {

ConnectionMode get defaultInitialConnectionMode => ConnectionMode.streaming;

bool get streamingReportSupported => false;

/// The browser EventSource can only send GET requests without a body.
/// The default streaming client on web is the browser EventSource. It can
/// only send GET requests without a body.
bool get streamingPostSupported => false;

/// The CORS allow-list of the streaming service does not include the
/// application tags header. A browser blocks a request that sends it.
bool get streamingTagsHeaderSupported => false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ final class DefaultDataSourceConfig {
ConnectionMode get defaultInitialConnectionMode =>
throw Exception('Stub implementation');

bool get streamingReportSupported => throw Exception('Stub implementation');

bool get streamingPostSupported => throw Exception('Stub implementation');

bool get streamingTagsHeaderSupported =>
throw Exception('Stub implementation');
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart'
hide ServiceEndpoints;
import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart';
import 'package:meta/meta.dart';

import '../../config/data_system_config.dart';
import '../../config/defaults/default_config.dart';
import '../../config/service_endpoints.dart';
import '../../fdv2_connection_mode.dart';
import '../data_source_manager.dart';
import '../data_source_status_manager.dart';
import '../streaming_client.dart';
import 'built_in_modes.dart';
import 'cache_initializer.dart';
import 'entry_factories.dart';
Expand Down Expand Up @@ -40,9 +41,13 @@ final class FDv2DataSystem {
final DataSourceStatusManager _statusManager;
final Map<ConnectionModeId, ModeDefinition> _connectionModeOverrides;
final CachedFlagsReader _cachedFlagsReader;
final FDv2SseClientFactory _sseClientFactory;
final SseClientBuilder _sseClientBuilder;
final HttpClientFactory? _httpClientFactory;

/// The builder that the streaming synchronizers use.
@visibleForTesting
SseClientBuilder get eventSource => _sseClientBuilder;

Selector _selector = Selector.empty;

FDv2DataSystem({
Expand All @@ -55,10 +60,12 @@ final class FDv2DataSystem {
required Duration defaultPollingInterval,
required DataSourceStatusManager statusManager,
required CachedFlagsReader cachedFlagsReader,
FDv2SseClientFactory sseClientFactory = defaultSseClientFactory,
// Builds the SSE client. When it is null, the data system uses the
// default client for the platform. Tests inject a fake.
SseClientBuilder? eventSource,
HttpClientFactory? httpClientFactory,
// Whether the platform's streaming transport can send a POST request.
// Defaults to the platform's capability; tests override it.
// Whether the streaming client can send a POST request. Defaults to the
// capability of the selected client. Tests override it.
bool? streamingPostSupported,
}) : _credential = credential,
_logger = logger,
Expand All @@ -67,11 +74,11 @@ final class FDv2DataSystem {
_withReasons = withReasons,
_usePost = config.usePost,
_streamingPostSupported = streamingPostSupported ??
DefaultConfig.dataSourceConfig.streamingPostSupported,
streamingCustomMethodSupported(eventSource: eventSource),
_defaultPollingInterval = defaultPollingInterval,
_statusManager = statusManager,
_cachedFlagsReader = cachedFlagsReader,
_sseClientFactory = sseClientFactory,
_sseClientBuilder = eventSource ?? SSEClient.new,
_httpClientFactory = httpClientFactory,
_connectionModeOverrides = config.connectionModes {
if (_usePost && !_streamingPostSupported) {
Expand Down Expand Up @@ -179,7 +186,7 @@ final class FDv2DataSystem {

final synchronizerSlots = buildSynchronizerFactories(
modeDefinition.synchronizers, factoryContext,
sseClientFactory: _sseClientFactory)
sseClientBuilder: _sseClientBuilder)
.map((factory) => SynchronizerSlot(factory: factory))
.toList();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:launchdarkly_event_source_client/launchdarkly_event_source_clien

import '../../config/defaults/default_config.dart';
import '../../config/service_endpoints.dart';
import '../streaming_client.dart';
import '../streaming_data_source.dart' show LDLoggerToEventSourceAdapter;
import 'cache_initializer.dart' as cache_src;
import 'endpoints.dart';
Expand Down Expand Up @@ -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<String> _fdv2StreamEventNames = {
Expand All @@ -94,23 +84,6 @@ const Set<String> _fdv2StreamEventNames = {
'ping',
};

/// Constructs the production [SSEClient]. The default for the factory
/// builders; tests inject a fake through the same parameter.
SSEClient defaultSseClientFactory({
required Uri Function() uriProvider,
required HttpProperties httpProperties,
required String? body,
required SseHttpMethod method,
required EventSourceLogger logger,
}) {
return SSEClient(uriProvider(), _fdv2StreamEventNames,
headers: httpProperties.baseHeaders,
body: body,
httpMethod: method,
logger: logger,
uriProvider: uriProvider);
}

/// Builds the streaming URI for the current state. Invoked per
/// connection attempt so the `basis` parameter tracks the selector.
Uri _buildStreamingUri({
Expand Down Expand Up @@ -202,7 +175,7 @@ InitializerFactory createInitializerFactoryFromEntry(
SynchronizerFactory createSynchronizerFactoryFromEntry(
mode.SynchronizerEntry entry,
SourceFactoryContext ctx, {
FDv2SseClientFactory sseClientFactory = defaultSseClientFactory,
SseClientBuilder sseClientBuilder = SSEClient.new,
}) {
switch (entry) {
case final mode.PollingSynchronizer e:
Expand Down Expand Up @@ -235,13 +208,13 @@ SynchronizerFactory createSynchronizerFactoryFromEntry(
basis: selectorGetter(),
additionalQueryParameters: ctx.additionalQueryParameters,
);
final sseClient = sseClientFactory(
uriProvider: uriProvider,
httpProperties: ctx.httpProperties,
body: ctx.usePost ? ctx.contextJson : null,
method: ctx.usePost ? SseHttpMethod.post : SseHttpMethod.get,
logger: LDLoggerToEventSourceAdapter(ctx.logger),
);
final sseClient = sseClientBuilder(
uriProvider(), _fdv2StreamEventNames,
headers: streamingRequestHeaders(ctx.httpProperties),
body: ctx.usePost ? ctx.contextJson : null,
httpMethod: ctx.usePost ? SseHttpMethod.post : SseHttpMethod.get,
logger: LDLoggerToEventSourceAdapter(ctx.logger),
uriProvider: uriProvider);

// Legacy ping events trigger a one-shot poll.
final pingPollingBase = _buildPollingBase(
Expand Down Expand Up @@ -278,10 +251,10 @@ List<InitializerFactory> buildInitializerFactories(
List<SynchronizerFactory> buildSynchronizerFactories(
List<mode.SynchronizerEntry> entries,
SourceFactoryContext ctx, {
FDv2SseClientFactory sseClientFactory = defaultSseClientFactory,
SseClientBuilder sseClientBuilder = SSEClient.new,
}) {
return entries
.map((e) => createSynchronizerFactoryFromEntry(e, ctx,
sseClientFactory: sseClientFactory))
sseClientBuilder: sseClientBuilder))
.toList();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart';
import 'package:launchdarkly_event_source_client/launchdarkly_event_source_client.dart';

import '../config/defaults/default_config.dart';

/// Builds the SSE client for a streaming connection.
///
/// The type has the shape of the [SSEClient] constructors, so [SSEClient.new]
/// and [SSEClient.http] are builders. The SDK calls the builder once for each
/// streaming connection it needs, and closes the client when it stops
/// streaming.
typedef SseClientBuilder = SSEClient Function(Uri uri, Set<String> eventTypes,
{required Map<String, String> headers,
required String? body,
required SseHttpMethod httpMethod,
required EventSourceLogger logger,
Uri Function()? uriProvider});

/// Whether the streaming client can send a POST or REPORT request with a
/// body.
///
/// The SDK treats a supplied [eventSource] as able to send a body. The
/// default client, [SSEClient.new], has the capability of the platform. This
/// is true when it is passed as the builder and when [eventSource] is null.
/// On web, the default client is the browser `EventSource`, which cannot
/// send a body. The SDK cannot recognize a function that wraps the default
/// client.
bool streamingCustomMethodSupported({required SseClientBuilder? eventSource}) =>
(eventSource != null && !identical(eventSource, SSEClient.new)) ||
DefaultConfig.dataSourceConfig.streamingPostSupported;

const String _tagsHeader = 'x-launchdarkly-tags';

/// Returns the headers for a streaming request.
///
/// On web, the function removes the application tags header. The CORS
/// allow-list of the streaming service does not include it, so a browser
/// blocks a request that sends it.
Map<String, String> 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,
});
}
Loading
Loading