| 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 json_rpc_2.server; | |
| 6 | |
| 7 import 'dart:async'; | |
| 8 import 'dart:collection'; | |
| 9 import 'dart:convert'; | |
| 10 | |
| 11 import 'package:stack_trace/stack_trace.dart'; | |
| 12 | |
| 13 import '../error_code.dart' as error_code; | |
| 14 import 'exception.dart'; | |
| 15 import 'parameters.dart'; | |
| 16 import 'two_way_stream.dart'; | |
| 17 import 'utils.dart'; | |
| 18 | |
| 19 /// A JSON-RPC 2.0 server. | |
| 20 /// | |
| 21 /// A server exposes methods that are called by requests, to which it provides | |
| 22 /// responses. Methods can be registered using [registerMethod] and | |
| 23 /// [registerFallback]. Requests can be handled using [handleRequest] and | |
| 24 /// [parseRequest]. | |
| 25 /// | |
| 26 /// Note that since requests can arrive asynchronously and methods can run | |
| 27 /// asynchronously, it's possible for multiple methods to be invoked at the same | |
| 28 /// time, or even for a single method to be invoked multiple times at once. | |
| 29 class Server { | |
| 30 TwoWayStream _streams; | |
| 31 | |
| 32 /// The methods registered for this server. | |
| 33 final _methods = new Map<String, Function>(); | |
| 34 | |
| 35 /// The fallback methods for this server. | |
| 36 /// | |
| 37 /// These are tried in order until one of them doesn't throw a | |
| 38 /// [RpcException.methodNotFound] exception. | |
| 39 final _fallbacks = new Queue<Function>(); | |
| 40 | |
| 41 /// Creates a [Server] that reads requests from [requests] and writes | |
| 42 /// responses to [responses]. | |
| 43 /// | |
| 44 /// If [requests] is a [StreamSink] as well as a [Stream] (for example, a | |
| 45 /// `WebSocket`), [responses] may be omitted. | |
| 46 /// | |
| 47 /// Note that the server won't begin listening to [requests] until | |
| 48 /// [Server.listen] is called. | |
| 49 Server(Stream<String> requests, [StreamSink<String> responses]) { | |
| 50 _streams = new TwoWayStream("Server", requests, "requests", | |
| 51 responses, "responses", onInvalidInput: (message, error) { | |
| 52 _streams.add(new RpcException(error_code.PARSE_ERROR, | |
| 53 'Invalid JSON: ${error.message}').serialize(message)); | |
| 54 }); | |
| 55 } | |
| 56 | |
| 57 /// Creates a [Server] that reads decoded requests from [requests] and writes | |
| 58 /// decoded responses to [responses]. | |
| 59 /// | |
| 60 /// Unlike [new Server], this doesn't read or write JSON strings. Instead, it | |
| 61 /// reads and writes decoded maps or lists. | |
| 62 /// | |
| 63 /// If [requests] is a [StreamSink] as well as a [Stream], [responses] may be | |
| 64 /// omitted. | |
| 65 /// | |
| 66 /// Note that the server won't begin listening to [requests] until | |
| 67 /// [Server.listen] is called. | |
| 68 Server.withoutJson(Stream requests, [StreamSink responses]) | |
| 69 : _streams = new TwoWayStream.withoutJson( | |
| 70 "Server", requests, "requests", responses, "responses"); | |
| 71 | |
| 72 /// Starts listening to the underlying stream. | |
| 73 /// | |
| 74 /// Returns a [Future] that will complete when the stream is closed or when it | |
| 75 /// has an error. | |
| 76 /// | |
| 77 /// [listen] may only be called once. | |
| 78 Future listen() => _streams.listen(_handleRequest); | |
| 79 | |
| 80 /// Closes the server's request subscription and response sink. | |
| 81 /// | |
| 82 /// Returns a [Future] that completes when all resources have been released. | |
| 83 /// | |
| 84 /// A server can't be closed before [listen] has been called. | |
| 85 Future close() => _streams.close(); | |
| 86 | |
| 87 /// Registers a method named [name] on this server. | |
| 88 /// | |
| 89 /// [callback] can take either zero or one arguments. If it takes zero, any | |
| 90 /// requests for that method that include parameters will be rejected. If it | |
| 91 /// takes one, it will be passed a [Parameters] object. | |
| 92 /// | |
| 93 /// [callback] can return either a JSON-serializable object or a Future that | |
| 94 /// completes to a JSON-serializable object. Any errors in [callback] will be | |
| 95 /// reported to the client as JSON-RPC 2.0 errors. | |
| 96 void registerMethod(String name, Function callback) { | |
| 97 if (_methods.containsKey(name)) { | |
| 98 throw new ArgumentError('There\'s already a method named "$name".'); | |
| 99 } | |
| 100 | |
| 101 _methods[name] = callback; | |
| 102 } | |
| 103 | |
| 104 /// Registers a fallback method on this server. | |
| 105 /// | |
| 106 /// A server may have any number of fallback methods. When a request comes in | |
| 107 /// that doesn't match any named methods, each fallback is tried in order. A | |
| 108 /// fallback can pass on handling a request by throwing a | |
| 109 /// [RpcException.methodNotFound] exception. | |
| 110 /// | |
| 111 /// [callback] can return either a JSON-serializable object or a Future that | |
| 112 /// completes to a JSON-serializable object. Any errors in [callback] will be | |
| 113 /// reported to the client as JSON-RPC 2.0 errors. [callback] may send custom | |
| 114 /// errors by throwing an [RpcException]. | |
| 115 void registerFallback(callback(Parameters parameters)) { | |
| 116 _fallbacks.add(callback); | |
| 117 } | |
| 118 | |
| 119 /// Handle a request. | |
| 120 /// | |
| 121 /// [request] is expected to be a JSON-serializable object representing a | |
| 122 /// request sent by a client. This calls the appropriate method or methods for | |
| 123 /// handling that request and returns a JSON-serializable response, or `null` | |
| 124 /// if no response should be sent. [callback] may send custom | |
| 125 /// errors by throwing an [RpcException]. | |
| 126 Future _handleRequest(request) { | |
| 127 return syncFuture(() { | |
| 128 if (request is! List) return _handleSingleRequest(request); | |
| 129 if (request.isEmpty) { | |
| 130 return new RpcException(error_code.INVALID_REQUEST, 'A batch must ' | |
| 131 'contain at least one request.').serialize(request); | |
| 132 } | |
| 133 | |
| 134 return Future.wait(request.map(_handleSingleRequest)).then((results) { | |
| 135 var nonNull = results.where((result) => result != null); | |
| 136 return nonNull.isEmpty ? null : nonNull.toList(); | |
| 137 }); | |
| 138 }).then(_streams.add); | |
| 139 } | |
| 140 | |
| 141 /// Handles an individual parsed request. | |
| 142 Future _handleSingleRequest(request) { | |
| 143 return syncFuture(() { | |
| 144 _validateRequest(request); | |
| 145 | |
| 146 var name = request['method']; | |
| 147 var method = _methods[name]; | |
| 148 if (method == null) method = _tryFallbacks; | |
| 149 | |
| 150 if (method is ZeroArgumentFunction) { | |
| 151 if (!request.containsKey('params')) return method(); | |
| 152 throw new RpcException.invalidParams('No parameters are allowed for ' | |
| 153 'method "$name".'); | |
| 154 } | |
| 155 | |
| 156 return method(new Parameters(name, request['params'])); | |
| 157 }).then((result) { | |
| 158 // A request without an id is a notification, which should not be sent a | |
| 159 // response, even if one is generated on the server. | |
| 160 if (!request.containsKey('id')) return null; | |
| 161 | |
| 162 return { | |
| 163 'jsonrpc': '2.0', | |
| 164 'result': result, | |
| 165 'id': request['id'] | |
| 166 }; | |
| 167 }).catchError((error, stackTrace) { | |
| 168 if (error is! RpcException) { | |
| 169 error = new RpcException( | |
| 170 error_code.SERVER_ERROR, getErrorMessage(error), data: { | |
| 171 'full': error.toString(), | |
| 172 'stack': new Chain.forTrace(stackTrace).toString() | |
| 173 }); | |
| 174 } | |
| 175 | |
| 176 if (error.code != error_code.INVALID_REQUEST && | |
| 177 !request.containsKey('id')) { | |
| 178 return null; | |
| 179 } else { | |
| 180 return error.serialize(request); | |
| 181 } | |
| 182 }); | |
| 183 } | |
| 184 | |
| 185 /// Validates that [request] matches the JSON-RPC spec. | |
| 186 void _validateRequest(request) { | |
| 187 if (request is! Map) { | |
| 188 throw new RpcException(error_code.INVALID_REQUEST, 'Request must be ' | |
| 189 'an Array or an Object.'); | |
| 190 } | |
| 191 | |
| 192 if (!request.containsKey('jsonrpc')) { | |
| 193 throw new RpcException(error_code.INVALID_REQUEST, 'Request must ' | |
| 194 'contain a "jsonrpc" key.'); | |
| 195 } | |
| 196 | |
| 197 if (request['jsonrpc'] != '2.0') { | |
| 198 throw new RpcException(error_code.INVALID_REQUEST, 'Invalid JSON-RPC ' | |
| 199 'version ${JSON.encode(request['jsonrpc'])}, expected "2.0".'); | |
| 200 } | |
| 201 | |
| 202 if (!request.containsKey('method')) { | |
| 203 throw new RpcException(error_code.INVALID_REQUEST, 'Request must ' | |
| 204 'contain a "method" key.'); | |
| 205 } | |
| 206 | |
| 207 var method = request['method']; | |
| 208 if (request['method'] is! String) { | |
| 209 throw new RpcException(error_code.INVALID_REQUEST, 'Request method must ' | |
| 210 'be a string, but was ${JSON.encode(method)}.'); | |
| 211 } | |
| 212 | |
| 213 var params = request['params']; | |
| 214 if (request.containsKey('params') && params is! List && params is! Map) { | |
| 215 throw new RpcException(error_code.INVALID_REQUEST, 'Request params must ' | |
| 216 'be an Array or an Object, but was ${JSON.encode(params)}.'); | |
| 217 } | |
| 218 | |
| 219 var id = request['id']; | |
| 220 if (id != null && id is! String && id is! num) { | |
| 221 throw new RpcException(error_code.INVALID_REQUEST, 'Request id must be a ' | |
| 222 'string, number, or null, but was ${JSON.encode(id)}.'); | |
| 223 } | |
| 224 } | |
| 225 | |
| 226 /// Try all the fallback methods in order. | |
| 227 Future _tryFallbacks(Parameters params) { | |
| 228 var iterator = _fallbacks.toList().iterator; | |
| 229 | |
| 230 _tryNext() { | |
| 231 if (!iterator.moveNext()) { | |
| 232 return new Future.error( | |
| 233 new RpcException.methodNotFound(params.method), | |
| 234 new Chain.current()); | |
| 235 } | |
| 236 | |
| 237 return syncFuture(() => iterator.current(params)).catchError((error) { | |
| 238 if (error is! RpcException) throw error; | |
| 239 if (error.code != error_code.METHOD_NOT_FOUND) throw error; | |
| 240 return _tryNext(); | |
| 241 }); | |
| 242 } | |
| 243 | |
| 244 return _tryNext(); | |
| 245 } | |
| 246 } | |
| OLD | NEW |