This repository has been archived by the owner on Oct 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create a package that implements a JSON-RPC 2.0 server.
R=rnystrom@google.com BUG=17492 Review URL: https://codereview.chromium.org//205533005 git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart/pkg/json_rpc_2@34223 260f80e4-7a28-3924-810f-c04153c831b5
- Loading branch information
0 parents
commit d89eba6
Showing
14 changed files
with
1,526 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
Copyright 2014, the Dart project authors. All rights reserved. | ||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions are | ||
met: | ||
|
||
* Redistributions of source code must retain the above copyright | ||
notice, this list of conditions and the following disclaimer. | ||
* Redistributions in binary form must reproduce the above | ||
copyright notice, this list of conditions and the following | ||
disclaimer in the documentation and/or other materials provided | ||
with the distribution. | ||
* Neither the name of Google Inc. nor the names of its | ||
contributors may be used to endorse or promote products derived | ||
from this software without specific prior written permission. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | ||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | ||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | ||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | ||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | ||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
A library that implements the [JSON-RPC 2.0 spec][spec]. | ||
|
||
[spec]: http://www.jsonrpc.org/specification | ||
|
||
## Server | ||
|
||
A JSON-RPC 2.0 server exposes a set of methods that can be called by clients. | ||
These methods can be registered using `Server.registerMethod`: | ||
|
||
```dart | ||
import "package:json_rpc_2/json_rpc_2.dart" as json_rpc; | ||
var server = new json_rpc.Server(); | ||
// Any string may be used as a method name. JSON-RPC 2.0 methods are | ||
// case-sensitive. | ||
var i = 0; | ||
server.registerMethod("count", () { | ||
// Just return the value to be sent as a response to the client. This can be | ||
// anything JSON-serializable, or a Future that completes to something | ||
// JSON-serializable. | ||
return i++; | ||
}); | ||
// Methods can take parameters. They're presented as a [Parameters] object which | ||
// makes it easy to validate that the expected parameters exist. | ||
server.registerMethod("echo", (params) { | ||
// If the request doesn't have a "message" parameter, this will automatically | ||
// send a response notifying the client that the request was invalid. | ||
return params.getNamed("message"); | ||
}); | ||
// [Parameters] has methods for verifying argument types. | ||
server.registerMethod("subtract", (params) { | ||
// If "minuend" or "subtrahend" aren't numbers, this will reject the request. | ||
return params.getNum("minuend") - params.getNum("subtrahend"); | ||
}); | ||
// [Parameters] also supports optional arguments. | ||
server.registerMethod("sort", (params) { | ||
var list = params.getList("list"); | ||
list.sort(); | ||
if (params.getBool("descending", orElse: () => false)) { | ||
return params.list.reversed; | ||
} else { | ||
return params.list; | ||
} | ||
}); | ||
// A method can send an error response by throwing a `json_rpc.RpcException`. | ||
// Any positive number may be used as an application-defined error code. | ||
const DIVIDE_BY_ZERO = 1; | ||
server.registerMethod("divide", (params) { | ||
var divisor = params.getNum("divisor"); | ||
if (divisor == 0) { | ||
throw new json_rpc.RpcException(DIVIDE_BY_ZERO, "Cannot divide by zero."); | ||
} | ||
return params.getNum("dividend") / divisor; | ||
}); | ||
``` | ||
|
||
Once you've registered your methods, you can handle requests with | ||
`Server.parseRequest`: | ||
|
||
```dart | ||
import 'dart:io'; | ||
WebSocket.connect('ws://localhost:4321').then((socket) { | ||
socket.listen((message) { | ||
server.parseRequest(message).then((response) { | ||
if (response != null) socket.add(response); | ||
}); | ||
}); | ||
}); | ||
``` | ||
|
||
If you're communicating with objects that haven't been serialized to a string, | ||
you can also call `Server.handleRequest` directly: | ||
|
||
```dart | ||
import 'dart:isolate'; | ||
var receive = new ReceivePort(); | ||
Isolate.spawnUri('path/to/client.dart', [], receive.sendPort).then((_) { | ||
receive.listen((message) { | ||
server.handleRequest(message['request']).then((response) { | ||
if (response != null) message['respond'].send(response); | ||
}); | ||
}); | ||
}) | ||
``` | ||
|
||
## Client | ||
|
||
Currently this package does not contain an implementation of a JSON-RPC 2.0 | ||
client. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// 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. | ||
|
||
/// Error codes defined in the [JSON-RPC 2.0 specificiation][spec]. | ||
/// | ||
/// These codes are generally used for protocol-level communication. Most of | ||
/// them shouldn't be used by the application. Those that should have | ||
/// convenience constructors in [RpcException]. | ||
/// | ||
/// [spec]: http://www.jsonrpc.org/specification#error_object | ||
library json_rpc_2.error_code; | ||
|
||
/// An error code indicating that invalid JSON was received by the server. | ||
const PARSE_ERROR = -32700; | ||
|
||
/// An error code indicating that the request JSON was invalid according to the | ||
/// JSON-RPC 2.0 spec. | ||
const INVALID_REQUEST = -32600; | ||
|
||
/// An error code indicating that the requested method does not exist or is | ||
/// unavailable. | ||
const METHOD_NOT_FOUND = -32601; | ||
|
||
/// An error code indicating that the request paramaters are invalid for the | ||
/// requested method. | ||
const INVALID_PARAMS = -32602; | ||
|
||
/// An internal JSON-RPC error. | ||
const INTERNAL_ERROR = -32603; | ||
|
||
/// An unexpected error occurred on the server. | ||
/// | ||
/// The spec reserves the range from -32000 to -32099 for implementation-defined | ||
/// server exceptions, but for now we only use one of those values. | ||
const SERVER_ERROR = -32000; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
// 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; | ||
|
||
export 'src/exception.dart'; | ||
export 'src/parameters.dart'; | ||
export 'src/server.dart'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
// 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.exception; | ||
|
||
import '../error_code.dart' as error_code; | ||
|
||
/// An exception from a JSON-RPC server that can be translated into an error | ||
/// response. | ||
class RpcException implements Exception { | ||
/// The error code. | ||
/// | ||
/// All non-negative error codes are available for use by application | ||
/// developers. | ||
final int code; | ||
|
||
/// The error message. | ||
/// | ||
/// This should be limited to a concise single sentence. Further information | ||
/// should be supplied via [data]. | ||
final String message; | ||
|
||
/// Extra application-defined information about the error. | ||
/// | ||
/// This must be a JSON-serializable object. If it's a [Map] without a | ||
/// `"request"` key, a copy of the request that caused the error will | ||
/// automatically be injected. | ||
final data; | ||
|
||
RpcException(this.code, this.message, {this.data}); | ||
|
||
/// An exception indicating that the method named [methodName] was not found. | ||
/// | ||
/// This should usually be used only by fallback handlers. | ||
RpcException.methodNotFound(String methodName) | ||
: this(error_code.METHOD_NOT_FOUND, 'Unknown method "$methodName".'); | ||
|
||
/// An exception indicating that the parameters for the requested method were | ||
/// invalid. | ||
/// | ||
/// Methods can use this to reject requests with invalid parameters. | ||
RpcException.invalidParams(String message) | ||
: this(error_code.INVALID_PARAMS, message); | ||
|
||
/// Converts this exception into a JSON-serializable object that's a valid | ||
/// JSON-RPC 2.0 error response. | ||
serialize(request) { | ||
var modifiedData; | ||
if (data is Map && !data.containsKey('request')) { | ||
modifiedData = new Map.from(data); | ||
modifiedData['request'] = request; | ||
} else if (data == null) { | ||
modifiedData = {'request': request}; | ||
} | ||
|
||
var id = request is Map ? request['id'] : null; | ||
if (id is! String && id is! num) id = null; | ||
return { | ||
'jsonrpc': '2.0', | ||
'error': {'code': code, 'message': message, 'data': modifiedData}, | ||
'id': id | ||
}; | ||
} | ||
} |
Oops, something went wrong.