From f476654836a0b9fda7dbccda6999d0a63727256d Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Mon, 2 Nov 2026 16:58:31 -0500 Subject: [PATCH 1/7] test: Add a browser contract test service that uses the HTTP SSE client --- .github/workflows/ci.yml | 72 ++ .../README.md | 20 + .../README.md | 58 ++ .../analysis_options.yaml | 1 + .../bin/adapter.dart | 236 ++++++ .../lib/main.dart | 43 ++ .../lib/src/entity.dart | 532 +++++++++++++ .../lib/src/protocol.dart | 26 + .../pubspec.lock | 713 ++++++++++++++++++ .../pubspec.yaml | 28 + .../testharness-suppressions-fdv2.txt | 34 + .../testharness-suppressions.txt | 24 + .../web/index.html | 11 + melos.yaml | 16 + 14 files changed, 1814 insertions(+) create mode 100644 apps/flutter_web_contract_test_service/README.md create mode 100644 apps/flutter_web_contract_test_service/analysis_options.yaml create mode 100644 apps/flutter_web_contract_test_service/bin/adapter.dart create mode 100644 apps/flutter_web_contract_test_service/lib/main.dart create mode 100644 apps/flutter_web_contract_test_service/lib/src/entity.dart create mode 100644 apps/flutter_web_contract_test_service/lib/src/protocol.dart create mode 100644 apps/flutter_web_contract_test_service/pubspec.lock create mode 100644 apps/flutter_web_contract_test_service/pubspec.yaml create mode 100644 apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt create mode 100644 apps/flutter_web_contract_test_service/testharness-suppressions.txt create mode 100644 apps/flutter_web_contract_test_service/web/index.html diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 86303c0f..197b735f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,3 +28,75 @@ jobs: github_token: ${{ secrets.GITHUB_TOKEN }} flutter_version: ${{ matrix.versions.flutter }} dart_version: ${{ matrix.versions.dart }} + + browser-contract-tests: + # Runs the SDK in headless Chrome with the HTTP-based SSE client. The default + # web client cannot send a request body or report an HTTP error. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Install Dart + uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c # v1 + with: + sdk: '3.7.2' + + - name: Install Flutter + uses: subosito/flutter-action@0ca7a949e71ae44c8e688a51c5e7e93b2c87e295 # v2 + with: + flutter-version: '3.29.3' + channel: 'stable' + + - name: Install Melos + shell: bash + run: | + dart pub global activate melos + echo "$HOME/.pub-cache/bin" >> $GITHUB_PATH + + - name: Install Dependencies + shell: bash + run: melos bs + + - name: Build the browser test entity + shell: bash + run: | + pushd apps/flutter_web_contract_test_service + flutter build web --release --base-href /app/ -t lib/main.dart + + - name: Contract Tests (FDv1, browser) + shell: bash + env: + CHROME_EXECUTABLE: /usr/bin/google-chrome + run: | + pushd apps/flutter_web_contract_test_service + dart run bin/adapter.dart > adapter.log 2>&1 & disown + - uses: launchdarkly/gh-actions/actions/contract-tests@contract-tests-v1.3.0 + with: + test_service_port: 8080 + token: ${{ secrets.GITHUB_TOKEN }} + enable_persistence_tests: false + extra_params: '-status-timeout 100 --skip-from=./apps/flutter_web_contract_test_service/testharness-suppressions.txt' + + # The FDv1 run stops the adapter when it finishes, so start it again here. + - name: Contract Tests (FDv2, browser) + shell: bash + env: + CHROME_EXECUTABLE: /usr/bin/google-chrome + run: | + pushd apps/flutter_web_contract_test_service + dart run bin/adapter.dart > adapter-fdv2.log 2>&1 & disown + - uses: launchdarkly/gh-actions/actions/contract-tests@contract-tests-v1.3.0 + with: + test_service_port: 8080 + token: ${{ secrets.GITHUB_TOKEN }} + version: 'v3' + branch: 'v3' + enable_persistence_tests: false + extra_params: '-status-timeout 100 --skip-from=./apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt' + + - name: Upload Adapter Logs + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + if: always() + with: + name: browser-contract-test-adapter-logs + path: apps/flutter_web_contract_test_service/adapter*.log diff --git a/apps/flutter_client_contract_test_service/README.md b/apps/flutter_client_contract_test_service/README.md index 78ba32e3..9cf263d9 100644 --- a/apps/flutter_client_contract_test_service/README.md +++ b/apps/flutter_client_contract_test_service/README.md @@ -12,6 +12,26 @@ $ flutter test bin/contract_test_service.dart Server listening on port 8080 ``` +# Running the contract test harness + +The service only answers requests. The tests come from the +[sdk-test-harness](https://github.com/launchdarkly/sdk-test-harness). +Leave the service running, and run the harness in a second terminal: + +``` +$ cd apps/flutter_client_contract_test_service/ +$ curl -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/main/downloader/run.sh \ + | VERSION=v2 PARAMS="-url http://localhost:8080 -debug -status-timeout 100 -stop-service-at-end -skip-from testharness-suppressions.txt" sh +``` + +This runs the FDv1 tests. To run the FDv2 tests, use `v3` in the URL and set +`VERSION=v3`. The `-stop-service-at-end` option stops the service when the +harness finishes, so start the service again before the next run. +`testharness-suppressions.txt` lists the tests that this service skips. + +From the repository root, `melos run client-contract-tests` and +`melos run client-contract-tests-fdv2` do both steps. + # Updating the generated API Classes If you need to add or modify the OpenAPI yaml files to add or modify functionality, you will then probably need to regenerate the *.openapi.dart and *.openapi.g.dart files. This can be done by running the following command: diff --git a/apps/flutter_web_contract_test_service/README.md b/apps/flutter_web_contract_test_service/README.md new file mode 100644 index 00000000..606e2425 --- /dev/null +++ b/apps/flutter_web_contract_test_service/README.md @@ -0,0 +1,58 @@ +Contract test service that runs the Flutter SDK in a browser. + +The SDK streams with `SSEClient.http`, not with the browser native +`EventSource`. The native client cannot send a request body or report an HTTP +error. So this service is the only contract test run that covers `usePost` and +HTTP error handling for streaming on web. + +# How it works + +The contract test harness speaks REST. A browser cannot listen for HTTP +requests. So the service has two parts: + +- `bin/adapter.dart` runs on the Dart VM. It serves the REST API for the + harness, serves the web build, starts headless Chrome, and relays each + request to the browser over a websocket. +- `lib/main.dart` is a Flutter web app. It runs in the browser, connects to + the adapter, and runs each request with the SDK. + +The browser tells the adapter which capabilities it has when it connects. The +capabilities that depend on the streaming transport (`client-use-post` and +`client-event-source-http-errors`) come from the SSE client in use. + +# Running it + +You need Chrome. The adapter uses the `CHROME_EXECUTABLE` variable or the +`--chrome` option first. Otherwise it uses the Chrome app on macOS, and +`google-chrome` from your `PATH` on other platforms. + +``` +$ cd apps/flutter_web_contract_test_service/ +$ flutter build web --release --base-href /app/ -t lib/main.dart +$ dart run bin/adapter.dart +Adapter listening on port 8080 +Browser connected +``` + +Leave the adapter running, and run the +[sdk-test-harness](https://github.com/launchdarkly/sdk-test-harness) in a +second terminal: + +``` +$ cd apps/flutter_web_contract_test_service/ +$ curl -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/main/downloader/run.sh \ + | VERSION=v2 PARAMS="-url http://localhost:8080 -debug -status-timeout 100 -stop-service-at-end -skip-from testharness-suppressions.txt" sh +``` + +This runs the FDv1 tests. To run the FDv2 tests, use `v3` in the URL, set +`VERSION=v3`, and skip from `testharness-suppressions-fdv2.txt`. The +`-stop-service-at-end` option stops the adapter when the harness finishes, so +start the adapter again before the next run. + +From the repository root, `melos run client-web-contract-tests` (FDv1) and +`melos run client-web-contract-tests-fdv2` (FDv2) build the web app, start the +adapter, and run the harness. + +`testharness-suppressions.txt` (FDv1) and `testharness-suppressions-fdv2.txt` +(FDv2) list the harness tests that this service skips. They match the lists of +the JS browser SDK runs that use the fetch based event source. diff --git a/apps/flutter_web_contract_test_service/analysis_options.yaml b/apps/flutter_web_contract_test_service/analysis_options.yaml new file mode 100644 index 00000000..7662d510 --- /dev/null +++ b/apps/flutter_web_contract_test_service/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../common_analysis.yaml diff --git a/apps/flutter_web_contract_test_service/bin/adapter.dart b/apps/flutter_web_contract_test_service/bin/adapter.dart new file mode 100644 index 00000000..a56e1952 --- /dev/null +++ b/apps/flutter_web_contract_test_service/bin/adapter.dart @@ -0,0 +1,236 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:args/args.dart'; +import 'package:shelf/shelf.dart'; +import 'package:shelf/shelf_io.dart' as shelf_io; +import 'package:shelf_static/shelf_static.dart'; +import 'package:shelf_web_socket/shelf_web_socket.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +import 'package:flutter_web_contract_test_service/src/protocol.dart'; + +const String _appPath = 'app'; +const Duration _browserTimeout = Duration(seconds: 90); + +/// The contract test harness speaks REST. The SDK runs in a browser, which +/// cannot listen for HTTP requests. This adapter listens for the harness, +/// starts a headless browser, and relays each request to the browser over a +/// websocket. +final class Adapter { + final HttpServer _server; + final String _name; + Process? _browser; + WebSocketChannel? _channel; + List? _capabilities; + final Completer _ready = Completer(); + final Completer _stopped = Completer(); + final Map>> _pending = {}; + int _nextRequestId = 0; + + Adapter._(this._server, this._name); + + static Future start( + {required int port, required String webDir, required String name}) async { + final adapter = Adapter._( + await HttpServer.bind(InternetAddress.loopbackIPv4, port), name); + final staticHandler = + createStaticHandler(webDir, defaultDocument: 'index.html'); + final socketHandler = webSocketHandler(adapter._onConnect); + FutureOr handler(Request request) { + final segments = request.url.pathSegments; + if (request.url.path == websocketPath.substring(1)) { + return socketHandler(request); + } + if (segments.isNotEmpty && segments.first == _appPath) { + return staticHandler(request.change(path: _appPath)); + } + return adapter._rest(request); + } + + shelf_io.serveRequests(adapter._server, handler); + return adapter; + } + + int get port => _server.port; + + Future get stopped => _stopped.future; + + /// Starts the browser and waits for it to report that it is ready. + Future launchBrowser(String executable) async { + final profile = await Directory.systemTemp.createTemp('flutter-web-entity'); + _browser = await Process.start(executable, [ + '--headless=new', + '--no-sandbox', + '--disable-gpu', + '--no-first-run', + '--user-data-dir=${profile.path}', + 'http://localhost:$port/$_appPath/index.html', + ]); + unawaited(_browser!.exitCode.then((code) { + if (!_stopped.isCompleted) { + stderr.writeln('The browser exited with code $code.'); + _failPending('The browser exited.'); + } + })); + unawaited(stdout.addStream(_browser!.stdout)); + unawaited(stderr.addStream(_browser!.stderr)); + await _ready.future.timeout(_browserTimeout); + } + + void _onConnect(WebSocketChannel channel, String? protocol) { + _channel = channel; + channel.stream.listen((data) { + final message = jsonDecode(data as String) as Map; + if (message['type'] == helloType) { + _capabilities = (message['capabilities'] as List) + .map((capability) => capability as String) + .toList(); + if (!_ready.isCompleted) { + _ready.complete(); + } + return; + } + _pending.remove(message['id'])?.complete(message); + }, onDone: () { + _channel = null; + _failPending('The browser disconnected.'); + }); + } + + void _failPending(String reason) { + for (final pending in _pending.values) { + pending.complete({'status': 500, 'error': reason}); + } + _pending.clear(); + } + + Future> _send(Map request) { + final channel = _channel; + if (channel == null) { + return Future.value({'status': 503, 'error': 'No browser connected.'}); + } + final id = _nextRequestId++; + final completer = Completer>(); + _pending[id] = completer; + channel.sink.add(jsonEncode({...request, 'id': id})); + return completer.future; + } + + Future _rest(Request request) async { + final segments = request.url.pathSegments; + final method = request.method; + + if (segments.isEmpty) { + switch (method) { + case 'GET': + if (_capabilities case final capabilities?) { + return _json(200, {'name': _name, 'capabilities': capabilities}); + } + return Response(503, body: 'The browser is not ready.'); + case 'POST': + final reply = await _send({ + 'op': createOp, + 'body': jsonDecode(await request.readAsString()), + }); + if (reply['status'] == 201) { + return Response(201, headers: { + HttpHeaders.locationHeader: '/client/${reply['clientId']}' + }); + } + return _failure(reply); + case 'DELETE': + unawaited(Future(() async { + await shutdown(); + })); + return Response.ok(''); + } + } + + if (segments.length == 2 && segments.first == 'client') { + final clientId = int.tryParse(segments[1]); + if (clientId == null) { + return Response.notFound(''); + } + switch (method) { + case 'POST': + final reply = await _send({ + 'op': commandOp, + 'clientId': clientId, + 'body': jsonDecode(await request.readAsString()), + }); + return reply['status'] == 200 + ? _json(200, reply['body']) + : _failure(reply); + case 'DELETE': + final reply = await _send({'op': deleteOp, 'clientId': clientId}); + return reply['status'] == 200 ? Response.ok('') : _failure(reply); + } + } + return Response.notFound(''); + } + + Response _failure(Map reply) => + Response(reply['status'] as int, body: reply['error']?.toString() ?? ''); + + Response _json(int status, Object? body) => Response(status, + body: jsonEncode(body), + headers: {HttpHeaders.contentTypeHeader: 'application/json'}); + + Future shutdown() async { + if (_stopped.isCompleted) { + return; + } + _stopped.complete(); + _browser?.kill(); + await _channel?.sink.close(); + await _server.close(force: true); + } +} + +const String _macChrome = + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; + +/// The Chrome to start when the `--chrome` option is not given. The +/// `CHROME_EXECUTABLE` variable wins, then the usual install for the platform. +String _defaultChrome() { + if (Platform.environment['CHROME_EXECUTABLE'] case final path? + when path.isNotEmpty) { + return path; + } + if (Platform.isMacOS && File(_macChrome).existsSync()) { + return _macChrome; + } + return 'google-chrome'; +} + +Future main(List arguments) async { + final parser = ArgParser() + ..addOption('port', defaultsTo: '8080', help: 'The port for the harness.') + ..addOption('web-dir', + defaultsTo: 'build/web', help: 'The Flutter web build output.') + ..addOption('chrome', + defaultsTo: _defaultChrome(), + help: 'The Chrome executable. The CHROME_EXECUTABLE variable also ' + 'sets it.'); + final options = parser.parse(arguments); + + final adapter = await Adapter.start( + port: int.parse(options['port'] as String), + webDir: options['web-dir'] as String, + name: 'flutter-web-client-sdk'); + print('Adapter listening on port ${adapter.port}'); + final chrome = options['chrome'] as String; + try { + await adapter.launchBrowser(chrome); + } on ProcessException catch (error) { + stderr.writeln('Could not start Chrome ("$chrome"): ${error.message}. ' + 'Set CHROME_EXECUTABLE or pass --chrome with the path to Chrome.'); + await adapter.shutdown(); + exit(1); + } + print('Browser connected'); + await adapter.stopped; + exit(0); +} diff --git a/apps/flutter_web_contract_test_service/lib/main.dart b/apps/flutter_web_contract_test_service/lib/main.dart new file mode 100644 index 00000000..4aef1c9e --- /dev/null +++ b/apps/flutter_web_contract_test_service/lib/main.dart @@ -0,0 +1,43 @@ +import 'dart:convert'; + +import 'package:flutter/widgets.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +import 'src/entity.dart'; +import 'src/protocol.dart'; + +/// The browser half of the contract test service. It connects to the adapter +/// and runs the requests that the adapter relays from the test harness. +Future main() async { + try { + await _run(); + } catch (error, stack) { + // The adapter waits for the hello message. Print the reason so a failed + // start is visible in the browser console. + debugPrint('Entity failed to start: $error\n$stack'); + rethrow; + } +} + +Future _run() async { + WidgetsFlutterBinding.ensureInitialized(); + runApp(const SizedBox.shrink()); + + final uri = Uri( + scheme: Uri.base.scheme == 'https' ? 'wss' : 'ws', + host: Uri.base.host, + port: Uri.base.port, + path: websocketPath); + final channel = WebSocketChannel.connect(uri); + await channel.ready; + + final entity = Entity(); + channel.sink.add( + jsonEncode({'type': helloType, 'capabilities': entity.capabilities})); + + channel.stream.listen((data) async { + final request = jsonDecode(data as String) as Map; + final response = await entity.handle(request); + channel.sink.add(jsonEncode({...response, 'id': request['id']})); + }); +} diff --git a/apps/flutter_web_contract_test_service/lib/src/entity.dart b/apps/flutter_web_contract_test_service/lib/src/entity.dart new file mode 100644 index 00000000..504baebd --- /dev/null +++ b/apps/flutter_web_contract_test_service/lib/src/entity.dart @@ -0,0 +1,532 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart' + as common; +import 'package:launchdarkly_flutter_client_sdk/launchdarkly_flutter_client_sdk.dart'; + +import 'protocol.dart'; + +const int _defaultWaitTimeMillis = 5000; + +/// Runs the SDK in the browser for the contract test harness. +/// +/// The browser streams with [SSEClient.http], not with the browser native +/// `EventSource`. The native client cannot send a request body or report an +/// HTTP error. +final class Entity { + static const List _baseCapabilities = [ + 'client-side', + 'strongly-typed', + 'context-comparison', + 'service-endpoints', + 'tags', + 'client-independence', + 'inline-context-all', + 'anonymous-redaction', + 'client-per-context-summaries', + 'client-prereq-events', + 'client-prereq-cycle-detection', + 'fdv1-fallback', + ]; + + final Map _clients = {}; + int _nextClientId = 0; + + /// The capabilities that depend on the streaming transport are listed only + /// when the SSE client in use reports the matching capability. A client that + /// is never subscribed to does not open a connection. + List get capabilities { + final probe = SSEClient.http(Uri.parse('http://localhost'), const {}); + try { + return [ + ..._baseCapabilities, + if (probe.hasCapability(SSECapability.httpErrors)) + 'client-event-source-http-errors', + if (probe.hasCapability(SSECapability.customMethod)) 'client-use-post', + ]; + } finally { + probe.close(); + } + } + + /// Handles one request from the adapter and returns the response. The + /// response has a `status` that mirrors the HTTP status for the harness. + Future> handle(Map request) async { + try { + switch (request['op']) { + case createOp: + final clientId = + await _create(request['body'] as Map); + return {'status': 201, 'clientId': clientId}; + case commandOp: + final client = _clients[request['clientId']]; + if (client == null) { + return {'status': 404}; + } + return { + 'status': 200, + 'body': + await _command(client, request['body'] as Map) + }; + case deleteOp: + final client = _clients.remove(request['clientId']); + if (client == null) { + return {'status': 404}; + } + await client.close(); + return {'status': 200}; + default: + return {'status': 400, 'error': 'Unknown op: ${request['op']}'}; + } + } catch (error, stack) { + return {'status': 500, 'error': '$error\n$stack'}; + } + } + + Future _create(Map body) async { + final configuration = body['configuration'] as Map? ?? {}; + final clientSide = + configuration['clientSide'] as Map? ?? {}; + final tags = configuration['tags'] as Map?; + final polling = configuration['polling'] as Map?; + final streaming = configuration['streaming'] as Map?; + final events = configuration['events'] as Map?; + final usePost = clientSide['usePost'] as bool? ?? false; + final mappedDataSystem = _mapDataSystem( + configuration['dataSystem'] as Map?, + usePost: usePost); + final startWait = (configuration['startWaitTimeMs'] as num?)?.toInt() ?? + _defaultWaitTimeMillis; + + final config = LDConfig( + configuration['credential'] as String? ?? '', + AutoEnvAttributes.disabled, + applicationInfo: tags?['applicationId'] != null + ? ApplicationInfo( + applicationId: tags!['applicationId'] as String, + applicationVersion: tags['applicationVersion'] as String?) + : null, + persistence: PersistenceConfig(maxCachedContexts: 0), + serviceEndpoints: ServiceEndpoints.custom( + polling: polling?['baseUri'] as String?, + streaming: streaming?['baseUri'] as String?, + events: events?['baseUri'] as String?), + dataSourceConfig: DataSourceConfig( + initialConnectionMode: mappedDataSystem?.initialConnectionMode ?? + (streaming != null + ? ConnectionMode.streaming + : ConnectionMode.polling), + evaluationReasons: clientSide['evaluationReasons'] as bool?, + useReport: clientSide['useReport'] as bool?), + events: EventsConfig( + eventCapacity: (events?['capacity'] as num?)?.toInt(), + disabled: events == null, + diagnosticOptOut: !(events?['enableDiagnostics'] as bool? ?? true)), + allAttributesPrivate: events?['allAttributesPrivate'] as bool? ?? false, + globalPrivateAttributes: + (events?['globalPrivateAttributes'] as List?) + ?.map((attribute) => attribute as String) + .toList(), + dataSystem: mappedDataSystem?.config, + eventSourceFactory: (request) => SSEClient.http( + request.uriProvider(), request.eventTypes, + headers: request.headers, + body: request.body, + httpMethod: request.method, + logger: request.logger, + uriProvider: request.uriProvider), + ); + + final context = _flattenedListToContext(_serializedContextToFlattenedList( + clientSide['initialContext'] as Map)); + final client = LDClient(config, context); + try { + await client.start().timeout(Duration(milliseconds: startWait)); + } catch (_) { + // The harness checks the outcome through later commands. + } + + final clientId = _nextClientId++; + _clients[clientId] = client; + return clientId; + } + + Future> _command( + LDClient client, Map body) async { + switch (body['command']) { + case 'identifyEvent': + final context = _flattenedListToContext( + _serializedContextToFlattenedList((body['identifyEvent'] + as Map)['context'] as Map)); + await client.identify(context); + return {}; + case 'evaluate': + return _evaluate(client, body['evaluate'] as Map); + case 'evaluateAll': + return { + 'state': client.allFlags().map((key, value) => + MapEntry(key, common.LDValueSerialization.toJson(value))) + }; + case 'customEvent': + final event = body['customEvent'] as Map; + client.track(event['eventKey'] as String, + data: common.LDValueSerialization.fromJson(event['data']), + metricValue: (event['metricValue'] as num?)?.toDouble()); + return {}; + case 'flushEvents': + client.flush(); + return {}; + case 'contextBuild': + final context = _contextFromSingleOrMulti( + body['contextBuild'] as Map); + return { + 'output': jsonEncode( + common.LDContextSerialization.toJson(context, isEvent: false)) + }; + case 'contextConvert': + return _contextConvert((body['contextConvert'] + as Map)['input'] as String); + case 'contextComparison': + final comparison = body['contextComparison'] as Map; + return { + 'equals': _buildContextForComparison( + comparison['context1'] as Map) == + _buildContextForComparison( + comparison['context2'] as Map) + }; + default: + throw UnimplementedError('Unknown command: ${body['command']}'); + } + } + + Map _evaluate( + LDClient client, Map request) { + final flagKey = request['flagKey'] as String; + final defaultValue = request['defaultValue']; + final valueType = request['valueType'] as String?; + + if (request['detail'] as bool? ?? false) { + final LDEvaluationDetail detail; + switch (valueType) { + case 'bool': + final result = + client.boolVariationDetail(flagKey, defaultValue as bool); + detail = LDEvaluationDetail(LDValue.ofBool(result.value), + result.variationIndex, result.reason); + case 'int': + final result = + client.intVariationDetail(flagKey, (defaultValue as num).toInt()); + detail = LDEvaluationDetail(LDValue.ofNum(result.value), + result.variationIndex, result.reason); + case 'double': + final result = client.doubleVariationDetail( + flagKey, (defaultValue as num).toDouble()); + detail = LDEvaluationDetail(LDValue.ofNum(result.value), + result.variationIndex, result.reason); + case 'string': + final result = + client.stringVariationDetail(flagKey, defaultValue as String); + detail = LDEvaluationDetail(LDValue.ofString(result.value), + result.variationIndex, result.reason); + default: + detail = client.jsonVariationDetail( + flagKey, common.LDValueSerialization.fromJson(defaultValue)); + } + return common.LDEvaluationDetailSerialization.toJson(detail); + } + + final LDValue value; + switch (valueType) { + case 'bool': + value = + LDValue.ofBool(client.boolVariation(flagKey, defaultValue as bool)); + case 'int': + value = LDValue.ofNum( + client.intVariation(flagKey, (defaultValue as num).toInt())); + case 'double': + value = LDValue.ofNum( + client.doubleVariation(flagKey, (defaultValue as num).toDouble())); + case 'string': + value = LDValue.ofString( + client.stringVariation(flagKey, defaultValue as String)); + default: + value = client.jsonVariation( + flagKey, common.LDValueSerialization.fromJson(defaultValue)); + } + // A null result is omitted. An absent key reads the same as null. + return { + if (common.LDValueSerialization.toJson(value) case final Object json) + 'value': json, + }; + } + + Map _contextConvert(String input) { + try { + final decoded = jsonDecode(input) as Map; + final context = + _flattenedListToContext(_serializedContextToFlattenedList(decoded)); + if (context.valid) { + return { + 'output': jsonEncode( + common.LDContextSerialization.toJson(context, isEvent: false)) + }; + } + return {'error': 'Context was invalid.'}; + } catch (error) { + return {'error': error.toString()}; + } + } + + /// Translates the harness `dataSystem` configuration block into the + /// SDK's [DataSystemConfig] and an initial connection mode. + /// + /// [usePost] is the harness `clientSide.usePost` flag. Under FDv2 it + /// selects POST requests with the context in the body. + ({DataSystemConfig config, ConnectionMode initialConnectionMode})? + _mapDataSystem(Map? raw, {required bool usePost}) { + if (raw == null) { + return null; + } + + Fdv1FallbackConfig? parseFdv1Fallback() { + if (raw['fdv1Fallback'] case final Map fallback) { + return Fdv1FallbackConfig( + pollInterval: fallback['pollIntervalMs'] != null + ? Duration( + milliseconds: (fallback['pollIntervalMs'] as num).toInt()) + : null, + endpoints: fallback['baseUri'] != null + ? EndpointConfig( + pollingBaseUri: Uri.parse(fallback['baseUri'] as String)) + : null, + ); + } + return null; + } + + final fdv1Fallback = parseFdv1Fallback(); + + ModeDefinition translateMode(Map modeJson) { + final initializers = []; + for (final entry in (modeJson['initializers'] as List? ?? [])) { + final initializer = entry as Map; + if (initializer['polling'] case final Map polling) { + initializers.add(PollingInitializer( + endpoints: EndpointConfig( + pollingBaseUri: polling['baseUri'] != null + ? Uri.parse(polling['baseUri'] as String) + : null))); + } + } + + final synchronizers = []; + for (final entry in (modeJson['synchronizers'] as List? ?? [])) { + final synchronizer = entry as Map; + if (synchronizer['streaming'] + case final Map streaming) { + synchronizers.add(StreamingSynchronizer( + initialReconnectDelay: streaming['initialRetryDelayMs'] != null + ? Duration( + milliseconds: + (streaming['initialRetryDelayMs'] as num).toInt()) + : null, + endpoints: EndpointConfig( + streamingBaseUri: streaming['baseUri'] != null + ? Uri.parse(streaming['baseUri'] as String) + : null))); + } else if (synchronizer['polling'] + case final Map polling) { + synchronizers.add(PollingSynchronizer( + pollInterval: polling['pollIntervalMs'] != null + ? Duration( + milliseconds: (polling['pollIntervalMs'] as num).toInt()) + : null, + endpoints: EndpointConfig( + pollingBaseUri: polling['baseUri'] != null + ? Uri.parse(polling['baseUri'] as String) + : null))); + } + } + + return ModeDefinition( + initializers: initializers, + synchronizers: synchronizers, + fdv1Fallback: fdv1Fallback); + } + + ConnectionMode parseInitialMode(String? name) { + return switch (name) { + 'polling' => ConnectionMode.polling, + 'offline' => ConnectionMode.offline, + _ => ConnectionMode.streaming, + }; + } + + ConnectionModeId? builtInModeId(String name) { + return switch (name) { + 'streaming' => ConnectionModeId.streaming, + 'polling' => ConnectionModeId.polling, + 'background' => ConnectionModeId.background, + 'offline' => ConnectionModeId.offline, + _ => null, + }; + } + + if (raw['connectionModeConfig'] case final Map connMode) { + final overrides = {}; + if (connMode['customConnectionModes'] + case final Map modes) { + for (final entry in modes.entries) { + if (builtInModeId(entry.key) case final id?) { + overrides[id] = translateMode(entry.value as Map); + } + } + } + final initialModeName = connMode['initialConnectionMode'] as String?; + return ( + config: DataSystemConfig( + connectionModes: overrides, + initialConnectionMode: + initialModeName == null ? null : builtInModeId(initialModeName), + usePost: usePost, + ), + initialConnectionMode: parseInitialMode(initialModeName), + ); + } + + if (raw['initializers'] != null || raw['synchronizers'] != null) { + return ( + config: DataSystemConfig( + connectionModes: {ConnectionModeId.streaming: translateMode(raw)}, + usePost: usePost), + initialConnectionMode: ConnectionMode.streaming, + ); + } + + return ( + config: DataSystemConfig(usePost: usePost), + initialConnectionMode: ConnectionMode.streaming, + ); + } + + LDContext _contextFromSingleOrMulti(Map input) { + if (input['single'] case final Map single) { + return _flattenedListToContext([_buildContextToFlattenedMap(single)]); + } + if (input['multi'] case final List multi) { + return _flattenedListToContext([ + for (final single in multi) + _buildContextToFlattenedMap(single as Map) + ]); + } + throw UnsupportedError( + 'Expected a single or multi context, but neither were provided.'); + } + + LDContext _buildContextForComparison(Map input) { + final builder = LDContextBuilder(); + if (input['single'] case final Map single) { + _buildSingleAttributes( + builder.kind(single['kind'] as String, single['key'] as String?), + single); + return builder.build(); + } + if (input['multi'] case final List multi) { + for (final entry in multi) { + final single = entry as Map; + _buildSingleAttributes( + builder.kind(single['kind'] as String, single['key'] as String?), + single); + } + return builder.build(); + } + throw UnsupportedError( + 'Expected a single or multi context, but neither were provided.'); + } + + void _buildSingleAttributes(LDAttributesBuilder singleAttributesBuilder, + Map single) { + final attributes = single['attributes'] as List?; + final privateAttributes = single['privateAttributes'] as List?; + if (attributes != null) { + for (final item in attributes) { + singleAttributesBuilder.setValue( + item['name'], LDValue.ofDynamic(item['value'])); + } + } + if (privateAttributes != null) { + for (final item in privateAttributes) { + // A literal is not a valid reference as written, so it is escaped + // through the reference type first. + if (item['literal']) { + singleAttributesBuilder.addPrivateAttributes([ + AttributeReference.fromComponents( + common.AttributeReference.fromLiteral(item['value']) + .components) + .redactionName + ]); + } else { + singleAttributesBuilder.addPrivateAttributes([item['value']]); + } + } + } + } + + /// Creates a map for one context from the `contextBuild` command structure. + Map _buildContextToFlattenedMap(Map input) { + final result = { + 'kind': input['kind'], + 'key': input['key'], + 'name': input['name'], + 'anonymous': input['anonymous'], + }; + if (input['private'] != null) { + result['_meta'] = {'privateAttributes': input['private']}; + } + result.addAll(input['custom'] as Map? ?? {}); + return result; + } + + /// Creates a flat list of single context maps from serialized JSON. + List> _serializedContextToFlattenedList( + Map json) { + final result = >[]; + if (json['kind'] == 'multi') { + for (final entry in json.entries) { + if (entry.key == 'kind') { + continue; + } + final single = + Map.of(entry.value as Map); + single['kind'] = entry.key; + result.add(single); + } + } else { + result.add(Map.of(json)); + } + return result; + } + + LDContext _flattenedListToContext(List> flattened) { + final builder = LDContextBuilder(); + for (final attributes in flattened) { + final attrsBuilder = + builder.kind(attributes['kind'] ?? 'user', attributes['key']); + for (final a in attributes.entries) { + if (a.key == 'kind' || a.key == 'key') { + continue; + } + attrsBuilder.setValue( + a.key, common.LDValueSerialization.fromJson(a.value)); + } + final meta = attributes['_meta'] as Map? ?? {}; + final privateAttributes = + ((meta['privateAttributes'] ?? []) as List) + .map((e) => e as String) + .toList(); + attrsBuilder.addPrivateAttributes(privateAttributes); + } + return builder.build(); + } +} diff --git a/apps/flutter_web_contract_test_service/lib/src/protocol.dart b/apps/flutter_web_contract_test_service/lib/src/protocol.dart new file mode 100644 index 00000000..51c387f1 --- /dev/null +++ b/apps/flutter_web_contract_test_service/lib/src/protocol.dart @@ -0,0 +1,26 @@ +/// The messages that the adapter and the browser entity exchange over the +/// websocket. Every message is a JSON object. +/// +/// The browser sends one `hello` message when it is ready. It lists the +/// contract test capabilities of the SDK in the browser. +/// +/// The adapter sends a request with an `id` and an `op`. The browser answers +/// with a response that has the same `id`. +library; + +/// The path that the browser connects to. +const String websocketPath = '/ws'; + +/// The `type` of the first message from the browser. +const String helloType = 'hello'; + +/// Creates a client. The request `body` is the harness configuration. +/// The response has the `clientId` of the new client. +const String createOp = 'create'; + +/// Runs a command on a client. The request has a `clientId` and a `body`. +/// The response has a `body`. +const String commandOp = 'command'; + +/// Closes a client. The request has a `clientId`. +const String deleteOp = 'delete'; diff --git a/apps/flutter_web_contract_test_service/pubspec.lock b/apps/flutter_web_contract_test_service/pubspec.lock new file mode 100644 index 00000000..863d483a --- /dev/null +++ b/apps/flutter_web_contract_test_service/pubspec.lock @@ -0,0 +1,713 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d" + url: "https://pub.dev" + source: hosted + version: "93.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b + url: "https://pub.dev" + source: hosted + version: "10.0.1" + args: + dependency: "direct main" + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + cli_config: + dependency: transitive + description: + name: cli_config + sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec + url: "https://pub.dev" + source: hosted + version: "0.2.0" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: "89b8801ba49f8b593fbf2d3e59efd0f566c46cd4ba6837ae2610c72b52a0f899" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + connectivity_plus: + dependency: transitive + description: + name: connectivity_plus + sha256: d7749fd36d8b404a4935612b94eca7c3ce3705377ab678e24ff2a4301436f741 + url: "https://pub.dev" + source: hosted + version: "7.3.2" + connectivity_plus_platform_interface: + dependency: transitive + description: + name: connectivity_plus_platform_interface + sha256: "3c09627c536d22fd24691a905cdd8b14520de69da52c7a97499c8be5284a32ed" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + coverage: + dependency: transitive + description: + name: coverage + sha256: ff89e37c19355194e279d26dafe8e4bece46c9ea63a30be4dc68214f5bc290d3 + url: "https://pub.dev" + source: hosted + version: "1.16.0" + crypto: + dependency: transitive + description: + name: crypto + sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 + url: "https://pub.dev" + source: hosted + version: "3.0.8" + dbus: + dependency: transitive + description: + name: dbus + sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612 + url: "https://pub.dev" + source: hosted + version: "0.8.0" + device_info_plus: + dependency: transitive + description: + name: device_info_plus + sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa + url: "https://pub.dev" + source: hosted + version: "13.3.0" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" + url: "https://pub.dev" + source: hosted + version: "8.1.0" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: "404dbf9bce29beafbe9dcb19219447b6f7d49900cd42b8d3b7af102b24508e25" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + glob: + dependency: transitive + description: + name: glob + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: "361668bdd71f0ae2dc6d17b75a593520f3c414af6534f9eed1aa72049dd71d18" + url: "https://pub.dev" + source: hosted + version: "3.2.3" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + io: + dependency: transitive + description: + name: io + sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + launchdarkly_common_client: + dependency: "direct overridden" + description: + path: "../../packages/common_client" + relative: true + source: path + version: "1.15.0" + launchdarkly_dart_common: + dependency: "direct main" + description: + path: "../../packages/common" + relative: true + source: path + version: "1.8.2" + launchdarkly_event_source_client: + dependency: "direct overridden" + description: + path: "../../packages/event_source_client" + relative: true + source: path + version: "3.0.0" + launchdarkly_flutter_client_sdk: + dependency: "direct main" + description: + path: "../../packages/flutter_client_sdk" + relative: true + source: path + version: "4.21.0" + lints: + dependency: "direct dev" + description: + name: lints + sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 + url: "https://pub.dev" + source: hosted + version: "3.0.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 + url: "https://pub.dev" + source: hosted + version: "2.1.0" + nm: + dependency: transitive + description: + name: nm + sha256: "2ae480aa3379716b8bb58dfebb168e2919394c92b629efaaa0baaa5d140786e6" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + package_info_plus: + dependency: transitive + description: + name: package_info_plus + sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908" + url: "https://pub.dev" + source: hosted + version: "10.2.2" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 + url: "https://pub.dev" + source: hosted + version: "4.1.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" + url: "https://pub.dev" + source: hosted + version: "1.5.3" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + shared_preferences: + dependency: transitive + description: + name: shared_preferences + sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + url: "https://pub.dev" + source: hosted + version: "2.4.23" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea" + url: "https://pub.dev" + source: hosted + version: "2.5.7" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shelf: + dependency: "direct main" + description: + name: shelf + sha256: e75e9cf311d7fd712048038cc17c25199c38536c20330d53e7db058b543d5a48 + url: "https://pub.dev" + source: hosted + version: "1.4.3" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: "direct main" + description: + name: shelf_static + sha256: "480504af9e5323899c5be26a4f6c2fc4437d50954d39842f0290f4ae733d57b4" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + shelf_web_socket: + dependency: "direct main" + description: + name: shelf_web_socket + sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b + url: "https://pub.dev" + source: hosted + version: "2.1.2" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "14c2945847669b44089bb1222f66873d7ff7103c58911917f2a63c5a62327898" + url: "https://pub.dev" + source: hosted + version: "0.10.14" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test: + dependency: "direct dev" + description: + name: test + sha256: ca578dc12bb8b2f40b67b7d3bd2fac4f31c01a6ff7130a14e2597b919934507f + url: "https://pub.dev" + source: hosted + version: "1.31.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + url: "https://pub.dev" + source: hosted + version: "0.7.12" + test_core: + dependency: transitive + description: + name: test_core + sha256: d2e98ec12998368dc59ddd47ab709f2cd55acd6b66dc7db764455a44082f4bc5 + url: "https://pub.dev" + source: hosted + version: "0.6.18" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + uuid: + dependency: transitive + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" + url: "https://pub.dev" + source: hosted + version: "15.4.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: "direct main" + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + win32: + dependency: transitive + description: + name: win32 + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d + url: "https://pub.dev" + source: hosted + version: "6.4.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" + url: "https://pub.dev" + source: hosted + version: "3.0.3" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4" + url: "https://pub.dev" + source: hosted + version: "7.0.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" +sdks: + dart: ">=3.11.0 <4.0.0" + flutter: ">=3.41.0" diff --git a/apps/flutter_web_contract_test_service/pubspec.yaml b/apps/flutter_web_contract_test_service/pubspec.yaml new file mode 100644 index 00000000..0d0411bd --- /dev/null +++ b/apps/flutter_web_contract_test_service/pubspec.yaml @@ -0,0 +1,28 @@ +name: flutter_web_contract_test_service +description: >- + Contract test service that runs the Flutter SDK in a browser, using the + HTTP-based SSE client. +version: 1.0.0 + +environment: + sdk: ^3.4.0 + flutter: '>=3.22.0' + +publish_to: none + +dependencies: + flutter: + sdk: flutter + args: ^2.3.0 + launchdarkly_dart_common: + path: ../../packages/common + launchdarkly_flutter_client_sdk: + path: ../../packages/flutter_client_sdk + shelf: ^1.4.0 + shelf_static: ^1.1.0 + shelf_web_socket: ^2.0.0 + web_socket_channel: ^3.0.0 + +dev_dependencies: + lints: ^3.0.0 + test: ^1.24.3 diff --git a/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt b/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt new file mode 100644 index 00000000..ea57f58e --- /dev/null +++ b/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt @@ -0,0 +1,34 @@ +# FDv2 run (harness v3). Same list as the JS browser SDK data system runs +# (js-core, packages/sdk/browser/contract-tests/suppressions_datamode_changes.txt). +# +# SSEClient.http drops the x-launchdarkly-tags header on web, to avoid CORS +# preflight failures, so the stream tags assertions cannot pass. The poll tags +# assertions are skipped for the same reason as in the JS browser SDK. +tags/FDv1 fallback directive requests +tags/disallowed characters +tags/stream requests/{"applicationId":null,"applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/stream requests/{"applicationId":null,"applicationVersion":"________________________________________________________________"} +tags/stream requests/{"applicationId":"","applicationVersion":null} +tags/stream requests/{"applicationId":"","applicationVersion":""} +tags/stream requests/{"applicationId":"","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/stream requests/{"applicationId":"","applicationVersion":"________________________________________________________________"} +tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":null} +tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":""} +tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":"________________________________________________________________"} +tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":null} +tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":""} +tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":"________________________________________________________________"} +tags/poll requests/{"applicationId":null,"applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/poll requests/{"applicationId":null,"applicationVersion":"________________________________________________________________"} +tags/poll requests/{"applicationId":"","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/poll requests/{"applicationId":"","applicationVersion":"________________________________________________________________"} +tags/poll requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":null} +tags/poll requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":""} +tags/poll requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/poll requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":"________________________________________________________________"} +tags/poll requests/{"applicationId":"________________________________________________________________","applicationVersion":null} +tags/poll requests/{"applicationId":"________________________________________________________________","applicationVersion":""} +tags/poll requests/{"applicationId":"________________________________________________________________","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/poll requests/{"applicationId":"________________________________________________________________","applicationVersion":"________________________________________________________________"} diff --git a/apps/flutter_web_contract_test_service/testharness-suppressions.txt b/apps/flutter_web_contract_test_service/testharness-suppressions.txt new file mode 100644 index 00000000..3898006e --- /dev/null +++ b/apps/flutter_web_contract_test_service/testharness-suppressions.txt @@ -0,0 +1,24 @@ +# FDv1 run (harness v2). Same list as the JS browser SDK fetch EventSource run +# (js-core, packages/sdk/browser/contract-tests/suppressions_fetch_eventsource.txt). +# +# SSEClient.http drops the x-launchdarkly-tags header on web, because the +# LaunchDarkly streaming service CORS allow-list rejects it and a browser +# preflight with it fails. These stream assertions expect that header, so they +# cannot pass with this transport. The combinations that expect no header +# still run. +tags/stream requests/{"applicationId":null,"applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/stream requests/{"applicationId":null,"applicationVersion":"________________________________________________________________"} +tags/stream requests/{"applicationId":"","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/stream requests/{"applicationId":"","applicationVersion":"________________________________________________________________"} +tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":null} +tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":""} +tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":"________________________________________________________________"} +tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":null} +tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":""} +tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} +tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":"________________________________________________________________"} + +# The Flutter SDK does not reject tag values with disallowed characters. The +# existing Flutter contract test service skips this test for the same reason. +tags/disallowed characters diff --git a/apps/flutter_web_contract_test_service/web/index.html b/apps/flutter_web_contract_test_service/web/index.html new file mode 100644 index 00000000..e0d454f8 --- /dev/null +++ b/apps/flutter_web_contract_test_service/web/index.html @@ -0,0 +1,11 @@ + + + + + + Flutter SDK contract test entity + + + + + diff --git a/melos.yaml b/melos.yaml index 067bbb2f..d3d0b388 100644 --- a/melos.yaml +++ b/melos.yaml @@ -55,3 +55,19 @@ scripts: cd apps/flutter_client_contract_test_service && flutter test bin/contract_test_service.dart & cd apps/flutter_client_contract_test_service && curl -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/v3/downloader/run.sh | VERSION=v3 PARAMS="-url http://localhost:8080 -debug -status-timeout 100 -stop-service-at-end -skip-from testharness-suppressions.txt" sh + + client-web-contract-tests: + description: Runs the client-side contract tests (sdk-test-harness v2) with the SDK in headless Chrome. + run: > + cd apps/flutter_web_contract_test_service && + flutter build web --release --base-href /app/ -t lib/main.dart && + dart run bin/adapter.dart & + cd apps/flutter_web_contract_test_service && curl -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/main/downloader/run.sh | VERSION=v2 PARAMS="-url http://localhost:8080 -debug -status-timeout 100 -stop-service-at-end -skip-from testharness-suppressions.txt" sh + + client-web-contract-tests-fdv2: + description: Runs the FDv2 client-side contract tests (sdk-test-harness v3) with the SDK in headless Chrome. + run: > + cd apps/flutter_web_contract_test_service && + flutter build web --release --base-href /app/ -t lib/main.dart && + dart run bin/adapter.dart & + cd apps/flutter_web_contract_test_service && curl -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/v3/downloader/run.sh | VERSION=v3 PARAMS="-url http://localhost:8080 -debug -status-timeout 100 -stop-service-at-end -skip-from testharness-suppressions-fdv2.txt" sh From dc41c90ff1082b3029436e3619341fe9fdb2c9fa Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Tue, 3 Nov 2026 16:41:00 -0500 Subject: [PATCH 2/7] test: fixing test entity to match browser sdk behavior when dealing with application tags --- .../lib/src/entity.dart | 16 +++++++++++----- .../pubspec.yaml | 6 ++++-- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/apps/flutter_web_contract_test_service/lib/src/entity.dart b/apps/flutter_web_contract_test_service/lib/src/entity.dart index 504baebd..2089b61d 100644 --- a/apps/flutter_web_contract_test_service/lib/src/entity.dart +++ b/apps/flutter_web_contract_test_service/lib/src/entity.dart @@ -102,11 +102,17 @@ final class Entity { final config = LDConfig( configuration['credential'] as String? ?? '', AutoEnvAttributes.disabled, - applicationInfo: tags?['applicationId'] != null - ? ApplicationInfo( - applicationId: tags!['applicationId'] as String, - applicationVersion: tags['applicationVersion'] as String?) - : null, + applicationInfo: switch (tags) { + // An empty application ID is invalid, so ApplicationInfo drops it. + // This keeps a version-only tag configuration working. + final t? + when t['applicationId'] != null || + t['applicationVersion'] != null => + ApplicationInfo( + applicationId: t['applicationId'] as String? ?? '', + applicationVersion: t['applicationVersion'] as String?), + _ => null, + }, persistence: PersistenceConfig(maxCachedContexts: 0), serviceEndpoints: ServiceEndpoints.custom( polling: polling?['baseUri'] as String?, diff --git a/apps/flutter_web_contract_test_service/pubspec.yaml b/apps/flutter_web_contract_test_service/pubspec.yaml index 0d0411bd..e06b4994 100644 --- a/apps/flutter_web_contract_test_service/pubspec.yaml +++ b/apps/flutter_web_contract_test_service/pubspec.yaml @@ -20,8 +20,10 @@ dependencies: path: ../../packages/flutter_client_sdk shelf: ^1.4.0 shelf_static: ^1.1.0 - shelf_web_socket: ^2.0.0 - web_socket_channel: ^3.0.0 + # Version 1 is needed so the oldest tested Dart SDK can resolve `test`. + shelf_web_socket: '>=1.0.0 <4.0.0' + # Version 2 is needed so the oldest tested Dart SDK can resolve `test`. + web_socket_channel: '>=2.0.0 <4.0.0' dev_dependencies: lints: ^3.0.0 From 14c3958b1732c502d2b6dd06febdc627814ab35e Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Thu, 5 Nov 2026 12:04:53 -0500 Subject: [PATCH 3/7] refactor: Select the HTTP SSE client with useHttpStreamingOnWeb --- .../README.md | 14 +++---- .../lib/main.dart | 2 +- .../lib/src/entity.dart | 37 +++++-------------- .../testharness-suppressions-fdv2.txt | 5 ++- .../testharness-suppressions.txt | 6 +-- 5 files changed, 23 insertions(+), 41 deletions(-) diff --git a/apps/flutter_web_contract_test_service/README.md b/apps/flutter_web_contract_test_service/README.md index 606e2425..a3fc05fa 100644 --- a/apps/flutter_web_contract_test_service/README.md +++ b/apps/flutter_web_contract_test_service/README.md @@ -1,9 +1,9 @@ Contract test service that runs the Flutter SDK in a browser. -The SDK streams with `SSEClient.http`, not with the browser native -`EventSource`. The native client cannot send a request body or report an HTTP -error. So this service is the only contract test run that covers `usePost` and -HTTP error handling for streaming on web. +The SDK streams with the HTTP-based SSE client (`useHttpStreamingOnWeb`), not +with the browser native `EventSource`. The native client cannot send a request +body or report an HTTP error. So this service is the only contract test run +that covers `usePost` and HTTP error handling for streaming on web. # How it works @@ -16,9 +16,9 @@ requests. So the service has two parts: - `lib/main.dart` is a Flutter web app. It runs in the browser, connects to the adapter, and runs each request with the SDK. -The browser tells the adapter which capabilities it has when it connects. The -capabilities that depend on the streaming transport (`client-use-post` and -`client-event-source-http-errors`) come from the SSE client in use. +The browser tells the adapter which capabilities it has when it connects. +`client-use-post` and `client-event-source-http-errors` need the HTTP-based +SSE client. # Running it diff --git a/apps/flutter_web_contract_test_service/lib/main.dart b/apps/flutter_web_contract_test_service/lib/main.dart index 4aef1c9e..0b17c01f 100644 --- a/apps/flutter_web_contract_test_service/lib/main.dart +++ b/apps/flutter_web_contract_test_service/lib/main.dart @@ -33,7 +33,7 @@ Future _run() async { final entity = Entity(); channel.sink.add( - jsonEncode({'type': helloType, 'capabilities': entity.capabilities})); + jsonEncode({'type': helloType, 'capabilities': Entity.capabilities})); channel.stream.listen((data) async { final request = jsonDecode(data as String) as Map; diff --git a/apps/flutter_web_contract_test_service/lib/src/entity.dart b/apps/flutter_web_contract_test_service/lib/src/entity.dart index 2089b61d..a972f7ac 100644 --- a/apps/flutter_web_contract_test_service/lib/src/entity.dart +++ b/apps/flutter_web_contract_test_service/lib/src/entity.dart @@ -11,11 +11,13 @@ const int _defaultWaitTimeMillis = 5000; /// Runs the SDK in the browser for the contract test harness. /// -/// The browser streams with [SSEClient.http], not with the browser native -/// `EventSource`. The native client cannot send a request body or report an -/// HTTP error. +/// The SDK streams with the HTTP-based SSE client, not with the browser +/// native `EventSource`. The native client cannot send a request body or +/// report an HTTP error. final class Entity { - static const List _baseCapabilities = [ + /// The last two capabilities need the HTTP-based SSE client, which + /// `useHttpStreamingOnWeb` selects below. + static const List capabilities = [ 'client-side', 'strongly-typed', 'context-comparison', @@ -28,28 +30,13 @@ final class Entity { 'client-prereq-events', 'client-prereq-cycle-detection', 'fdv1-fallback', + 'client-event-source-http-errors', + 'client-use-post', ]; final Map _clients = {}; int _nextClientId = 0; - /// The capabilities that depend on the streaming transport are listed only - /// when the SSE client in use reports the matching capability. A client that - /// is never subscribed to does not open a connection. - List get capabilities { - final probe = SSEClient.http(Uri.parse('http://localhost'), const {}); - try { - return [ - ..._baseCapabilities, - if (probe.hasCapability(SSECapability.httpErrors)) - 'client-event-source-http-errors', - if (probe.hasCapability(SSECapability.customMethod)) 'client-use-post', - ]; - } finally { - probe.close(); - } - } - /// Handles one request from the adapter and returns the response. The /// response has a `status` that mirrors the HTTP status for the harness. Future> handle(Map request) async { @@ -135,13 +122,7 @@ final class Entity { ?.map((attribute) => attribute as String) .toList(), dataSystem: mappedDataSystem?.config, - eventSourceFactory: (request) => SSEClient.http( - request.uriProvider(), request.eventTypes, - headers: request.headers, - body: request.body, - httpMethod: request.method, - logger: request.logger, - uriProvider: request.uriProvider), + useHttpStreamingOnWeb: true, ); final context = _flattenedListToContext(_serializedContextToFlattenedList( diff --git a/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt b/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt index ea57f58e..573c6c71 100644 --- a/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt +++ b/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt @@ -1,8 +1,9 @@ # FDv2 run (harness v3). Same list as the JS browser SDK data system runs # (js-core, packages/sdk/browser/contract-tests/suppressions_datamode_changes.txt). # -# SSEClient.http drops the x-launchdarkly-tags header on web, to avoid CORS -# preflight failures, so the stream tags assertions cannot pass. The poll tags +# On web, the SDK drops the x-launchdarkly-tags header from streaming +# requests, to avoid CORS preflight failures, so the stream tags assertions +# cannot pass. The poll tags # assertions are skipped for the same reason as in the JS browser SDK. tags/FDv1 fallback directive requests tags/disallowed characters diff --git a/apps/flutter_web_contract_test_service/testharness-suppressions.txt b/apps/flutter_web_contract_test_service/testharness-suppressions.txt index 3898006e..79162528 100644 --- a/apps/flutter_web_contract_test_service/testharness-suppressions.txt +++ b/apps/flutter_web_contract_test_service/testharness-suppressions.txt @@ -1,9 +1,9 @@ # FDv1 run (harness v2). Same list as the JS browser SDK fetch EventSource run # (js-core, packages/sdk/browser/contract-tests/suppressions_fetch_eventsource.txt). # -# SSEClient.http drops the x-launchdarkly-tags header on web, because the -# LaunchDarkly streaming service CORS allow-list rejects it and a browser -# preflight with it fails. These stream assertions expect that header, so they +# On web, the SDK drops the x-launchdarkly-tags header from streaming +# requests, because the LaunchDarkly streaming service CORS allow-list rejects +# it and a browser preflight with it fails. These stream assertions expect that header, so they # cannot pass with this transport. The combinations that expect no header # still run. tags/stream requests/{"applicationId":null,"applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} From 6582a1fdeda16f1090696c1591da09c38fb8e443 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Fri, 6 Nov 2026 10:19:05 -0500 Subject: [PATCH 4/7] fix: Keep the browser contract test adapter alive on bad input and clean up Chrome on exit --- .../README.md | 12 +- .../bin/adapter.dart | 91 ++++++++--- .../lib/src/entity.dart | 13 +- .../test/adapter_test.dart | 153 ++++++++++++++++++ .../testharness-suppressions-fdv2.txt | 26 ++- .../testharness-suppressions.txt | 19 +-- 6 files changed, 271 insertions(+), 43 deletions(-) create mode 100644 apps/flutter_web_contract_test_service/test/adapter_test.dart diff --git a/apps/flutter_web_contract_test_service/README.md b/apps/flutter_web_contract_test_service/README.md index a3fc05fa..6307cdb1 100644 --- a/apps/flutter_web_contract_test_service/README.md +++ b/apps/flutter_web_contract_test_service/README.md @@ -22,9 +22,10 @@ SSE client. # Running it -You need Chrome. The adapter uses the `CHROME_EXECUTABLE` variable or the -`--chrome` option first. Otherwise it uses the Chrome app on macOS, and -`google-chrome` from your `PATH` on other platforms. +You need Chrome. The `--chrome` option sets the path to Chrome. Without the +option, the adapter uses the `CHROME_EXECUTABLE` variable. Otherwise it uses +the Chrome app on macOS, and `google-chrome` from your `PATH` on other +platforms. ``` $ cd apps/flutter_web_contract_test_service/ @@ -54,5 +55,6 @@ From the repository root, `melos run client-web-contract-tests` (FDv1) and adapter, and run the harness. `testharness-suppressions.txt` (FDv1) and `testharness-suppressions-fdv2.txt` -(FDv2) list the harness tests that this service skips. They match the lists of -the JS browser SDK runs that use the fetch based event source. +(FDv2) list the harness tests that this service skips. They start from the +lists of the JS browser SDK runs that use the fetch-based event source, and +each file states where it differs. diff --git a/apps/flutter_web_contract_test_service/bin/adapter.dart b/apps/flutter_web_contract_test_service/bin/adapter.dart index a56e1952..e9e21416 100644 --- a/apps/flutter_web_contract_test_service/bin/adapter.dart +++ b/apps/flutter_web_contract_test_service/bin/adapter.dart @@ -22,10 +22,12 @@ final class Adapter { final HttpServer _server; final String _name; Process? _browser; + Directory? _profile; WebSocketChannel? _channel; List? _capabilities; final Completer _ready = Completer(); final Completer _stopped = Completer(); + bool _stopping = false; final Map>> _pending = {}; int _nextRequestId = 0; @@ -37,7 +39,11 @@ final class Adapter { await HttpServer.bind(InternetAddress.loopbackIPv4, port), name); final staticHandler = createStaticHandler(webDir, defaultDocument: 'index.html'); - final socketHandler = webSocketHandler(adapter._onConnect); + // Only the page that this adapter serves may drive the relay. + final socketHandler = webSocketHandler(adapter._onConnect, allowedOrigins: [ + 'http://localhost:${adapter.port}', + 'http://127.0.0.1:${adapter.port}', + ]); FutureOr handler(Request request) { final segments = request.url.pathSegments; if (request.url.path == websocketPath.substring(1)) { @@ -57,10 +63,14 @@ final class Adapter { Future get stopped => _stopped.future; - /// Starts the browser and waits for it to report that it is ready. + /// Starts headless Chrome and waits for the page to send its hello message. + /// + /// Throws a [TimeoutException] if the page does not connect in time, and a + /// [StateError] if the browser exits first. Future launchBrowser(String executable) async { - final profile = await Directory.systemTemp.createTemp('flutter-web-entity'); - _browser = await Process.start(executable, [ + final profile = + _profile = await Directory.systemTemp.createTemp('flutter-web-entity'); + final browser = _browser = await Process.start(executable, [ '--headless=new', '--no-sandbox', '--disable-gpu', @@ -68,21 +78,34 @@ final class Adapter { '--user-data-dir=${profile.path}', 'http://localhost:$port/$_appPath/index.html', ]); - unawaited(_browser!.exitCode.then((code) { - if (!_stopped.isCompleted) { - stderr.writeln('The browser exited with code $code.'); - _failPending('The browser exited.'); + unawaited(browser.exitCode.then((code) { + if (_stopping) { + return; + } + stderr.writeln('The browser exited with code $code.'); + if (!_ready.isCompleted) { + _ready.completeError(StateError('The browser exited with code $code.')); } + _failPending('The browser exited.'); })); - unawaited(stdout.addStream(_browser!.stdout)); - unawaited(stderr.addStream(_browser!.stderr)); + // Forward the browser output without binding the process sinks. A bound + // sink rejects every other write to it, and shelf logs handler errors to + // stderr. + browser.stdout.listen(stdout.add); + browser.stderr.listen(stderr.add); await _ready.future.timeout(_browserTimeout); } void _onConnect(WebSocketChannel channel, String? protocol) { _channel = channel; channel.stream.listen((data) { - final message = jsonDecode(data as String) as Map; + final Map message; + try { + message = jsonDecode(data as String) as Map; + } catch (error) { + stderr.writeln('Ignored a malformed websocket message: $error'); + return; + } if (message['type'] == helloType) { _capabilities = (message['capabilities'] as List) .map((capability) => capability as String) @@ -94,8 +117,11 @@ final class Adapter { } _pending.remove(message['id'])?.complete(message); }, onDone: () { - _channel = null; - _failPending('The browser disconnected.'); + // A newer connection may already own the relay. + if (identical(_channel, channel)) { + _channel = null; + _failPending('The browser disconnected.'); + } }); } @@ -178,14 +204,25 @@ final class Adapter { body: jsonEncode(body), headers: {HttpHeaders.contentTypeHeader: 'application/json'}); + /// Stops the browser, deletes its profile, and closes the server. Safe to + /// call more than once. Future shutdown() async { - if (_stopped.isCompleted) { - return; + if (_stopping) { + return _stopped.future; + } + _stopping = true; + final browser = _browser; + if (browser != null) { + browser.kill(); + await browser.exitCode + .timeout(const Duration(seconds: 5), onTimeout: () => -1); + } + if (_profile case final profile?) { + await profile.delete(recursive: true).catchError((_) => profile); } - _stopped.complete(); - _browser?.kill(); await _channel?.sink.close(); - await _server.close(force: true); + await _server.close(); + _stopped.complete(); } } @@ -221,6 +258,15 @@ Future main(List arguments) async { webDir: options['web-dir'] as String, name: 'flutter-web-client-sdk'); print('Adapter listening on port ${adapter.port}'); + // The harness normally stops the adapter with DELETE. Stop the browser on + // a signal too, so an interrupted run leaves no Chrome behind. + for (final signal in [ProcessSignal.sigint, ProcessSignal.sigterm]) { + signal.watch().listen((_) async { + await adapter.shutdown(); + exit(1); + }); + } + final chrome = options['chrome'] as String; try { await adapter.launchBrowser(chrome); @@ -229,6 +275,15 @@ Future main(List arguments) async { 'Set CHROME_EXECUTABLE or pass --chrome with the path to Chrome.'); await adapter.shutdown(); exit(1); + } on TimeoutException { + stderr.writeln('The page did not connect within $_browserTimeout. ' + 'Check that the web app was built with --base-href /$_appPath/.'); + await adapter.shutdown(); + exit(1); + } on StateError catch (error) { + stderr.writeln(error.message); + await adapter.shutdown(); + exit(1); } print('Browser connected'); await adapter.stopped; diff --git a/apps/flutter_web_contract_test_service/lib/src/entity.dart b/apps/flutter_web_contract_test_service/lib/src/entity.dart index a972f7ac..d0199e32 100644 --- a/apps/flutter_web_contract_test_service/lib/src/entity.dart +++ b/apps/flutter_web_contract_test_service/lib/src/entity.dart @@ -15,11 +15,13 @@ const int _defaultWaitTimeMillis = 5000; /// native `EventSource`. The native client cannot send a request body or /// report an HTTP error. final class Entity { - /// The last two capabilities need the HTTP-based SSE client, which - /// `useHttpStreamingOnWeb` selects below. + /// `client-event-source-http-errors` and `client-use-post` need the + /// HTTP-based SSE client. Keep `useHttpStreamingOnWeb: true` in [_create] + /// while the list declares them. static const List capabilities = [ 'client-side', 'strongly-typed', + 'context-type', 'context-comparison', 'service-endpoints', 'tags', @@ -30,6 +32,7 @@ final class Entity { 'client-prereq-events', 'client-prereq-cycle-detection', 'fdv1-fallback', + 'polling-gzip', 'client-event-source-http-errors', 'client-use-post', ]; @@ -498,8 +501,10 @@ final class Entity { LDContext _flattenedListToContext(List> flattened) { final builder = LDContextBuilder(); for (final attributes in flattened) { - final attrsBuilder = - builder.kind(attributes['kind'] ?? 'user', attributes['key']); + // Explicit casts, because a release web build omits the implicit ones + // and would accept a key that is not a string. + final attrsBuilder = builder.kind(attributes['kind'] as String? ?? 'user', + attributes['key'] as String?); for (final a in attributes.entries) { if (a.key == 'kind' || a.key == 'key') { continue; diff --git a/apps/flutter_web_contract_test_service/test/adapter_test.dart b/apps/flutter_web_contract_test_service/test/adapter_test.dart new file mode 100644 index 00000000..594186d4 --- /dev/null +++ b/apps/flutter_web_contract_test_service/test/adapter_test.dart @@ -0,0 +1,153 @@ +// Tests for the adapter process. They do not need Chrome. The adapter starts +// with `--chrome` pointing at a shell script that only sleeps, so the child +// holds the stdio pipes the same way a real browser does. +// +// Run from this directory with `flutter test test/adapter_test.dart`. + +@TestOn('vm') +library; + +import 'dart:async'; +import 'dart:io'; + +import 'package:test/test.dart'; + +void main() { + late Directory scratch; + late Process adapter; + late int port; + late File fakeChromePidFile; + late StringBuffer stderrBuffer; + + int? fakeChromePid() { + if (!fakeChromePidFile.existsSync()) { + return null; + } + return int.tryParse(fakeChromePidFile.readAsStringSync().trim()); + } + + bool processExists(int pid) => Process.killPid(pid, ProcessSignal.sigcont); + + setUp(() async { + stderrBuffer = StringBuffer(); + scratch = await Directory.systemTemp.createTemp('adapter-test-'); + // The static handler needs an existing directory with an index file. + final webDir = Directory('${scratch.path}/web')..createSync(); + File('${webDir.path}/index.html').writeAsStringSync(''); + + // A stand-in for Chrome. It records its PID so the test can check for + // it and kill it, then holds stdout and stderr open. + fakeChromePidFile = File('${scratch.path}/chrome.pid'); + final fakeChrome = File('${scratch.path}/fake-chrome.sh') + ..writeAsStringSync('#!/bin/sh\n' + 'echo \$\$ > "${fakeChromePidFile.path}"\n' + 'exec sleep 300\n'); + await Process.run('chmod', ['+x', fakeChrome.path]); + + port = await _freePort(); + adapter = await Process.start('dart', [ + 'run', + 'bin/adapter.dart', + '--port', + '$port', + '--web-dir', + webDir.path, + '--chrome', + fakeChrome.path, + ]); + adapter.stderr + .transform(const SystemEncoding().decoder) + .listen(stderrBuffer.write); + adapter.stdout.drain(); + + await _waitForPort(port); + }); + + tearDown(() async { + // A termination signal lets the adapter delete its browser profile. + adapter.kill(ProcessSignal.sigterm); + await adapter.exitCode.timeout(const Duration(seconds: 5), onTimeout: () { + adapter.kill(ProcessSignal.sigkill); + return -1; + }); + if (fakeChromePid() case final pid?) { + Process.killPid(pid, ProcessSignal.sigkill); + } + await scratch.delete(recursive: true); + }); + + test('the adapter survives one POST with a non-JSON body', () async { + final client = HttpClient(); + try { + final request = await client.post('127.0.0.1', port, '/'); + request.headers.contentType = ContentType.json; + request.write('this is not json'); + final response = await request.close(); + await response.drain(); + expect(response.statusCode, 500); + } finally { + client.close(force: true); + } + + final exitCode = await adapter.exitCode + .timeout(const Duration(seconds: 3), onTimeout: () => -1); + + expect(exitCode, -1, + reason: 'the adapter exited with code $exitCode after one malformed ' + 'POST; stderr was: $stderrBuffer'); + expect(stderrBuffer.toString(), + isNot(contains('StreamSink is bound to a stream'))); + }); + + test('a termination signal stops the adapter and the browser', () async { + // The adapter starts the browser after it opens its port. + final pid = await _waitFor(fakeChromePid, 'the browser PID file'); + expect(processExists(pid), isTrue); + + adapter.kill(ProcessSignal.sigterm); + + final exitCode = + await adapter.exitCode.timeout(const Duration(seconds: 10)); + expect(exitCode, 1); + // The kill is asynchronous on the OS side; allow it a moment to land. + await Future.delayed(const Duration(milliseconds: 200)); + expect(processExists(pid), isFalse, + reason: 'the browser process is still running after the adapter ' + 'stopped'); + }); +} + +/// Polls [read] until it returns a value. +Future _waitFor(T? Function() read, String what) async { + final deadline = DateTime.now().add(const Duration(seconds: 10)); + while (DateTime.now().isBefore(deadline)) { + if (read() case final value?) { + return value; + } + await Future.delayed(const Duration(milliseconds: 100)); + } + fail('$what did not appear within 10 seconds'); +} + +Future _freePort() async { + final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = socket.port; + await socket.close(); + return port; +} + +/// Polls the adapter until it accepts a connection. The status GET answers +/// 503 until the page connects, which is enough to show the server is up. +Future _waitForPort(int port) async { + final deadline = DateTime.now().add(const Duration(seconds: 60)); + while (DateTime.now().isBefore(deadline)) { + try { + final socket = await Socket.connect(InternetAddress.loopbackIPv4, port); + await socket.close(); + return; + } on SocketException { + await Future.delayed(const Duration(milliseconds: 200)); + } + } + fail('the adapter did not open port $port within 60 seconds'); +} diff --git a/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt b/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt index 573c6c71..17053bbc 100644 --- a/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt +++ b/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt @@ -1,16 +1,23 @@ -# FDv2 run (harness v3). Same list as the JS browser SDK data system runs +# FDv2 run (harness v3). Based on the JS browser SDK data system list # (js-core, packages/sdk/browser/contract-tests/suppressions_datamode_changes.txt). +# Each difference from that list is stated below. # -# On web, the SDK drops the x-launchdarkly-tags header from streaming -# requests, to avoid CORS preflight failures, so the stream tags assertions -# cannot pass. The poll tags -# assertions are skipped for the same reason as in the JS browser SDK. +# On web, the SDK removes the x-launchdarkly-tags header from streaming +# requests. The CORS allow-list of the LaunchDarkly streaming service does not +# include it, so a browser preflight with it fails. The stream tags tests +# expect the header, so they cannot pass. The default FDv2 data system +# streams, so the fallback directive test and the disallowed characters test +# fail the same way. The poll tags tests also fail this way, because the +# harness pairs the polling initializer with a streaming synchronizer for a +# JavaScript-kind SDK and checks the synchronizer request. +# +# The JS list also skips "streaming/fdv2/FDv1 fallback directive/directive +# without FDv1 fallback configured halts the data system". The Flutter SDK +# passes that test, so it is not listed here. tags/FDv1 fallback directive requests tags/disallowed characters tags/stream requests/{"applicationId":null,"applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} tags/stream requests/{"applicationId":null,"applicationVersion":"________________________________________________________________"} -tags/stream requests/{"applicationId":"","applicationVersion":null} -tags/stream requests/{"applicationId":"","applicationVersion":""} tags/stream requests/{"applicationId":"","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} tags/stream requests/{"applicationId":"","applicationVersion":"________________________________________________________________"} tags/stream requests/{"applicationId":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678","applicationVersion":null} @@ -33,3 +40,8 @@ tags/poll requests/{"applicationId":"___________________________________________ tags/poll requests/{"applicationId":"________________________________________________________________","applicationVersion":""} tags/poll requests/{"applicationId":"________________________________________________________________","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} tags/poll requests/{"applicationId":"________________________________________________________________","applicationVersion":"________________________________________________________________"} + +# Not in the JS list. The Flutter SDK treats a null context kind as the +# default kind "user". The existing Flutter contract test service skips this +# test for the same reason. +context type/convert/invalid context/{"kind": null, "key": "x"} diff --git a/apps/flutter_web_contract_test_service/testharness-suppressions.txt b/apps/flutter_web_contract_test_service/testharness-suppressions.txt index 79162528..46744fa9 100644 --- a/apps/flutter_web_contract_test_service/testharness-suppressions.txt +++ b/apps/flutter_web_contract_test_service/testharness-suppressions.txt @@ -1,11 +1,11 @@ -# FDv1 run (harness v2). Same list as the JS browser SDK fetch EventSource run +# FDv1 run (harness v2). Based on the JS browser SDK fetch EventSource list # (js-core, packages/sdk/browser/contract-tests/suppressions_fetch_eventsource.txt). +# Each difference from that list is stated below. # -# On web, the SDK drops the x-launchdarkly-tags header from streaming -# requests, because the LaunchDarkly streaming service CORS allow-list rejects -# it and a browser preflight with it fails. These stream assertions expect that header, so they -# cannot pass with this transport. The combinations that expect no header -# still run. +# On web, the SDK removes the x-launchdarkly-tags header from streaming +# requests. The CORS allow-list of the LaunchDarkly streaming service does not +# include it, so a browser preflight with it fails. These stream tests expect +# the header. The tests that expect no header still run. tags/stream requests/{"applicationId":null,"applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} tags/stream requests/{"applicationId":null,"applicationVersion":"________________________________________________________________"} tags/stream requests/{"applicationId":"","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} @@ -19,6 +19,7 @@ tags/stream requests/{"applicationId":"_________________________________________ tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":"._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"} tags/stream requests/{"applicationId":"________________________________________________________________","applicationVersion":"________________________________________________________________"} -# The Flutter SDK does not reject tag values with disallowed characters. The -# existing Flutter contract test service skips this test for the same reason. -tags/disallowed characters +# Not in the JS list. The Flutter SDK treats a null context kind as the +# default kind "user". The existing Flutter contract test service skips this +# test for the same reason. +context type/convert/invalid context/{"kind": null, "key": "x"} From 106ee527f14d5d159b03e9f95548f12b729aa0e1 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Fri, 6 Nov 2026 10:55:15 -0500 Subject: [PATCH 5/7] chore: Remove the adapter unit test from the browser contract test service --- .../pubspec.lock | 214 +----------------- .../pubspec.yaml | 5 +- .../test/adapter_test.dart | 153 ------------- 3 files changed, 5 insertions(+), 367 deletions(-) delete mode 100644 apps/flutter_web_contract_test_service/test/adapter_test.dart diff --git a/apps/flutter_web_contract_test_service/pubspec.lock b/apps/flutter_web_contract_test_service/pubspec.lock index 863d483a..ff1a58fd 100644 --- a/apps/flutter_web_contract_test_service/pubspec.lock +++ b/apps/flutter_web_contract_test_service/pubspec.lock @@ -1,22 +1,6 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: - _fe_analyzer_shared: - dependency: transitive - description: - name: _fe_analyzer_shared - sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d" - url: "https://pub.dev" - source: hosted - version: "93.0.0" - analyzer: - dependency: transitive - description: - name: analyzer - sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b - url: "https://pub.dev" - source: hosted - version: "10.0.1" args: dependency: "direct main" description: @@ -33,14 +17,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" - boolean_selector: - dependency: transitive - description: - name: boolean_selector - sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" - url: "https://pub.dev" - source: hosted - version: "2.1.2" characters: dependency: transitive description: @@ -49,22 +25,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" - cli_config: - dependency: transitive - description: - name: cli_config - sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec - url: "https://pub.dev" - source: hosted - version: "0.2.0" - cli_util: - dependency: transitive - description: - name: cli_util - sha256: "89b8801ba49f8b593fbf2d3e59efd0f566c46cd4ba6837ae2610c72b52a0f899" - url: "https://pub.dev" - source: hosted - version: "0.6.0" clock: dependency: transitive description: @@ -105,14 +65,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.2" - coverage: - dependency: transitive - description: - name: coverage - sha256: ff89e37c19355194e279d26dafe8e4bece46c9ea63a30be4dc68214f5bc290d3 - url: "https://pub.dev" - source: hosted - version: "1.16.0" crypto: dependency: transitive description: @@ -187,22 +139,6 @@ packages: description: flutter source: sdk version: "0.0.0" - frontend_server_client: - dependency: transitive - description: - name: frontend_server_client - sha256: "404dbf9bce29beafbe9dcb19219447b6f7d49900cd42b8d3b7af102b24508e25" - url: "https://pub.dev" - source: hosted - version: "4.1.0" - glob: - dependency: transitive - description: - name: glob - sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" - url: "https://pub.dev" - source: hosted - version: "2.2.0" http: dependency: transitive description: @@ -211,14 +147,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.6.0" - http_multi_server: - dependency: transitive - description: - name: http_multi_server - sha256: "361668bdd71f0ae2dc6d17b75a593520f3c414af6534f9eed1aa72049dd71d18" - url: "https://pub.dev" - source: hosted - version: "3.2.3" http_parser: dependency: transitive description: @@ -227,21 +155,13 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.2" - io: - dependency: transitive - description: - name: io - sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" - url: "https://pub.dev" - source: hosted - version: "1.1.0" launchdarkly_common_client: dependency: "direct overridden" description: path: "../../packages/common_client" relative: true source: path - version: "1.15.0" + version: "1.15.1" launchdarkly_dart_common: dependency: "direct main" description: @@ -255,14 +175,14 @@ packages: path: "../../packages/event_source_client" relative: true source: path - version: "3.0.0" + version: "3.0.1" launchdarkly_flutter_client_sdk: dependency: "direct main" description: path: "../../packages/flutter_client_sdk" relative: true source: path - version: "4.21.0" + version: "4.21.1" lints: dependency: "direct dev" description: @@ -271,22 +191,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0" - logging: - dependency: transitive - description: - name: logging - sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 - url: "https://pub.dev" - source: hosted - version: "1.3.0" - matcher: - dependency: transitive - description: - name: matcher - sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" - url: "https://pub.dev" - source: hosted - version: "0.12.20" material_color_utilities: dependency: transitive description: @@ -319,22 +223,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.6.0" - node_preamble: - dependency: transitive - description: - name: node_preamble - sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" - url: "https://pub.dev" - source: hosted - version: "2.0.2" - package_config: - dependency: transitive - description: - name: package_config - sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc - url: "https://pub.dev" - source: hosted - version: "2.2.0" package_info_plus: dependency: transitive description: @@ -407,22 +295,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.8" - pool: - dependency: transitive - description: - name: pool - sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" - url: "https://pub.dev" - source: hosted - version: "1.5.3" - pub_semver: - dependency: transitive - description: - name: pub_semver - sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" - url: "https://pub.dev" - source: hosted - version: "2.2.1" shared_preferences: dependency: transitive description: @@ -487,14 +359,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.3" - shelf_packages_handler: - dependency: transitive - description: - name: shelf_packages_handler - sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" - url: "https://pub.dev" - source: hosted - version: "3.0.2" shelf_static: dependency: "direct main" description: @@ -516,22 +380,6 @@ packages: description: flutter source: sdk version: "0.0.0" - source_map_stack_trace: - dependency: transitive - description: - name: source_map_stack_trace - sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b - url: "https://pub.dev" - source: hosted - version: "2.1.2" - source_maps: - dependency: transitive - description: - name: source_maps - sha256: "14c2945847669b44089bb1222f66873d7ff7103c58911917f2a63c5a62327898" - url: "https://pub.dev" - source: hosted - version: "0.10.14" source_span: dependency: transitive description: @@ -572,30 +420,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.2.2" - test: - dependency: "direct dev" - description: - name: test - sha256: ca578dc12bb8b2f40b67b7d3bd2fac4f31c01a6ff7130a14e2597b919934507f - url: "https://pub.dev" - source: hosted - version: "1.31.1" - test_api: - dependency: transitive - description: - name: test_api - sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" - url: "https://pub.dev" - source: hosted - version: "0.7.12" - test_core: - dependency: transitive - description: - name: test_core - sha256: d2e98ec12998368dc59ddd47ab709f2cd55acd6b66dc7db764455a44082f4bc5 - url: "https://pub.dev" - source: hosted - version: "0.6.18" typed_data: dependency: transitive description: @@ -620,22 +444,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" - vm_service: - dependency: transitive - description: - name: vm_service - sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" - url: "https://pub.dev" - source: hosted - version: "15.4.0" - watcher: - dependency: transitive - description: - name: watcher - sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" - url: "https://pub.dev" - source: hosted - version: "1.2.1" web: dependency: transitive description: @@ -660,14 +468,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.3" - webkit_inspection_protocol: - dependency: transitive - description: - name: webkit_inspection_protocol - sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" - url: "https://pub.dev" - source: hosted - version: "1.2.1" win32: dependency: transitive description: @@ -700,14 +500,6 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" - yaml: - dependency: transitive - description: - name: yaml - sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea - url: "https://pub.dev" - source: hosted - version: "3.1.4" sdks: dart: ">=3.11.0 <4.0.0" flutter: ">=3.41.0" diff --git a/apps/flutter_web_contract_test_service/pubspec.yaml b/apps/flutter_web_contract_test_service/pubspec.yaml index e06b4994..0b019d51 100644 --- a/apps/flutter_web_contract_test_service/pubspec.yaml +++ b/apps/flutter_web_contract_test_service/pubspec.yaml @@ -20,11 +20,10 @@ dependencies: path: ../../packages/flutter_client_sdk shelf: ^1.4.0 shelf_static: ^1.1.0 - # Version 1 is needed so the oldest tested Dart SDK can resolve `test`. + # The range starts low so the oldest tested Dart SDK can resolve it. shelf_web_socket: '>=1.0.0 <4.0.0' - # Version 2 is needed so the oldest tested Dart SDK can resolve `test`. + # The range starts low so the oldest tested Dart SDK can resolve it. web_socket_channel: '>=2.0.0 <4.0.0' dev_dependencies: lints: ^3.0.0 - test: ^1.24.3 diff --git a/apps/flutter_web_contract_test_service/test/adapter_test.dart b/apps/flutter_web_contract_test_service/test/adapter_test.dart deleted file mode 100644 index 594186d4..00000000 --- a/apps/flutter_web_contract_test_service/test/adapter_test.dart +++ /dev/null @@ -1,153 +0,0 @@ -// Tests for the adapter process. They do not need Chrome. The adapter starts -// with `--chrome` pointing at a shell script that only sleeps, so the child -// holds the stdio pipes the same way a real browser does. -// -// Run from this directory with `flutter test test/adapter_test.dart`. - -@TestOn('vm') -library; - -import 'dart:async'; -import 'dart:io'; - -import 'package:test/test.dart'; - -void main() { - late Directory scratch; - late Process adapter; - late int port; - late File fakeChromePidFile; - late StringBuffer stderrBuffer; - - int? fakeChromePid() { - if (!fakeChromePidFile.existsSync()) { - return null; - } - return int.tryParse(fakeChromePidFile.readAsStringSync().trim()); - } - - bool processExists(int pid) => Process.killPid(pid, ProcessSignal.sigcont); - - setUp(() async { - stderrBuffer = StringBuffer(); - scratch = await Directory.systemTemp.createTemp('adapter-test-'); - // The static handler needs an existing directory with an index file. - final webDir = Directory('${scratch.path}/web')..createSync(); - File('${webDir.path}/index.html').writeAsStringSync(''); - - // A stand-in for Chrome. It records its PID so the test can check for - // it and kill it, then holds stdout and stderr open. - fakeChromePidFile = File('${scratch.path}/chrome.pid'); - final fakeChrome = File('${scratch.path}/fake-chrome.sh') - ..writeAsStringSync('#!/bin/sh\n' - 'echo \$\$ > "${fakeChromePidFile.path}"\n' - 'exec sleep 300\n'); - await Process.run('chmod', ['+x', fakeChrome.path]); - - port = await _freePort(); - adapter = await Process.start('dart', [ - 'run', - 'bin/adapter.dart', - '--port', - '$port', - '--web-dir', - webDir.path, - '--chrome', - fakeChrome.path, - ]); - adapter.stderr - .transform(const SystemEncoding().decoder) - .listen(stderrBuffer.write); - adapter.stdout.drain(); - - await _waitForPort(port); - }); - - tearDown(() async { - // A termination signal lets the adapter delete its browser profile. - adapter.kill(ProcessSignal.sigterm); - await adapter.exitCode.timeout(const Duration(seconds: 5), onTimeout: () { - adapter.kill(ProcessSignal.sigkill); - return -1; - }); - if (fakeChromePid() case final pid?) { - Process.killPid(pid, ProcessSignal.sigkill); - } - await scratch.delete(recursive: true); - }); - - test('the adapter survives one POST with a non-JSON body', () async { - final client = HttpClient(); - try { - final request = await client.post('127.0.0.1', port, '/'); - request.headers.contentType = ContentType.json; - request.write('this is not json'); - final response = await request.close(); - await response.drain(); - expect(response.statusCode, 500); - } finally { - client.close(force: true); - } - - final exitCode = await adapter.exitCode - .timeout(const Duration(seconds: 3), onTimeout: () => -1); - - expect(exitCode, -1, - reason: 'the adapter exited with code $exitCode after one malformed ' - 'POST; stderr was: $stderrBuffer'); - expect(stderrBuffer.toString(), - isNot(contains('StreamSink is bound to a stream'))); - }); - - test('a termination signal stops the adapter and the browser', () async { - // The adapter starts the browser after it opens its port. - final pid = await _waitFor(fakeChromePid, 'the browser PID file'); - expect(processExists(pid), isTrue); - - adapter.kill(ProcessSignal.sigterm); - - final exitCode = - await adapter.exitCode.timeout(const Duration(seconds: 10)); - expect(exitCode, 1); - // The kill is asynchronous on the OS side; allow it a moment to land. - await Future.delayed(const Duration(milliseconds: 200)); - expect(processExists(pid), isFalse, - reason: 'the browser process is still running after the adapter ' - 'stopped'); - }); -} - -/// Polls [read] until it returns a value. -Future _waitFor(T? Function() read, String what) async { - final deadline = DateTime.now().add(const Duration(seconds: 10)); - while (DateTime.now().isBefore(deadline)) { - if (read() case final value?) { - return value; - } - await Future.delayed(const Duration(milliseconds: 100)); - } - fail('$what did not appear within 10 seconds'); -} - -Future _freePort() async { - final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); - final port = socket.port; - await socket.close(); - return port; -} - -/// Polls the adapter until it accepts a connection. The status GET answers -/// 503 until the page connects, which is enough to show the server is up. -Future _waitForPort(int port) async { - final deadline = DateTime.now().add(const Duration(seconds: 60)); - while (DateTime.now().isBefore(deadline)) { - try { - final socket = await Socket.connect(InternetAddress.loopbackIPv4, port); - await socket.close(); - return; - } on SocketException { - await Future.delayed(const Duration(milliseconds: 200)); - } - } - fail('the adapter did not open port $port within 60 seconds'); -} From 7ed53f113f0163e9789733e0ec2210b6af09ea93 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Fri, 6 Nov 2026 14:57:34 -0500 Subject: [PATCH 6/7] fix: Report the browser contract test adapter as not ready after Chrome exits and free the port on shutdown --- apps/flutter_web_contract_test_service/bin/adapter.dart | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/flutter_web_contract_test_service/bin/adapter.dart b/apps/flutter_web_contract_test_service/bin/adapter.dart index e9e21416..b5efdf05 100644 --- a/apps/flutter_web_contract_test_service/bin/adapter.dart +++ b/apps/flutter_web_contract_test_service/bin/adapter.dart @@ -83,6 +83,7 @@ final class Adapter { return; } stderr.writeln('The browser exited with code $code.'); + _capabilities = null; if (!_ready.isCompleted) { _ready.completeError(StateError('The browser exited with code $code.')); } @@ -120,6 +121,7 @@ final class Adapter { // A newer connection may already own the relay. if (identical(_channel, channel)) { _channel = null; + _capabilities = null; _failPending('The browser disconnected.'); } }); @@ -204,13 +206,16 @@ final class Adapter { body: jsonEncode(body), headers: {HttpHeaders.contentTypeHeader: 'application/json'}); - /// Stops the browser, deletes its profile, and closes the server. Safe to + /// Closes the server, stops the browser, and deletes its profile. Safe to /// call more than once. Future shutdown() async { if (_stopping) { return _stopped.future; } _stopping = true; + // Release the port first. The next harness run binds it while the + // browser is still on its way out. + await _server.close(); final browser = _browser; if (browser != null) { browser.kill(); @@ -221,7 +226,6 @@ final class Adapter { await profile.delete(recursive: true).catchError((_) => profile); } await _channel?.sink.close(); - await _server.close(); _stopped.complete(); } } From 91dc80882b56a450ca78f15f8144a9865dc4dc7c Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Mon, 9 Nov 2026 09:53:58 -0500 Subject: [PATCH 7/7] refactor: Select the HTTP SSE client in the browser contract service with eventSource --- apps/flutter_web_contract_test_service/README.md | 4 ++-- apps/flutter_web_contract_test_service/lib/src/entity.dart | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/flutter_web_contract_test_service/README.md b/apps/flutter_web_contract_test_service/README.md index 6307cdb1..ca0e2b33 100644 --- a/apps/flutter_web_contract_test_service/README.md +++ b/apps/flutter_web_contract_test_service/README.md @@ -1,7 +1,7 @@ Contract test service that runs the Flutter SDK in a browser. -The SDK streams with the HTTP-based SSE client (`useHttpStreamingOnWeb`), not -with the browser native `EventSource`. The native client cannot send a request +The SDK streams with the HTTP-based SSE client (`eventSource: SSEClient.http`), +not with the browser native `EventSource`. The native client cannot send a request body or report an HTTP error. So this service is the only contract test run that covers `usePost` and HTTP error handling for streaming on web. diff --git a/apps/flutter_web_contract_test_service/lib/src/entity.dart b/apps/flutter_web_contract_test_service/lib/src/entity.dart index d0199e32..5e143862 100644 --- a/apps/flutter_web_contract_test_service/lib/src/entity.dart +++ b/apps/flutter_web_contract_test_service/lib/src/entity.dart @@ -16,7 +16,7 @@ const int _defaultWaitTimeMillis = 5000; /// report an HTTP error. final class Entity { /// `client-event-source-http-errors` and `client-use-post` need the - /// HTTP-based SSE client. Keep `useHttpStreamingOnWeb: true` in [_create] + /// HTTP-based SSE client. Keep `eventSource: SSEClient.http` in [_create] /// while the list declares them. static const List capabilities = [ 'client-side', @@ -125,7 +125,7 @@ final class Entity { ?.map((attribute) => attribute as String) .toList(), dataSystem: mappedDataSystem?.config, - useHttpStreamingOnWeb: true, + eventSource: SSEClient.http, ); final context = _flattenedListToContext(_serializedContextToFlattenedList(