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