Unverified Commit 1dbafdb5 authored by Jenn Magder's avatar Jenn Magder Committed by GitHub

Migrate protocol_discovery to null safety (#91267)

parent bdeefecc
...@@ -385,7 +385,6 @@ class CustomDeviceAppSession { ...@@ -385,7 +385,6 @@ class CustomDeviceAppSession {
final ProtocolDiscovery discovery = ProtocolDiscovery.observatory( final ProtocolDiscovery discovery = ProtocolDiscovery.observatory(
logReader, logReader,
portForwarder: _device._config.usesPortForwarding ? _device.portForwarder : null, portForwarder: _device._config.usesPortForwarding ? _device.portForwarder : null,
hostPort: null, devicePort: null,
logger: _logger, logger: _logger,
ipv6: ipv6, ipv6: ipv6,
); );
......
...@@ -214,7 +214,7 @@ abstract class DeviceManager { ...@@ -214,7 +214,7 @@ abstract class DeviceManager {
/// ///
/// * If [flutterProject] is null, then assume the project supports all /// * If [flutterProject] is null, then assume the project supports all
/// device types. /// device types.
Future<List<Device>> findTargetDevices(FlutterProject flutterProject, { Duration? timeout }) async { Future<List<Device>> findTargetDevices(FlutterProject? flutterProject, { Duration? timeout }) async {
if (timeout != null) { if (timeout != null) {
// Reset the cache with the specified timeout. // Reset the cache with the specified timeout.
await refreshAllConnectedDevices(timeout: timeout); await refreshAllConnectedDevices(timeout: timeout);
...@@ -317,7 +317,7 @@ abstract class DeviceManager { ...@@ -317,7 +317,7 @@ abstract class DeviceManager {
/// ///
/// This exists to allow the check to be overridden for google3 clients. If /// This exists to allow the check to be overridden for google3 clients. If
/// [flutterProject] is null then return true. /// [flutterProject] is null then return true.
bool isDeviceSupportedForProject(Device device, FlutterProject flutterProject) { bool isDeviceSupportedForProject(Device device, FlutterProject? flutterProject) {
if (flutterProject == null) { if (flutterProject == null) {
return true; return true;
} }
......
...@@ -2,12 +2,8 @@ ...@@ -2,12 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
// @dart = 2.8
import 'dart:async'; import 'dart:async';
import 'package:meta/meta.dart';
import 'base/io.dart'; import 'base/io.dart';
import 'base/logger.dart'; import 'base/logger.dart';
import 'device.dart'; import 'device.dart';
...@@ -20,28 +16,27 @@ class ProtocolDiscovery { ...@@ -20,28 +16,27 @@ class ProtocolDiscovery {
this.logReader, this.logReader,
this.serviceName, { this.serviceName, {
this.portForwarder, this.portForwarder,
this.throttleDuration, required this.throttleDuration,
this.hostPort, this.hostPort,
this.devicePort, this.devicePort,
this.ipv6, required this.ipv6,
Logger logger, required Logger logger,
}) : _logger = logger, }) : _logger = logger,
assert(logReader != null) { assert(logReader != null) {
_deviceLogSubscription = logReader.logLines.listen( _deviceLogSubscription = logReader.logLines.listen(
_handleLine, _handleLine,
onDone: _stopScrapingLogs, onDone: _stopScrapingLogs,
); );
_uriStreamController = _BufferedStreamController<Uri>();
} }
factory ProtocolDiscovery.observatory( factory ProtocolDiscovery.observatory(
DeviceLogReader logReader, { DeviceLogReader logReader, {
DevicePortForwarder portForwarder, DevicePortForwarder? portForwarder,
Duration throttleDuration, Duration? throttleDuration,
@required int hostPort, int? hostPort,
@required int devicePort, int? devicePort,
@required bool ipv6, required bool ipv6,
@required Logger logger, required Logger logger,
}) { }) {
const String kObservatoryService = 'Observatory'; const String kObservatoryService = 'Observatory';
return ProtocolDiscovery._( return ProtocolDiscovery._(
...@@ -58,17 +53,17 @@ class ProtocolDiscovery { ...@@ -58,17 +53,17 @@ class ProtocolDiscovery {
final DeviceLogReader logReader; final DeviceLogReader logReader;
final String serviceName; final String serviceName;
final DevicePortForwarder portForwarder; final DevicePortForwarder? portForwarder;
final int hostPort; final int? hostPort;
final int devicePort; final int? devicePort;
final bool ipv6; final bool ipv6;
final Logger _logger; final Logger _logger;
/// The time to wait before forwarding a new observatory URIs from [logReader]. /// The time to wait before forwarding a new observatory URIs from [logReader].
final Duration throttleDuration; final Duration throttleDuration;
StreamSubscription<String> _deviceLogSubscription; StreamSubscription<String>? _deviceLogSubscription;
_BufferedStreamController<Uri> _uriStreamController; final _BufferedStreamController<Uri> _uriStreamController = _BufferedStreamController<Uri>();
/// The discovered service URL. /// The discovered service URL.
/// ///
...@@ -76,7 +71,7 @@ class ProtocolDiscovery { ...@@ -76,7 +71,7 @@ class ProtocolDiscovery {
/// ///
/// Use [uris] instead. /// Use [uris] instead.
// TODO(egarciad): replace `uri` for `uris`. // TODO(egarciad): replace `uri` for `uris`.
Future<Uri> get uri async { Future<Uri?> get uri async {
try { try {
return await uris.first; return await uris.first;
} on StateError { } on StateError {
...@@ -103,26 +98,26 @@ class ProtocolDiscovery { ...@@ -103,26 +98,26 @@ class ProtocolDiscovery {
Future<void> cancel() => _stopScrapingLogs(); Future<void> cancel() => _stopScrapingLogs();
Future<void> _stopScrapingLogs() async { Future<void> _stopScrapingLogs() async {
await _uriStreamController?.close(); await _uriStreamController.close();
await _deviceLogSubscription?.cancel(); await _deviceLogSubscription?.cancel();
_deviceLogSubscription = null; _deviceLogSubscription = null;
} }
Match _getPatternMatch(String line) { Match? _getPatternMatch(String line) {
final RegExp r = RegExp(RegExp.escape(serviceName) + r' listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)'); final RegExp r = RegExp(RegExp.escape(serviceName) + r' listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)');
return r.firstMatch(line); return r.firstMatch(line);
} }
Uri _getObservatoryUri(String line) { Uri? _getObservatoryUri(String line) {
final Match match = _getPatternMatch(line); final Match? match = _getPatternMatch(line);
if (match != null) { if (match != null) {
return Uri.parse(match[1]); return Uri.parse(match[1]!);
} }
return null; return null;
} }
void _handleLine(String line) { void _handleLine(String line) {
Uri uri; Uri? uri;
try { try {
uri = _getObservatoryUri(line); uri = _getObservatoryUri(line);
} on FormatException catch (error, stackTrace) { } on FormatException catch (error, stackTrace) {
...@@ -142,9 +137,10 @@ class ProtocolDiscovery { ...@@ -142,9 +137,10 @@ class ProtocolDiscovery {
_logger.printTrace('$serviceName URL on device: $deviceUri'); _logger.printTrace('$serviceName URL on device: $deviceUri');
Uri hostUri = deviceUri; Uri hostUri = deviceUri;
if (portForwarder != null) { final DevicePortForwarder? forwarder = portForwarder;
if (forwarder != null) {
final int actualDevicePort = deviceUri.port; final int actualDevicePort = deviceUri.port;
final int actualHostPort = await portForwarder.forward(actualDevicePort, hostPort: hostPort); final int actualHostPort = await forwarder.forward(actualDevicePort, hostPort: hostPort);
_logger.printTrace('Forwarded host port $actualHostPort to device port $actualDevicePort for $serviceName'); _logger.printTrace('Forwarded host port $actualHostPort to device port $actualDevicePort for $serviceName');
hostUri = deviceUri.replace(port: actualHostPort); hostUri = deviceUri.replace(port: actualHostPort);
} }
...@@ -167,25 +163,24 @@ class _BufferedStreamController<T> { ...@@ -167,25 +163,24 @@ class _BufferedStreamController<T> {
return _streamController.stream; return _streamController.stream;
} }
StreamController<T> _streamControllerInstance; late final StreamController<T> _streamController = () {
final StreamController<T> streamControllerInstance = StreamController<T>.broadcast();
StreamController<T> get _streamController { streamControllerInstance.onListen = () {
_streamControllerInstance ??= StreamController<T>.broadcast(onListen: () {
for (final dynamic event in _events) { for (final dynamic event in _events) {
assert(T is! List); assert(T is! List);
if (event is T) { if (event is T) {
_streamControllerInstance.add(event); streamControllerInstance.add(event);
} else { } else {
_streamControllerInstance.addError( streamControllerInstance.addError(
(event as Iterable<dynamic>).first as Object, (event as Iterable<dynamic>).first as Object,
(event as Iterable<dynamic>).last as StackTrace, event.last as StackTrace,
); );
} }
} }
_events.clear(); _events.clear();
}); };
return _streamControllerInstance; return streamControllerInstance;
} }();
final List<dynamic> _events; final List<dynamic> _events;
...@@ -200,7 +195,7 @@ class _BufferedStreamController<T> { ...@@ -200,7 +195,7 @@ class _BufferedStreamController<T> {
} }
/// Sends or enqueues an error event. /// Sends or enqueues an error event.
void addError(Object error, [StackTrace stackTrace]) { void addError(Object error, [StackTrace? stackTrace]) {
if (_streamController.hasListener) { if (_streamController.hasListener) {
_streamController.addError(error, stackTrace); _streamController.addError(error, stackTrace);
} else { } else {
...@@ -220,13 +215,13 @@ class _BufferedStreamController<T> { ...@@ -220,13 +215,13 @@ class _BufferedStreamController<T> {
/// and arrival times: `a (0ms), b (5ms), c (11ms), d (21ms)`. /// and arrival times: `a (0ms), b (5ms), c (11ms), d (21ms)`.
/// The events `a`, `c`, and `d` will be produced as a result. /// The events `a`, `c`, and `d` will be produced as a result.
StreamTransformer<S, S> _throttle<S>({ StreamTransformer<S, S> _throttle<S>({
@required Duration waitDuration, required Duration waitDuration,
}) { }) {
assert(waitDuration != null); assert(waitDuration != null);
S latestLine; S latestLine;
int lastExecution; int? lastExecution;
Future<void> throttleFuture; Future<void>? throttleFuture;
bool done = false; bool done = false;
return StreamTransformer<S, S> return StreamTransformer<S, S>
...@@ -237,7 +232,7 @@ StreamTransformer<S, S> _throttle<S>({ ...@@ -237,7 +232,7 @@ StreamTransformer<S, S> _throttle<S>({
final bool isFirstMessage = lastExecution == null; final bool isFirstMessage = lastExecution == null;
final int currentTime = DateTime.now().millisecondsSinceEpoch; final int currentTime = DateTime.now().millisecondsSinceEpoch;
lastExecution ??= currentTime; lastExecution ??= currentTime;
final int remainingTime = currentTime - lastExecution; final int remainingTime = currentTime - lastExecution!;
// Always send the first event immediately. // Always send the first event immediately.
final int nextExecutionTime = isFirstMessage || remainingTime > waitDuration.inMilliseconds final int nextExecutionTime = isFirstMessage || remainingTime > waitDuration.inMilliseconds
......
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
// @dart = 2.8
import 'dart:async'; import 'dart:async';
import 'package:fake_async/fake_async.dart'; import 'package:fake_async/fake_async.dart';
...@@ -14,7 +12,6 @@ import 'package:flutter_tools/src/base/user_messages.dart'; ...@@ -14,7 +12,6 @@ import 'package:flutter_tools/src/base/user_messages.dart';
import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/project.dart';
import 'package:meta/meta.dart';
import 'package:test/fake.dart'; import 'package:test/fake.dart';
import '../src/common.dart'; import '../src/common.dart';
...@@ -491,37 +488,37 @@ void main() { ...@@ -491,37 +488,37 @@ void main() {
class TestDeviceManager extends DeviceManager { class TestDeviceManager extends DeviceManager {
TestDeviceManager( TestDeviceManager(
List<Device> allDevices, { List<Device> allDevices, {
List<DeviceDiscovery> deviceDiscoveryOverrides, List<DeviceDiscovery>? deviceDiscoveryOverrides,
@required Logger logger, required Logger logger,
@required Terminal terminal, required Terminal terminal,
String wellKnownId, String? wellKnownId,
}) : super(logger: logger, terminal: terminal, userMessages: UserMessages()) { }) : _fakeDeviceDiscoverer = FakePollingDeviceDiscovery(),
_fakeDeviceDiscoverer = FakePollingDeviceDiscovery(); _deviceDiscoverers = <DeviceDiscovery>[],
super(logger: logger, terminal: terminal, userMessages: UserMessages()) {
if (wellKnownId != null) { if (wellKnownId != null) {
_fakeDeviceDiscoverer.wellKnownIds.add(wellKnownId); _fakeDeviceDiscoverer.wellKnownIds.add(wellKnownId);
} }
_deviceDiscoverers = <DeviceDiscovery>[ _deviceDiscoverers.add(_fakeDeviceDiscoverer);
_fakeDeviceDiscoverer, if (deviceDiscoveryOverrides != null) {
if (deviceDiscoveryOverrides != null) _deviceDiscoverers.addAll(deviceDiscoveryOverrides);
...deviceDiscoveryOverrides }
];
resetDevices(allDevices); resetDevices(allDevices);
} }
@override @override
List<DeviceDiscovery> get deviceDiscoverers => _deviceDiscoverers; List<DeviceDiscovery> get deviceDiscoverers => _deviceDiscoverers;
List<DeviceDiscovery> _deviceDiscoverers; final List<DeviceDiscovery> _deviceDiscoverers;
FakePollingDeviceDiscovery _fakeDeviceDiscoverer; final FakePollingDeviceDiscovery _fakeDeviceDiscoverer;
void resetDevices(List<Device> allDevices) { void resetDevices(List<Device> allDevices) {
_fakeDeviceDiscoverer.setDevices(allDevices); _fakeDeviceDiscoverer.setDevices(allDevices);
} }
bool isAlwaysSupportedOverride; bool? isAlwaysSupportedOverride;
@override @override
bool isDeviceSupportedForProject(Device device, FlutterProject flutterProject) { bool isDeviceSupportedForProject(Device device, FlutterProject? flutterProject) {
if (isAlwaysSupportedOverride != null) { if (isAlwaysSupportedOverride != null) {
return isAlwaysSupportedOverride; return isAlwaysSupportedOverride!;
} }
return super.isDeviceSupportedForProject(device, flutterProject); return super.isDeviceSupportedForProject(device, flutterProject);
} }
...@@ -543,7 +540,7 @@ class MockDeviceDiscovery extends Fake implements DeviceDiscovery { ...@@ -543,7 +540,7 @@ class MockDeviceDiscovery extends Fake implements DeviceDiscovery {
} }
@override @override
Future<List<Device>> discoverDevices({Duration timeout}) async { Future<List<Device>> discoverDevices({Duration? timeout}) async {
discoverDevicesCalled += 1; discoverDevicesCalled += 1;
return deviceValues; return deviceValues;
} }
...@@ -560,18 +557,18 @@ class LongPollingDeviceDiscovery extends PollingDeviceDiscovery { ...@@ -560,18 +557,18 @@ class LongPollingDeviceDiscovery extends PollingDeviceDiscovery {
final Completer<List<Device>> _completer = Completer<List<Device>>(); final Completer<List<Device>> _completer = Completer<List<Device>>();
@override @override
Future<List<Device>> pollingGetDevices({ Duration timeout }) async { Future<List<Device>> pollingGetDevices({ Duration? timeout }) async {
return _completer.future; return _completer.future;
} }
@override @override
Future<void> stopPolling() async { Future<void> stopPolling() async {
_completer.complete(); _completer.complete(<Device>[]);
} }
@override @override
Future<void> dispose() async { Future<void> dispose() async {
_completer.complete(); _completer.complete(<Device>[]);
} }
@override @override
...@@ -588,7 +585,7 @@ class ThrowingPollingDeviceDiscovery extends PollingDeviceDiscovery { ...@@ -588,7 +585,7 @@ class ThrowingPollingDeviceDiscovery extends PollingDeviceDiscovery {
ThrowingPollingDeviceDiscovery() : super('throw'); ThrowingPollingDeviceDiscovery() : super('throw');
@override @override
Future<List<Device>> pollingGetDevices({ Duration timeout }) async { Future<List<Device>> pollingGetDevices({ Duration? timeout }) async {
throw const ProcessException('fake-discovery', <String>[]); throw const ProcessException('fake-discovery', <String>[]);
} }
...@@ -614,15 +611,15 @@ class FakeTerminal extends Fake implements Terminal { ...@@ -614,15 +611,15 @@ class FakeTerminal extends Fake implements Terminal {
_nextResult = result; _nextResult = result;
} }
List<String> _nextPrompt; List<String>? _nextPrompt;
String _nextResult; late String _nextResult;
@override @override
Future<String> promptForCharInput( Future<String> promptForCharInput(
List<String> acceptedCharacters, { List<String> acceptedCharacters, {
Logger logger, Logger? logger,
String prompt, String? prompt,
int defaultChoiceIndex, int? defaultChoiceIndex,
bool displayAcceptedCharacters = true, bool displayAcceptedCharacters = true,
}) async { }) async {
expect(acceptedCharacters, _nextPrompt); expect(acceptedCharacters, _nextPrompt);
......
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
// @dart = 2.8
import 'dart:async'; import 'dart:async';
import 'package:flutter_tools/src/application_package.dart'; import 'package:flutter_tools/src/application_package.dart';
...@@ -64,7 +62,7 @@ class FakeDevice extends Device { ...@@ -64,7 +62,7 @@ class FakeDevice extends Device {
bool ephemeral = true, bool ephemeral = true,
bool isSupported = true, bool isSupported = true,
PlatformType type = PlatformType.web, PlatformType type = PlatformType.web,
LaunchResult launchResult, LaunchResult? launchResult,
}) : _isSupported = isSupported, }) : _isSupported = isSupported,
_launchResult = launchResult ?? LaunchResult.succeeded(), _launchResult = launchResult ?? LaunchResult.succeeded(),
super( super(
...@@ -82,24 +80,24 @@ class FakeDevice extends Device { ...@@ -82,24 +80,24 @@ class FakeDevice extends Device {
@override @override
Future<LaunchResult> startApp(covariant ApplicationPackage package, { Future<LaunchResult> startApp(covariant ApplicationPackage package, {
String mainPath, String? mainPath,
String route, String? route,
DebuggingOptions debuggingOptions, DebuggingOptions? debuggingOptions,
Map<String, dynamic> platformArgs, Map<String, dynamic>? platformArgs,
bool prebuiltApplication = false, bool prebuiltApplication = false,
bool ipv6 = false, bool ipv6 = false,
String userIdentifier, String? userIdentifier,
}) async => _launchResult; }) async => _launchResult;
@override @override
Future<bool> stopApp(covariant ApplicationPackage app, { Future<bool> stopApp(covariant ApplicationPackage app, {
String userIdentifier, String? userIdentifier,
}) async => true; }) async => true;
@override @override
Future<bool> uninstallApp( Future<bool> uninstallApp(
covariant ApplicationPackage app, { covariant ApplicationPackage app, {
String userIdentifier, String? userIdentifier,
}) async => true; }) async => true;
@override @override
...@@ -140,12 +138,12 @@ class FakePollingDeviceDiscovery extends PollingDeviceDiscovery { ...@@ -140,12 +138,12 @@ class FakePollingDeviceDiscovery extends PollingDeviceDiscovery {
final StreamController<Device> _onRemovedController = StreamController<Device>.broadcast(); final StreamController<Device> _onRemovedController = StreamController<Device>.broadcast();
@override @override
Future<List<Device>> pollingGetDevices({ Duration timeout }) async { Future<List<Device>> pollingGetDevices({ Duration? timeout }) async {
lastPollingTimeout = timeout; lastPollingTimeout = timeout;
return _devices; return _devices;
} }
Duration lastPollingTimeout; Duration? lastPollingTimeout;
@override @override
bool get supportsPlatform => true; bool get supportsPlatform => true;
...@@ -185,19 +183,15 @@ class FakeDeviceLogReader extends DeviceLogReader { ...@@ -185,19 +183,15 @@ class FakeDeviceLogReader extends DeviceLogReader {
@override @override
String get name => 'FakeLogReader'; String get name => 'FakeLogReader';
StreamController<String> _cachedLinesController;
bool disposed = false; bool disposed = false;
final List<String> _lineQueue = <String>[]; final List<String> _lineQueue = <String>[];
StreamController<String> get _linesController { late final StreamController<String> _linesController =
_cachedLinesController ??= StreamController<String> StreamController<String>
.broadcast(onListen: () { .broadcast(onListen: () {
_lineQueue.forEach(_linesController.add); _lineQueue.forEach(_linesController.add);
_lineQueue.clear(); _lineQueue.clear();
}); });
return _cachedLinesController;
}
@override @override
Stream<String> get logLines => _linesController.stream; Stream<String> get logLines => _linesController.stream;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment