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..ca0e2b33 --- /dev/null +++ b/apps/flutter_web_contract_test_service/README.md @@ -0,0 +1,60 @@ +Contract test service that runs the Flutter SDK in a browser. + +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. + +# 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. +`client-use-post` and `client-event-source-http-errors` need the HTTP-based +SSE client. + +# Running it + +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/ +$ 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 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/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..b5efdf05 --- /dev/null +++ b/apps/flutter_web_contract_test_service/bin/adapter.dart @@ -0,0 +1,295 @@ +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; + Directory? _profile; + WebSocketChannel? _channel; + List? _capabilities; + final Completer _ready = Completer(); + final Completer _stopped = Completer(); + bool _stopping = false; + 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'); + // 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)) { + 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 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 = + _profile = await Directory.systemTemp.createTemp('flutter-web-entity'); + final browser = _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 (_stopping) { + return; + } + stderr.writeln('The browser exited with code $code.'); + _capabilities = null; + if (!_ready.isCompleted) { + _ready.completeError(StateError('The browser exited with code $code.')); + } + _failPending('The browser exited.'); + })); + // 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 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) + .toList(); + if (!_ready.isCompleted) { + _ready.complete(); + } + return; + } + _pending.remove(message['id'])?.complete(message); + }, onDone: () { + // A newer connection may already own the relay. + if (identical(_channel, channel)) { + _channel = null; + _capabilities = 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'}); + + /// 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(); + await browser.exitCode + .timeout(const Duration(seconds: 5), onTimeout: () => -1); + } + if (_profile case final profile?) { + await profile.delete(recursive: true).catchError((_) => profile); + } + await _channel?.sink.close(); + _stopped.complete(); + } +} + +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}'); + // 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); + } 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); + } 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; + 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..0b17c01f --- /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..5e143862 --- /dev/null +++ b/apps/flutter_web_contract_test_service/lib/src/entity.dart @@ -0,0 +1,524 @@ +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 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 { + /// `client-event-source-http-errors` and `client-use-post` need the + /// HTTP-based SSE client. Keep `eventSource: SSEClient.http` in [_create] + /// while the list declares them. + static const List capabilities = [ + 'client-side', + 'strongly-typed', + 'context-type', + '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', + 'polling-gzip', + 'client-event-source-http-errors', + 'client-use-post', + ]; + + final Map _clients = {}; + int _nextClientId = 0; + + /// 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: 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?, + 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, + eventSource: SSEClient.http, + ); + + 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) { + // 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; + } + 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..ff1a58fd --- /dev/null +++ b/apps/flutter_web_contract_test_service/pubspec.lock @@ -0,0 +1,505 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + 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" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + 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" + 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" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + launchdarkly_common_client: + dependency: "direct overridden" + description: + path: "../../packages/common_client" + relative: true + source: path + version: "1.15.1" + 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.1" + launchdarkly_flutter_client_sdk: + dependency: "direct main" + description: + path: "../../packages/flutter_client_sdk" + relative: true + source: path + version: "4.21.1" + lints: + dependency: "direct dev" + description: + name: lints + sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 + url: "https://pub.dev" + source: hosted + version: "3.0.0" + 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" + 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" + 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_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_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" + 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" + 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" + 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" +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..0b019d51 --- /dev/null +++ b/apps/flutter_web_contract_test_service/pubspec.yaml @@ -0,0 +1,29 @@ +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 + # The range starts low so the oldest tested Dart SDK can resolve it. + shelf_web_socket: '>=1.0.0 <4.0.0' + # 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 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..17053bbc --- /dev/null +++ b/apps/flutter_web_contract_test_service/testharness-suppressions-fdv2.txt @@ -0,0 +1,47 @@ +# 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 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":"._-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":"________________________________________________________________"} + +# 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 new file mode 100644 index 00000000..46744fa9 --- /dev/null +++ b/apps/flutter_web_contract_test_service/testharness-suppressions.txt @@ -0,0 +1,25 @@ +# 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 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"} +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":"________________________________________________________________"} + +# 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/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