protocol_discovery.dart 8.12 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7 8
import 'package:meta/meta.dart';

9
import 'base/io.dart';
10
import 'base/logger.dart';
11
import 'device.dart';
12
import 'globals.dart' as globals;
13

14
/// Discovers a specific service protocol on a device, and forwards the service
15
/// protocol device port to the host.
16
class ProtocolDiscovery {
17
  ProtocolDiscovery._(
18 19
    this.logReader,
    this.serviceName, {
20
    this.portForwarder,
21
    this.throttleDuration,
22
    this.throttleTimeout,
23
    this.hostPort,
24
    this.devicePort,
25
    this.ipv6,
26 27 28
    Logger logger,
  }) : _logger = logger,
       assert(logReader != null) {
29 30 31 32 33
    _deviceLogSubscription = logReader.logLines.listen(
      _handleLine,
      onDone: _stopScrapingLogs,
    );
    _uriStreamController = _BufferedStreamController<Uri>();
34 35 36 37 38
  }

  factory ProtocolDiscovery.observatory(
    DeviceLogReader logReader, {
    DevicePortForwarder portForwarder,
39
    Duration throttleDuration,
40
    Duration throttleTimeout,
41 42 43
    @required int hostPort,
    @required int devicePort,
    @required bool ipv6,
44
    Logger logger, // TODO(jonahwilliams): make required.
45 46
  }) {
    const String kObservatoryService = 'Observatory';
47
    return ProtocolDiscovery._(
48 49
      logReader,
      kObservatoryService,
50
      portForwarder: portForwarder,
51
      throttleDuration: throttleDuration ?? const Duration(milliseconds: 200),
52
      throttleTimeout: throttleTimeout,
53
      hostPort: hostPort,
54
      devicePort: devicePort,
55
      ipv6: ipv6,
56
      logger: logger ?? globals.logger,
57
    );
58 59
  }

60 61
  final DeviceLogReader logReader;
  final String serviceName;
62
  final DevicePortForwarder portForwarder;
63
  final int hostPort;
64
  final int devicePort;
65
  final bool ipv6;
66
  final Logger _logger;
67

68 69
  /// The time to wait before forwarding a new observatory URIs from [logReader].
  final Duration throttleDuration;
Devon Carew's avatar
Devon Carew committed
70

71 72 73 74 75
  /// The time between URIs are discovered before timing out when scraping the [logReader].
  ///
  /// If null, log scanning will continue indefinitely.
  final Duration throttleTimeout;

76
  StreamSubscription<String> _deviceLogSubscription;
77
  _BufferedStreamController<Uri> _uriStreamController;
78

79
  /// The discovered service URL.
80 81 82
  ///
  /// Returns null if the log reader shuts down before any uri is found.
  ///
83 84
  /// Use [uris] instead.
  // TODO(egarciad): replace `uri` for `uris`.
85 86 87 88 89 90
  Future<Uri> get uri async {
    try {
      return await uris.first;
    } on StateError {
      return null;
    }
91 92
  }

93
  /// The discovered service URLs.
94
  ///
95 96
  /// When a new observatory URL: is available in [logReader],
  /// the URLs are forwarded at most once every [throttleDuration].
97
  /// Returns when no event has been observed for [throttleTimeout].
98 99
  ///
  /// Port forwarding is only attempted when this is invoked,
100
  /// for each observatory URL in the stream.
101
  Stream<Uri> get uris {
102
    Stream<Uri> uriStream = _uriStreamController.stream
103 104
      .transform(_throttle<Uri>(
        waitDuration: throttleDuration,
105 106 107 108 109 110 111
      ));
    if (throttleTimeout != null) {
      // Don't throw a TimeoutException. The URL wasn't found in time, just close the stream.
      uriStream = uriStream.timeout(throttleTimeout,
          onTimeout: (EventSink<Uri> sink) => sink.close());
    }
    return uriStream.asyncMap<Uri>(_forwardPort);
112
  }
113

114
  Future<void> cancel() => _stopScrapingLogs();
115

116
  Future<void> _stopScrapingLogs() async {
117
    await _uriStreamController?.close();
118 119
    await _deviceLogSubscription?.cancel();
    _deviceLogSubscription = null;
Devon Carew's avatar
Devon Carew committed
120 121
  }

122
  Match _getPatternMatch(String line) {
123
    final RegExp r = RegExp(RegExp.escape(serviceName) + r' listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)');
124 125
    return r.firstMatch(line);
  }
126

127 128
  Uri _getObservatoryUri(String line) {
    final Match match = _getPatternMatch(line);
129
    if (match != null) {
130 131 132 133 134 135 136 137 138
      return Uri.parse(match[1]);
    }
    return null;
  }

  void _handleLine(String line) {
    Uri uri;
    try {
      uri = _getObservatoryUri(line);
139
    } on FormatException catch (error, stackTrace) {
140
      _uriStreamController.addError(error, stackTrace);
141
    }
142 143
    if (uri == null) {
      return;
144
    }
145
    if (devicePort != null && uri.port != devicePort) {
146
      _logger.printTrace('skipping potential observatory $uri due to device port mismatch');
147 148
      return;
    }
149
    _uriStreamController.add(uri);
150 151
  }

152
  Future<Uri> _forwardPort(Uri deviceUri) async {
153
    _logger.printTrace('$serviceName URL on device: $deviceUri');
154 155 156
    Uri hostUri = deviceUri;

    if (portForwarder != null) {
157 158
      final int actualDevicePort = deviceUri.port;
      final int actualHostPort = await portForwarder.forward(actualDevicePort, hostPort: hostPort);
159
      _logger.printTrace('Forwarded host port $actualHostPort to device port $actualDevicePort for $serviceName');
160
      hostUri = deviceUri.replace(port: actualHostPort);
161
    }
Devon Carew's avatar
Devon Carew committed
162

163
    assert(InternetAddress(hostUri.host).isLoopback);
164
    if (ipv6) {
165
      hostUri = hostUri.replace(host: InternetAddress.loopbackIPv6.host);
166
    }
167
    return hostUri;
168 169
  }
}
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

/// Provides a broadcast stream controller that buffers the events
/// if there isn't a listener attached.
/// The events are then delivered when a listener is attached to the stream.
class _BufferedStreamController<T> {
  _BufferedStreamController() : _events = <dynamic>[];

  /// The stream that this controller is controlling.
  Stream<T> get stream {
    return _streamController.stream;
  }

  StreamController<T> _streamControllerInstance;

  StreamController<T> get _streamController {
    _streamControllerInstance ??= StreamController<T>.broadcast(onListen: () {
186
      for (final dynamic event in _events) {
187
        assert(T is! List);
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        if (event is T) {
          _streamControllerInstance.add(event);
        } else {
          _streamControllerInstance.addError(
            event.first as Object,
            event.last as StackTrace,
          );
        }
      }
      _events.clear();
    });
    return _streamControllerInstance;
  }

  final List<dynamic> _events;

  /// Sends [event] if there is a listener attached to the broadcast stream.
  /// Otherwise, it enqueues [event] until a listener is attached.
  void add(T event) {
    if (_streamController.hasListener) {
      _streamController.add(event);
    } else {
      _events.add(event);
    }
  }

  /// Sends or enqueues an error event.
  void addError(Object error, [StackTrace stackTrace]) {
    if (_streamController.hasListener) {
      _streamController.addError(error, stackTrace);
    } else {
      _events.add(<dynamic>[error, stackTrace]);
    }
  }

  /// Closes the stream.
  Future<void> close() {
    return _streamController.close();
  }
}

/// This transformer will produce an event at most once every [waitDuration].
///
/// For example, consider a `waitDuration` of `10ms`, and list of event names
/// and arrival times: `a (0ms), b (5ms), c (11ms), d (21ms)`.
233
/// The events `a`, `c`, and `d` will be produced as a result.
234 235 236 237 238 239 240 241
StreamTransformer<S, S> _throttle<S>({
  @required Duration waitDuration,
}) {
  assert(waitDuration != null);

  S latestLine;
  int lastExecution;
  Future<void> throttleFuture;
242
  bool done = false;
243 244 245 246 247 248

  return StreamTransformer<S, S>
    .fromHandlers(
      handleData: (S value, EventSink<S> sink) {
        latestLine = value;

249
        final bool isFirstMessage = lastExecution == null;
250 251 252
        final int currentTime = DateTime.now().millisecondsSinceEpoch;
        lastExecution ??= currentTime;
        final int remainingTime = currentTime - lastExecution;
253 254 255

        // Always send the first event immediately.
        final int nextExecutionTime = isFirstMessage || remainingTime > waitDuration.inMilliseconds
256 257 258 259 260
          ? 0
          : waitDuration.inMilliseconds - remainingTime;
        throttleFuture ??= Future<void>
          .delayed(Duration(milliseconds: nextExecutionTime))
          .whenComplete(() {
261 262 263
            if (done) {
              return;
            }
264 265 266 267
            sink.add(latestLine);
            throttleFuture = null;
            lastExecution = DateTime.now().millisecondsSinceEpoch;
          });
268 269 270 271
      },
      handleDone: (EventSink<S> sink) {
        done = true;
        sink.close();
272 273 274
      }
    );
}