Index: pkg/json_rpc_2/lib/src/server.dart |
diff --git a/pkg/json_rpc_2/lib/src/server.dart b/pkg/json_rpc_2/lib/src/server.dart |
new file mode 100644 |
index 0000000000000000000000000000000000000000..751ac54297fa53629876966ac5882a13103bad3c |
--- /dev/null |
+++ b/pkg/json_rpc_2/lib/src/server.dart |
@@ -0,0 +1,213 @@ |
+// Copyright (c) 2014, 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. |
+ |
+library json_rpc_2.server; |
+ |
+import 'dart:async'; |
+import 'dart:collection'; |
+import 'dart:convert'; |
+ |
+import 'package:stack_trace/stack_trace.dart'; |
+ |
+import '../error_code.dart' as error_code; |
+import 'exception.dart'; |
+import 'parameters.dart'; |
+import 'utils.dart'; |
+ |
+/// A JSON-RPC 2.0 server. |
+/// |
+/// A server exposes methods that are called by requests, to which it provides |
+/// responses. Methods can be registered using [registerMethod] and |
+/// [registerFallback]. Requests can be handled using [handleRequest] and |
+/// [parseRequest]. |
+class Server { |
Bob Nystrom
2014/03/20 18:25:58
I feel like "Server" will lead people to believe t
nweiz
2014/03/20 22:55:41
I think it's most important to follow the spec's n
|
+ /// The methods registered for this server. |
+ final _methods = new Map<String, Function>(); |
+ |
+ /// The fallback methods for this server. |
+ /// |
+ /// These are tried in order until one of their [_Fallback.test] functions |
+ /// returns `true`. |
+ final _fallbacks = new Queue<_Fallback>(); |
+ |
+ Server(); |
+ |
+ /// Registers a method named [name] on this server. |
+ /// |
+ /// [callback] can take either zero or one arguments. If it takes zero, any |
+ /// requests for that method that include parameters will be rejected. If it |
+ /// takes one, it will be passed a [Parameters] object. |
+ /// |
+ /// [callback] can return either a JSON-serializable object or a Future that |
+ /// completes to a JSON-serializable object. Any errors in [callback] will be |
+ /// reported to the client as JSON-RPC 2.0 errors. |
+ void registerMethod(String name, Function callback) { |
+ if (_methods.containsKey(name)) { |
+ throw new ArgumentError('There\'s already a method named "$name".'); |
Bob Nystrom
2014/03/20 18:25:58
Would be good to support either explicit unregistr
nweiz
2014/03/20 22:55:41
I don't want to encourage people to design APIs wh
|
+ } |
+ |
+ _methods[name] = callback; |
+ } |
+ |
+ /// Registers a fallback method on this server. |
+ /// |
+ /// A server may have any number of fallback methods. When a request comes in |
+ /// that doesn't match any named methods, each fallback is tried in order by |
+ /// calling its [test] callback. The first one to return `true` will handle |
+ /// the request. |
+ /// |
+ /// [callback] can return either a JSON-serializable object or a Future that |
+ /// completes to a JSON-serializable object. Any errors in [callback] will be |
+ /// reported to the client as JSON-RPC 2.0 errors. [callback] may send custom |
+ /// errors by throwing an [RpcException]. |
+ void registerFallback(callback(Parameters parameters), |
+ {bool test(String name)}) { |
Bob Nystrom
2014/03/20 18:25:58
Only passing the method name to test() is pretty l
nweiz
2014/03/20 22:55:41
Done. I made it check for a METHOD_NOT_FOUND error
|
+ if (test == null) test = (_) => true; |
+ _fallbacks.add(new _Fallback(callback, test)); |
+ } |
+ |
+ /// Handle a request that's already been parsed from JSON. |
+ /// |
+ /// [request] is expected to be a JSON-serializable object representing a |
+ /// request sent by a client. This calls the appropriate method or methods for |
+ /// handling that request and returns a JSON-serializable response, or `null` |
+ /// if no response should be sent. [callback] may send custom |
+ /// errors by throwing an [RpcException]. |
+ Future handleRequest(request) { |
+ return syncFuture(() { |
+ if (request is! List) return _handleSingleRequest(request); |
Bob Nystrom
2014/03/20 18:25:58
Why support a list of requests? It seems like this
nweiz
2014/03/20 22:55:41
It's in the spec: http://www.jsonrpc.org/specifica
Bob Nystrom
2014/03/21 00:36:02
Well how about that.
|
+ if (request.isEmpty) { |
+ return new RpcException(error_code.INVALID_REQUEST, 'A batch must ' |
Bob Nystrom
2014/03/20 18:25:58
Serializing and returning an exception instead of
nweiz
2014/03/20 22:55:41
It's important that errors be handled in [_handleS
|
+ 'contain at least one request.').serialize(request); |
+ } |
+ |
+ return Future.wait(request.map(_handleSingleRequest)).then((results) { |
Bob Nystrom
2014/03/20 18:25:58
Handling these in parallel might surprise users. D
nweiz
2014/03/20 22:55:41
It's documented in the spec, but okay, I'll add a
|
+ var nonNull = results.where((result) => result != null); |
+ return nonNull.isEmpty ? null : nonNull.toList(); |
+ }); |
+ }); |
+ } |
+ |
+ /// Parses and handles a JSON serialized request. |
+ /// |
+ /// This calls the appropriate method or methods for handling that request and |
+ /// returns a JSON string, or `null` if no response should be sent. |
+ Future<String> parseRequest(String request) { |
+ return syncFuture(() { |
+ var decodedRequest; |
+ try { |
+ decodedRequest = JSON.decode(request); |
+ } on FormatException catch (error) { |
+ return new RpcException(error_code.PARSE_ERROR, 'Invalid JSON: ' |
+ '${error.message}').serialize(request); |
+ } |
+ |
+ return handleRequest(decodedRequest); |
+ }).then((response) { |
+ if (response == null) return null; |
+ return JSON.encode(response); |
+ }); |
+ } |
+ |
+ /// Handles an individual parsed request. |
+ Future _handleSingleRequest(request) { |
+ var parameters; |
+ return syncFuture(() { |
+ _validateRequest(request); |
+ |
+ var name = request['method']; |
+ var method = _methods[name]; |
+ if (method == null) { |
+ method = _fallbacks.firstWhere((fallback) => fallback.test(name), |
+ orElse: () => throw new RpcException.methodNotFound(name)).callback; |
+ } |
+ |
+ if (method is ZeroArgumentFunction) { |
+ if (!request.containsKey('params')) return method(); |
+ throw new RpcException.invalidParams('No parameters are allowed for ' |
+ 'method "$name".'); |
+ } |
+ |
+ parameters = new Parameters(name, request['params']); |
Bob Nystrom
2014/03/20 18:25:58
Unhoist the declaration of this (or just inline it
nweiz
2014/03/20 22:55:41
We can't declare it until we've validated that the
Bob Nystrom
2014/03/21 00:36:02
I just meant to declare the parameters variable he
nweiz
2014/03/21 01:24:16
Oh, got it. This code used to refer to the paramet
|
+ return method(parameters); |
+ }).then((result) { |
+ // A request without an id is a notification, which should not be sent a |
+ // response, even if one is generated on the server. |
+ if (!request.containsKey('id')) return null; |
+ |
+ return { |
+ 'jsonrpc': '2.0', |
+ 'result': result, |
+ 'id': request['id'] |
+ }; |
+ }).catchError((error, stackTrace) { |
+ if (error is! RpcException) { |
+ error = new RpcException( |
+ error_code.SERVER_ERROR, getErrorMessage(error), data: { |
+ 'full': error.toString(), |
+ 'stack': new Chain.forTrace(stackTrace).toString() |
+ }); |
+ } |
+ |
+ if (error.code != error_code.INVALID_REQUEST && |
+ !request.containsKey('id')) { |
+ return null; |
+ } else { |
+ return error.serialize(request); |
+ } |
+ }); |
+ } |
+ |
+ /// Validates that [request] matches the JSON-RPC spec. |
+ void _validateRequest(request) { |
+ if (request is! Map) { |
+ throw new RpcException(error_code.INVALID_REQUEST, 'Requests must be ' |
+ 'Arrays or Objects.'); |
+ } |
+ |
+ if (!request.containsKey('jsonrpc')) { |
+ throw new RpcException(error_code.INVALID_REQUEST, 'Requests must ' |
+ 'contain a "jsonrpc" key.'); |
+ } |
+ |
+ if (request['jsonrpc'] != '2.0') { |
+ throw new RpcException(error_code.INVALID_REQUEST, 'Invalid JSON-RPC ' |
+ 'version "${request['jsonrpc']}", expected "2.0".'); |
+ } |
+ |
+ if (!request.containsKey('method')) { |
+ throw new RpcException(error_code.INVALID_REQUEST, 'Requests must ' |
+ 'contain a "method" key.'); |
+ } |
+ |
+ var method = request['method']; |
+ if (request['method'] is! String) { |
+ throw new RpcException(error_code.INVALID_REQUEST, 'Request method must ' |
+ 'be a string, but was "$method".'); |
Bob Nystrom
2014/03/20 18:25:58
Instead of quoting, how about JSON encoding method
nweiz
2014/03/20 22:55:41
Done.
|
+ } |
+ |
+ var params = request['params']; |
+ if (request.containsKey('params') && params is! List && params is! Map) { |
+ throw new RpcException(error_code.INVALID_REQUEST, 'Request params must ' |
+ 'be an Array or an Object, but was "$params".'); |
+ } |
+ |
+ var id = request['id']; |
+ if (id != null && id is! String && id is! num) { |
+ throw new RpcException(error_code.INVALID_REQUEST, 'Request id must be a ' |
+ 'string, number, or null, but was "$id".'); |
+ } |
+ } |
+} |
+ |
+/// A struct for a fallback method. |
+class _Fallback { |
+ /// The callback function. |
+ final Function callback; |
+ |
+ /// The function to test if a method is valid for this fallback. |
+ final Function test; |
+ |
+ _Fallback(this.callback, this.test); |
+} |