OLD | NEW |
| (Empty) |
1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 library pub.barback.admin_server; | |
6 | |
7 import 'dart:async'; | |
8 import 'dart:io'; | |
9 | |
10 import 'package:http_parser/http_parser.dart'; | |
11 import 'package:shelf/shelf.dart' as shelf; | |
12 import 'package:shelf_web_socket/shelf_web_socket.dart'; | |
13 | |
14 import '../io.dart'; | |
15 import '../log.dart' as log; | |
16 import 'asset_environment.dart'; | |
17 import 'base_server.dart'; | |
18 import 'web_socket_api.dart'; | |
19 | |
20 /// The web admin interface to pub serve. | |
21 // TODO(rnystrom): Currently this just provides access to the Web Socket API. | |
22 // See #16954. | |
23 class AdminServer extends BaseServer { | |
24 /// All currently open [WebSocket] connections. | |
25 final _webSockets = new Set<CompatibleWebSocket>(); | |
26 | |
27 shelf.Handler _handler; | |
28 | |
29 /// Creates a new server and binds it to [port] of [host]. | |
30 static Future<AdminServer> bind(AssetEnvironment environment, | |
31 String host, int port) { | |
32 return bindServer(host, port).then((server) { | |
33 log.fine('Bound admin server to $host:$port.'); | |
34 return new AdminServer._(environment, server); | |
35 }); | |
36 } | |
37 | |
38 AdminServer._(AssetEnvironment environment, HttpServer server) | |
39 : super(environment, server) { | |
40 _handler = new shelf.Cascade() | |
41 .add(webSocketHandler(_handleWebSocket)) | |
42 .add(_handleHttp).handler; | |
43 } | |
44 | |
45 /// Closes the server and all Web Socket connections. | |
46 Future close() { | |
47 var futures = [super.close()]; | |
48 futures.addAll(_webSockets.map((socket) => socket.close())); | |
49 return Future.wait(futures); | |
50 } | |
51 | |
52 handleRequest(shelf.Request request) => _handler(request); | |
53 | |
54 /// Handles an HTTP request. | |
55 _handleHttp(shelf.Request request) { | |
56 // TODO(rnystrom): Actually respond to requests once there is an admin | |
57 // interface. See #16954. | |
58 logRequest(request, "501 Not Implemented"); | |
59 return new shelf.Response(501, | |
60 body: "Currently this server only accepts Web Socket connections."); | |
61 } | |
62 | |
63 /// Creates a web socket for [request] which should be an upgrade request. | |
64 void _handleWebSocket(CompatibleWebSocket socket) { | |
65 _webSockets.add(socket); | |
66 var api = new WebSocketApi(socket, environment); | |
67 api.listen() | |
68 .whenComplete(() => _webSockets.remove(api)) | |
69 .catchError(addError); | |
70 } | |
71 } | |
OLD | NEW |