dart_vm.dart 10.5 KB
Newer Older
1
// Copyright 2018 The Chromium Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc;
import 'package:web_socket_channel/io.dart';

import '../common/logging.dart';

13
const Duration _kConnectTimeout = Duration(seconds: 9);
14

15
const Duration _kReconnectAttemptInterval = Duration(seconds: 3);
16

17
const Duration _kRpcTimeout = Duration(seconds: 5);
18

19
final Logger _log = Logger('DartVm');
20

21
/// Signature of an asynchronous function for establishing a JSON RPC-2
22
/// connection to a [Uri].
23 24 25 26
typedef RpcPeerConnectionFunction = Future<json_rpc.Peer> Function(
  Uri uri, {
  Duration timeout,
});
27 28 29 30 31 32 33

/// [DartVm] uses this function to connect to the Dart VM on Fuchsia.
///
/// This function can be assigned to a different one in the event that a
/// custom connection function is needed.
RpcPeerConnectionFunction fuchsiaVmServiceConnectionFunction = _waitAndConnect;

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
/// The JSON RPC 2 spec says that a notification from a client must not respond
/// to the client. It's possible the client sent a notification as a "ping", but
/// the service isn't set up yet to respond.
///
/// For example, if the client sends a notification message to the server for
/// 'streamNotify', but the server has not finished loading, it will throw an
/// exception. Since the message is a notification, the server follows the
/// specification and does not send a response back, but is left with an
/// unhandled exception. That exception is safe for us to ignore - the client
/// is signaling that it will try again later if it doesn't get what it wants
/// here by sending a notification.
// This may be ignoring too many exceptions. It would be best to rewrite
// the client code to not use notifications so that it gets error replies back
// and can decide what to do from there.
// TODO(dnfield): https://github.com/flutter/flutter/issues/31813
bool _ignoreRpcError(dynamic error) {
  if (error is json_rpc.RpcException) {
    final json_rpc.RpcException exception = error;
    return exception.data == null || exception.data['id'] == null;
  } else if (error is String && error.startsWith('JSON-RPC error -32601')) {
    return true;
  }
  return false;
}

59 60

void _unhandledJsonRpcError(dynamic error, dynamic stack) {
61 62 63
  if (_ignoreRpcError(error)) {
    return;
  }
64 65 66
  _log.fine('Error in internalimplementation of JSON RPC.\n$error\n$stack');
}

67 68
/// Attempts to connect to a Dart VM service.
///
69 70 71 72 73
/// Gives up after `timeout` has elapsed.
Future<json_rpc.Peer> _waitAndConnect(
  Uri uri, {
  Duration timeout = _kConnectTimeout,
}) async {
74
  final Stopwatch timer = Stopwatch()..start();
75 76 77 78 79

  Future<json_rpc.Peer> attemptConnection(Uri uri) async {
    WebSocket socket;
    json_rpc.Peer peer;
    try {
80
      socket = await WebSocket.connect(uri.toString()).timeout(timeout);
81
      peer = json_rpc.Peer(IOWebSocketChannel(socket).cast(), onUnhandledError: _unhandledJsonRpcError)..listen();
82
      return peer;
83 84 85 86 87 88
    } on HttpException catch (e) {
      // This is a fine warning as this most likely means the port is stale.
      _log.fine('$e: ${e.message}');
      await peer?.close();
      await socket?.close();
      rethrow;
89
    } catch (e) {
90
      _log.fine('Dart VM connection failed $e: ${e.message}');
91
      // Other unknown errors will be handled with reconnects.
92 93
      await peer?.close();
      await socket?.close();
94
      if (timer.elapsed < timeout) {
95
        _log.info('Attempting to reconnect');
96
        await Future<void>.delayed(_kReconnectAttemptInterval);
97 98
        return attemptConnection(uri);
      } else {
99
        _log.warning('Connection to Fuchsia\'s Dart VM timed out at '
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
            '${uri.toString()}');
        rethrow;
      }
    }
  }

  return attemptConnection(uri);
}

/// Restores the VM service connection function to the default implementation.
void restoreVmServiceConnectionFunction() {
  fuchsiaVmServiceConnectionFunction = _waitAndConnect;
}

/// An error raised when a malformed RPC response is received from the Dart VM.
///
/// A more detailed description of the error is found within the [message]
/// field.
class RpcFormatError extends Error {
  /// Basic constructor outlining the reason for the format error.
  RpcFormatError(this.message);

  /// The reason for format error.
  final String message;

  @override
  String toString() {
    return '$RpcFormatError: $message\n${super.stackTrace}';
  }
}

/// Handles JSON RPC-2 communication with a Dart VM service.
///
/// Either wraps existing RPC calls to the Dart VM service, or runs raw RPC
/// function calls via [invokeRpc].
class DartVm {
136
  DartVm._(this._peer, this.uri);
137 138 139

  final json_rpc.Peer _peer;

140 141 142
  /// The URI through which this DartVM instance is connected.
  final Uri uri;

143 144 145
  /// Attempts to connect to the given [Uri].
  ///
  /// Throws an error if unable to connect.
146 147 148 149
  static Future<DartVm> connect(
    Uri uri, {
    Duration timeout = _kConnectTimeout,
  }) async {
150 151 152
    if (uri.scheme == 'http') {
      uri = uri.replace(scheme: 'ws', path: '/ws');
    }
153 154
    final json_rpc.Peer peer =
        await fuchsiaVmServiceConnectionFunction(uri, timeout: timeout);
155 156 157
    if (peer == null) {
      return null;
    }
158
    return DartVm._(peer, uri);
159 160 161 162
  }

  /// Returns a [List] of [IsolateRef] objects whose name matches `pattern`.
  ///
163
  /// This is not limited to Isolates running Flutter, but to any Isolate on the
164 165
  /// VM. Therefore, the [pattern] argument should be written to exclude
  /// matching unintended isolates.
166 167 168 169
  Future<List<IsolateRef>> getMainIsolatesByPattern(
    Pattern pattern, {
    Duration timeout = _kRpcTimeout,
  }) async {
170
    final Map<String, dynamic> jsonVmRef =
171
        await invokeRpc('getVM', timeout: timeout);
172
    final List<IsolateRef> result = <IsolateRef>[];
173
    for (Map<String, dynamic> jsonIsolate in jsonVmRef['isolates']) {
174
      final String name = jsonIsolate['name'];
175
      if (pattern.matchAsPrefix(name) != null) {
176
        _log.fine('Found Isolate matching "$pattern": "$name"');
177
        result.add(IsolateRef._fromJson(jsonIsolate, this));
178 179 180
      }
    }
    return result;
181 182 183 184 185 186 187 188 189 190
  }

  /// Invokes a raw JSON RPC command with the VM service.
  ///
  /// When `timeout` is set and reached, throws a [TimeoutException].
  ///
  /// If the function returns, it is with a parsed JSON response.
  Future<Map<String, dynamic>> invokeRpc(
    String function, {
    Map<String, dynamic> params,
191
    Duration timeout = _kRpcTimeout,
192
  }) async {
193
    final Map<String, dynamic> result = await _peer
194 195 196 197 198 199 200
      .sendRequest(function, params ?? <String, dynamic>{})
      .timeout(timeout, onTimeout: () {
        throw TimeoutException(
          'Peer connection timed out during RPC call',
          timeout,
        );
      });
201
    return result;
202 203 204 205 206 207 208 209
  }

  /// Returns a list of [FlutterView] objects running across all Dart VM's.
  ///
  /// If there is no associated isolate with the flutter view (used to determine
  /// the flutter view's name), then the flutter view's ID will be added
  /// instead. If none of these things can be found (isolate has no name or the
  /// flutter view has no ID), then the result will not be added to the list.
210 211 212
  Future<List<FlutterView>> getAllFlutterViews({
    Duration timeout = _kRpcTimeout,
  }) async {
213 214
    final List<FlutterView> views = <FlutterView>[];
    final Map<String, dynamic> rpcResponse =
215
        await invokeRpc('_flutter.listViews', timeout: timeout);
216
    for (Map<String, dynamic> jsonView in rpcResponse['views']) {
217
      final FlutterView flutterView = FlutterView._fromJson(jsonView);
218 219 220 221 222 223 224 225 226 227
      if (flutterView != null) {
        views.add(flutterView);
      }
    }
    return views;
  }

  /// Disconnects from the Dart VM Service.
  ///
  /// After this function completes this object is no longer usable.
228
  Future<void> stop() async {
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    await _peer?.close();
  }
}

/// Represents an instance of a Flutter view running on a Fuchsia device.
class FlutterView {
  FlutterView._(this._name, this._id);

  /// Attempts to construct a [FlutterView] from a json representation.
  ///
  /// If there is no isolate and no ID for the view, throws an [RpcFormatError].
  /// If there is an associated isolate, and there is no name for said isolate,
  /// also throws an [RpcFormatError].
  ///
  /// All other cases return a [FlutterView] instance. The name of the
  /// view may be null, but the id will always be set.
  factory FlutterView._fromJson(Map<String, dynamic> json) {
    final Map<String, dynamic> isolate = json['isolate'];
    final String id = json['id'];
    String name;
    if (isolate != null) {
      name = isolate['name'];
      if (name == null) {
252
        throw RpcFormatError('Unable to find name for isolate "$isolate"');
253 254 255
      }
    }
    if (id == null) {
256
      throw RpcFormatError(
257 258
          'Unable to find view name for the following JSON structure "$json"');
    }
259
    return FlutterView._(name, id);
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  }

  /// Determines the name of the isolate associated with this view. If there is
  /// no associated isolate, this will be set to the view's ID.
  final String _name;

  /// The ID of the Flutter view.
  final String _id;

  /// The ID of the [FlutterView].
  String get id => _id;

  /// Returns the name of the [FlutterView].
  ///
  /// May be null if there is no associated isolate.
  String get name => _name;
}
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

/// This is a wrapper class for the `@Isolate` RPC object.
///
/// See:
/// https://github.com/dart-lang/sdk/blob/master/runtime/vm/service/service.md#isolate
///
/// This class contains information about the Isolate like its name and ID, as
/// well as a reference to the parent DartVM on which it is running.
class IsolateRef {
  IsolateRef._(this.name, this.number, this.dartVm);

  factory IsolateRef._fromJson(Map<String, dynamic> json, DartVm dartVm) {
    final String number = json['number'];
    final String name = json['name'];
    final String type = json['type'];
    if (type == null) {
293
      throw RpcFormatError('Unable to find type within JSON "$json"');
294 295
    }
    if (type != '@Isolate') {
296
      throw RpcFormatError('Type "$type" does not match for IsolateRef');
297 298
    }
    if (number == null) {
299
      throw RpcFormatError(
300 301 302
          'Unable to find number for isolate ref within JSON "$json"');
    }
    if (name == null) {
303
      throw RpcFormatError(
304 305
          'Unable to find name for isolate ref within JSON "$json"');
    }
306
    return IsolateRef._(name, int.parse(number), dartVm);
307 308 309 310 311 312 313 314 315 316 317
  }

  /// The full name of this Isolate (not guaranteed to be unique).
  final String name;

  /// The unique number ID of this isolate.
  final int number;

  /// The parent [DartVm] on which this Isolate lives.
  final DartVm dartVm;
}