Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a new WebSocket API #1122

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pkgs/cronet_http/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions pkgs/cronet_http/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import 'package:cupertino_http/cupertino_http.dart';
import 'package:web_socket_conformance_tests/web_socket_conformance_tests.dart';

void main() {
testAll((uri, {protocols}) => CupertinoWebSocket.connect(uri));
}
2 changes: 2 additions & 0 deletions pkgs/cupertino_http/example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ dev_dependencies:
integration_test:
sdk: flutter
test: ^1.21.1
web_socket_conformance_tests:
path: ../../web_socket_conformance_tests

flutter:
uses-material-design: true
1 change: 1 addition & 0 deletions pkgs/cupertino_http/lib/cupertino_http.dart
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,4 @@ import 'src/cupertino_client.dart';

export 'src/cupertino_api.dart';
export 'src/cupertino_client.dart';
export 'src/websocket.dart';
167 changes: 167 additions & 0 deletions pkgs/cupertino_http/lib/src/websocket.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:cupertino_http/cupertino_http.dart';
import 'package:websocket/websocket.dart';

class CupertinoWebSocketException extends XXXWebSocketException {
CupertinoWebSocketException([super.message = '']);

factory CupertinoWebSocketException.fromError(Error e) =>
CupertinoWebSocketException(e.toString());
}

class CupertinoWebSocket implements XXXWebSocket {
static Future<CupertinoWebSocket> connect(Uri uri) async {
final readyCompleter = Completer<void>();
late CupertinoWebSocket webSocket;

final session = URLSession.sessionWithConfiguration(
URLSessionConfiguration.defaultSessionConfiguration(),
onComplete: (session, task, error) {
print('onComplete:');
if (!readyCompleter.isCompleted) {
if (error != null) {
readyCompleter
.completeError(CupertinoWebSocketException.fromError(error));
} else {
readyCompleter.complete();
}
} else {
webSocket._closed(1006, Data.fromList('abnormal close'.codeUnits));
}
}, onWebSocketTaskOpened: (session, task, protocol) {
print('onWebSocketTaskOpened:');
// _protocol = protocol;
readyCompleter.complete();
}, onWebSocketTaskClosed: (session, task, closeCode, reason) {
print('onWebSocketTaskClosed: $closeCode');
webSocket._closed(closeCode, reason);
});
print(uri);
final task = session.webSocketTaskWithRequest(URLRequest.fromUrl(uri))
..resume();
await readyCompleter.future;
return webSocket = CupertinoWebSocket._(task);
}

final URLSessionWebSocketTask _task;
final _events = StreamController<WebSocketEvent>();

void handleMessage(URLSessionWebSocketMessage value) {
print('handleMessage: $value');
late WebSocketEvent v;
switch (value.type) {
case URLSessionWebSocketMessageType.urlSessionWebSocketMessageTypeString:
v = TextDataReceived(value.string!);
break;
case URLSessionWebSocketMessageType.urlSessionWebSocketMessageTypeData:
v = BinaryDataReceived(value.data!.bytes);
break;
}
_events.add(v);
scheduleReceive();
}

void scheduleReceive() {
// print('scheduleReceive');
_task.receiveMessage().then(handleMessage, onError: _closeWithError);
}

CupertinoWebSocket._(this._task) {
scheduleReceive();
}

void _closeWithError(Object e) {
print('closedWithError: $e');
if (e is Error) {
if (e.domain == 'NSPOSIXErrorDomain' && e.code == 57) {
// Socket is not connected.
// onWebSocketTaskClosed/onComplete will be invoked and may indicate a
// close code.
return;
}
var (int code, String? reason) = switch ([e.domain, e.code]) {
['NSPOSIXErrorDomain', 100] => (1002, e.localizedDescription),
_ => (1006, e.localizedDescription)
};
_task.cancel();
_closed(code, reason == null ? null : Data.fromList(reason.codeUnits));
} else {
throw UnsupportedError('');
}
}

void _closed(int? closeCode, Data? reason) {
print('closing with $closeCode');
if (!_events.isClosed) {
final closeReason = reason == null ? '' : utf8.decode(reason.bytes);

_events
..add(CloseReceived(closeCode, closeReason))
..close();
}
}

@override
void sendBytes(Uint8List b) {
if (_events.isClosed) {
throw StateError('WebSocket is closed');
}
_task
.sendMessage(URLSessionWebSocketMessage.fromData(Data.fromList(b)))
.then((_) => _, onError: _closeWithError);
}

@override
void sendText(String s) {
if (_events.isClosed) {
throw StateError('WebSocket is closed');
}
_task
.sendMessage(URLSessionWebSocketMessage.fromString(s))
.then((_) => _, onError: _closeWithError);
}

@override
Future<void> close([int? code, String? reason]) async {
if (_events.isClosed) {
throw XXXWebSocketConnectionClosed();
}

if (code != null) {
RangeError.checkValueInInterval(code, 3000, 4999, 'code');
}
if (reason != null && utf8.encode(reason).length > 123) {
throw ArgumentError.value(reason, 'reason',
'reason must be <= 123 bytes long when encoded as UTF-8');
}

if (!_events.isClosed) {
unawaited(_events.close());

// XXX Wait until all pending writes are done.
print('close($code, $reason)');
if (code != null) {
reason = reason ?? '';
_task.cancelWithCloseCode(code, Data.fromList(reason.codeUnits));
} else {
_task.cancel();
}
}
}

@override
Stream<WebSocketEvent> get events => _events.stream;
}

/*
test('with code and reason', () async {
final channel = await channelFactory(uri);

channel.addString('Please close');
expect(await channel.events.toList(),
[Closed(4123, 'server closed the connection')]);
});
*/
2 changes: 2 additions & 0 deletions pkgs/cupertino_http/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ dependencies:
flutter:
sdk: flutter
http: ^1.2.0
websocket:
path: ../websocket

dev_dependencies:
dart_flutter_team_lints: ^2.0.0
Expand Down
7 changes: 7 additions & 0 deletions pkgs/web_socket_conformance_tests/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/

# Avoid committing pubspec.lock for library packages; see
# https://dart.dev/guides/libraries/private-files#pubspeclock.
pubspec.lock
3 changes: 3 additions & 0 deletions pkgs/web_socket_conformance_tests/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 1.0.0

- Initial version.
39 changes: 39 additions & 0 deletions pkgs/web_socket_conformance_tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<!--
This README describes the package. If you publish this package to pub.dev,
this README's contents appear on the landing page for your package.

For information about how to write a good package README, see the guide for
[writing package pages](https://dart.dev/guides/libraries/writing-package-pages).

For general information about developing packages, see the Dart guide for
[creating packages](https://dart.dev/guides/libraries/create-library-packages)
and the Flutter guide for
[developing packages and plugins](https://flutter.dev/developing-packages).
-->

TODO: Put a short description of the package here that helps potential users
know whether this package might be useful for them.

## Features

TODO: List what your package can do. Maybe include images, gifs, or videos.

## Getting started

TODO: List prerequisites and provide or point to information on how to
start using the package.

## Usage

TODO: Include short and useful examples for package users. Add longer examples
to `/example` folder.

```dart
const like = 'sample';
```

## Additional information

TODO: Tell users more about the package: where to find more information, how to
contribute to the package, how to file issues, what response they can expect
from the package authors, and more.
30 changes: 30 additions & 0 deletions pkgs/web_socket_conformance_tests/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.

include: package:lints/recommended.yaml

# Uncomment the following section to specify additional rules.

# linter:
# rules:
# - camel_case_types

# analyzer:
# exclude:
# - path/to/excluded/files/**

# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints

# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/// Generates the '*_server_vm.dart' and '*_server_web.dart' support files.
library;

import 'dart:core';
import 'dart:io';

import 'package:dart_style/dart_style.dart';

const vm = '''// Generated by generate_server_wrappers.dart. Do not edit.

import 'package:stream_channel/stream_channel.dart';

import '<server_file_placeholder>';

/// Starts the redirect test HTTP server in the same process.
Future<StreamChannel<Object?>> startServer() async {
final controller = StreamChannelController<Object?>(sync: true);
hybridMain(controller.foreign);
return controller.local;
}
''';

const web = '''// Generated by generate_server_wrappers.dart. Do not edit.

import 'package:stream_channel/stream_channel.dart';
import 'package:test/test.dart';

/// Starts the redirect test HTTP server out-of-process.
Future<StreamChannel<Object?>> startServer() async => spawnHybridUri(Uri(
scheme: 'package',
path: 'web_socket_conformance_tests/src/<server_file_placeholder>'));
''';

void main() async {
final files = await Directory('lib/src').list().toList();
final formatter = DartFormatter();

files.where((file) => file.path.endsWith('_server.dart')).forEach((file) {
final vmPath = file.path.replaceAll('_server.dart', '_server_vm.dart');
File(vmPath).writeAsStringSync(formatter.format(vm.replaceAll(
'<server_file_placeholder>', file.uri.pathSegments.last)));

final webPath = file.path.replaceAll('_server.dart', '_server_web.dart');
File(webPath).writeAsStringSync(formatter.format(web.replaceAll(
'<server_file_placeholder>', file.uri.pathSegments.last)));
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import 'package:web_socket_conformance_tests/web_socket_conformance_tests.dart';

void main() {
var awesome = Awesome();
print('awesome: ${awesome.isAwesome}');
}
41 changes: 41 additions & 0 deletions pkgs/web_socket_conformance_tests/lib/src/close_local_server.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. 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:stream_channel/stream_channel.dart';

/// Starts an WebSocket server that echos the payload of the request.
///
/// Channel protocol:
/// On Startup:
/// - send port
/// On Request Received:
/// - echoes the request payload
/// When Receive Anything:
/// - exit
void hybridMain(StreamChannel<Object?> channel) async {
late HttpServer server;

server = (await HttpServer.bind('localhost', 0))
..listen((request) async {
final webSocket = await WebSocketTransformer.upgrade(
request,
);

webSocket.listen((event) {
channel.sink.add(event);
}, onDone: () {
webSocket.close(4123, 'server closed the connection');
channel.sink.add(webSocket.closeCode);
channel.sink.add(webSocket.closeReason);
});
});

channel.sink.add(server.port);
await channel
.stream.first; // Any writes indicates that the server should exit.
unawaited(server.close());
}
Loading
Loading