protocol_discovery.dart 6.85 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 'device.dart';
11
import 'globals.dart' as globals;
12

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

  factory ProtocolDiscovery.observatory(
    DeviceLogReader logReader, {
    DevicePortForwarder portForwarder,
36
    Duration throttleDuration = const Duration(milliseconds: 200),
37 38 39
    @required int hostPort,
    @required int devicePort,
    @required bool ipv6,
40 41
  }) {
    const String kObservatoryService = 'Observatory';
42
    return ProtocolDiscovery._(
43 44
      logReader,
      kObservatoryService,
45
      portForwarder: portForwarder,
46
      throttleDuration: throttleDuration,
47
      hostPort: hostPort,
48
      devicePort: devicePort,
49
      ipv6: ipv6,
50
    );
51 52
  }

53 54
  final DeviceLogReader logReader;
  final String serviceName;
55
  final DevicePortForwarder portForwarder;
56
  final int hostPort;
57
  final int devicePort;
58
  final bool ipv6;
59

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

63
  StreamSubscription<String> _deviceLogSubscription;
64
  _BufferedStreamController<Uri> _uriStreamController;
65

66
  /// The discovered service URL.
67 68 69 70 71 72
  /// Use [uris] instead.
  // TODO(egarciad): replace `uri` for `uris`.
  Future<Uri> get uri {
    return uris.first;
  }

73
  /// The discovered service URLs.
74
  ///
75 76
  /// When a new observatory URL: is available in [logReader],
  /// the URLs are forwarded at most once every [throttleDuration].
77 78
  ///
  /// Port forwarding is only attempted when this is invoked,
79
  /// for each observatory URL in the stream.
80 81 82 83 84 85
  Stream<Uri> get uris {
    return _uriStreamController.stream
      .transform(_throttle<Uri>(
        waitDuration: throttleDuration,
      ))
      .asyncMap<Uri>(_forwardPort);
86
  }
87

88
  Future<void> cancel() => _stopScrapingLogs();
89

90
  Future<void> _stopScrapingLogs() async {
91
    await _uriStreamController?.close();
92 93
    await _deviceLogSubscription?.cancel();
    _deviceLogSubscription = null;
Devon Carew's avatar
Devon Carew committed
94 95
  }

96
  Match _getPatternMatch(String line) {
97
    final RegExp r = RegExp(RegExp.escape(serviceName) + r' listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)');
98 99
    return r.firstMatch(line);
  }
100

101 102
  Uri _getObservatoryUri(String line) {
    final Match match = _getPatternMatch(line);
103
    if (match != null) {
104 105 106 107 108 109 110 111 112 113 114
      return Uri.parse(match[1]);
    }
    return null;
  }

  void _handleLine(String line) {
    Uri uri;
    try {
      uri = _getObservatoryUri(line);
    } on FormatException catch(error, stackTrace) {
      _uriStreamController.addError(error, stackTrace);
115
    }
116 117
    if (uri == null) {
      return;
118
    }
119
    if (devicePort != null && uri.port != devicePort) {
120
      globals.printTrace('skipping potential observatory $uri due to device port mismatch');
121 122
      return;
    }
123
    _uriStreamController.add(uri);
124 125
  }

126
  Future<Uri> _forwardPort(Uri deviceUri) async {
127
    globals.printTrace('$serviceName URL on device: $deviceUri');
128 129 130
    Uri hostUri = deviceUri;

    if (portForwarder != null) {
131 132
      final int actualDevicePort = deviceUri.port;
      final int actualHostPort = await portForwarder.forward(actualDevicePort, hostPort: hostPort);
133
      globals.printTrace('Forwarded host port $actualHostPort to device port $actualDevicePort for $serviceName');
134
      hostUri = deviceUri.replace(port: actualHostPort);
135
    }
Devon Carew's avatar
Devon Carew committed
136

137
    assert(InternetAddress(hostUri.host).isLoopback);
138
    if (ipv6) {
139
      hostUri = hostUri.replace(host: InternetAddress.loopbackIPv6.host);
140
    }
141
    return hostUri;
142 143
  }
}
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

/// 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: () {
160
      for (final dynamic event in _events) {
161
        assert(T is! List);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 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 233 234 235 236 237 238
        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)`.
/// The events `c` and `d` will be produced as a result.
StreamTransformer<S, S> _throttle<S>({
  @required Duration waitDuration,
}) {
  assert(waitDuration != null);

  S latestLine;
  int lastExecution;
  Future<void> throttleFuture;

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

        final int currentTime = DateTime.now().millisecondsSinceEpoch;
        lastExecution ??= currentTime;
        final int remainingTime = currentTime - lastExecution;
        final int nextExecutionTime = remainingTime > waitDuration.inMilliseconds
          ? 0
          : waitDuration.inMilliseconds - remainingTime;

        throttleFuture ??= Future<void>
          .delayed(Duration(milliseconds: nextExecutionTime))
          .whenComplete(() {
            sink.add(latestLine);
            throttleFuture = null;
            lastExecution = DateTime.now().millisecondsSinceEpoch;
          });
      }
    );
}