mirror of
https://github.com/OMGeeky/tarpc.git
synced 2026-02-23 15:49:54 +01:00
Compare commits
74 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32e0b0d7f8 | ||
|
|
b87c52758e | ||
|
|
9235e12904 | ||
|
|
265fe56fa6 | ||
|
|
7b5b29a9c3 | ||
|
|
fe978f2c56 | ||
|
|
44f472c65c | ||
|
|
e8fcf0e4de | ||
|
|
2eb0b2cc83 | ||
|
|
a8766a9200 | ||
|
|
ef96c87226 | ||
|
|
3543b34f2b | ||
|
|
4c1d15f8ea | ||
|
|
ece1cc60b9 | ||
|
|
7d8a508379 | ||
|
|
9193357d60 | ||
|
|
b777e0bbf7 | ||
|
|
04624f054d | ||
|
|
f870f832a9 | ||
|
|
dc347021d4 | ||
|
|
5973e54f62 | ||
|
|
e5e5c5975c | ||
|
|
6bb3691a30 | ||
|
|
e2f1511fb3 | ||
|
|
99ba380825 | ||
|
|
39235343d6 | ||
|
|
f3afd080f3 | ||
|
|
043d0a1c21 | ||
|
|
be4caeebe8 | ||
|
|
06a2cab31c | ||
|
|
934c51f4ab | ||
|
|
cc8a8e76b0 | ||
|
|
b9ba10b8a4 | ||
|
|
1ee1f9274a | ||
|
|
7f354be850 | ||
|
|
c9a63c2a5a | ||
|
|
ee1143c709 | ||
|
|
4ed127b39e | ||
|
|
66cd136c6a | ||
|
|
58cbe6f4ea | ||
|
|
250a7fd7b9 | ||
|
|
a44fd808d9 | ||
|
|
65c4d83c88 | ||
|
|
00692fe9a3 | ||
|
|
0968760ef7 | ||
|
|
75b2c00b54 | ||
|
|
ffee124526 | ||
|
|
06a03697c4 | ||
|
|
a675551a31 | ||
|
|
d0e9693263 | ||
|
|
6d23174219 | ||
|
|
a06b583334 | ||
|
|
937e9c2c43 | ||
|
|
54883d6354 | ||
|
|
86b1470832 | ||
|
|
82762583be | ||
|
|
3462451256 | ||
|
|
17d800b8a8 | ||
|
|
403eba201b | ||
|
|
f2328d200e | ||
|
|
51e6bac2dc | ||
|
|
f3fcbbb8d2 | ||
|
|
05acb97f04 | ||
|
|
07c052a1c1 | ||
|
|
34cf0c8172 | ||
|
|
7b196400b8 | ||
|
|
1f30bb9ba6 | ||
|
|
e2756edd72 | ||
|
|
8957d2dac3 | ||
|
|
21e5734ef7 | ||
|
|
dddeca19a1 | ||
|
|
a9b86280b5 | ||
|
|
7dae99d7b5 | ||
|
|
9dd3d55744 |
16
.travis.yml
16
.travis.yml
@@ -6,6 +6,13 @@ rust:
|
|||||||
- beta
|
- beta
|
||||||
- nightly
|
- nightly
|
||||||
|
|
||||||
|
addons:
|
||||||
|
apt:
|
||||||
|
packages:
|
||||||
|
- libcurl4-openssl-dev
|
||||||
|
- libelf-dev
|
||||||
|
- libdw-dev
|
||||||
|
|
||||||
before_script:
|
before_script:
|
||||||
- |
|
- |
|
||||||
pip install 'travis-cargo<0.2' --user &&
|
pip install 'travis-cargo<0.2' --user &&
|
||||||
@@ -13,8 +20,13 @@ before_script:
|
|||||||
|
|
||||||
script:
|
script:
|
||||||
- |
|
- |
|
||||||
(cd tarpc && cargo build) &&
|
(cd tarpc && travis-cargo build) &&
|
||||||
(cd tarpc && cargo test)
|
(cd tarpc && travis-cargo test)
|
||||||
|
|
||||||
after_success:
|
after_success:
|
||||||
- (cd tarpc && travis-cargo coveralls --no-sudo)
|
- (cd tarpc && travis-cargo coveralls --no-sudo)
|
||||||
|
|
||||||
|
env:
|
||||||
|
global:
|
||||||
|
# override the default `--features unstable` used for the nightly branch
|
||||||
|
- TRAVIS_CARGO_NIGHTLY_FEATURE=""
|
||||||
|
|||||||
49
README.md
49
README.md
@@ -6,8 +6,27 @@
|
|||||||
|
|
||||||
*Disclaimer*: This is not an official Google product.
|
*Disclaimer*: This is not an official Google product.
|
||||||
|
|
||||||
tarpc is an RPC framework for rust with a focus on ease of use. Defining and implementing an echo-like server can be done in just a few lines of code:
|
tarpc is an RPC framework for rust with a focus on ease of use. Defining a service can be done in
|
||||||
|
just a few lines of code, and most of the boilerplate of writing a server is taken care of for you.
|
||||||
|
|
||||||
|
[Documentation](https://google.github.io/tarpc)
|
||||||
|
|
||||||
|
## What is an RPC framework?
|
||||||
|
"RPC" stands for "Remote Procedure Call," a function call where the work of producing the return
|
||||||
|
value is being done somewhere else. When an rpc function is invoked, behind the scenes the function
|
||||||
|
contacts some other process somewhere and asks them to compute the function instead. The original
|
||||||
|
function then returns the value produced by that other server.
|
||||||
|
|
||||||
|
[More information](https://www.cs.cf.ac.uk/Dave/C/node33.html)
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
Add to your `Cargo.toml` dependencies:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
tarpc = "0.3.0"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example
|
||||||
```rust
|
```rust
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate tarpc;
|
extern crate tarpc;
|
||||||
@@ -17,18 +36,19 @@ mod hello_service {
|
|||||||
rpc hello(name: String) -> String;
|
rpc hello(name: String) -> String;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
use hello_service::Service as HelloService;
|
||||||
|
|
||||||
struct HelloService;
|
struct HelloServer;
|
||||||
impl hello_service::Service for HelloService {
|
impl HelloService for HelloServer {
|
||||||
fn hello(&self, name: String) -> String {
|
fn hello(&self, name: String) -> String {
|
||||||
format!("Hello, {}!", s)
|
format!("Hello, {}!", name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let server_handle = hello_service::serve("0.0.0.0:0", HelloService, None).unwrap();
|
let server_handle = HelloServer.spawn("0.0.0.0:0").unwrap();
|
||||||
let client = hello_service::Client::new(server_handle.local_addr(), None).unwrap();
|
let client = hello_service::Client::new(server_handle.local_addr()).unwrap();
|
||||||
assert_eq!("Hello, Mom!".into(), client.hello("Mom".into()).unwrap());
|
assert_eq!("Hello, Mom!", client.hello("Mom".into()).unwrap());
|
||||||
drop(client);
|
drop(client);
|
||||||
server_handle.shutdown();
|
server_handle.shutdown();
|
||||||
}
|
}
|
||||||
@@ -36,14 +56,19 @@ fn main() {
|
|||||||
|
|
||||||
The `service!` macro expands to a collection of items that collectively form an rpc service. In the
|
The `service!` macro expands to a collection of items that collectively form an rpc service. In the
|
||||||
above example, the macro is called within the `hello_service` module. This module will contain a
|
above example, the macro is called within the `hello_service` module. This module will contain a
|
||||||
`Client` type, a `Service` trait, and a `serve` function. `serve` can be used to start a server
|
`Client` (and `AsyncClient`) type, and a `Service` trait. The trait provides `default fn`s for
|
||||||
listening on a tcp port. A `Client` can connect to such a service. Any type implementing the
|
starting the service: `spawn` and `spawn_with_config`, which start the service listening on a tcp
|
||||||
`Service` trait can be passed to `serve`. These generated types are specific to the echo service,
|
port. A `Client` (or `AsyncClient`) can connect to such a service. These generated types make it
|
||||||
and make it easy and ergonomic to write servers without dealing with sockets or serialization
|
easy and ergonomic to write servers without dealing with sockets or serialization directly. See the
|
||||||
directly. See the tarpc_examples package for more sophisticated examples.
|
tarpc_examples package for more sophisticated examples.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
Use `cargo doc` as you normally would to see the documentation created for all
|
||||||
|
items expanded by a `service!` invocation.
|
||||||
|
|
||||||
## Additional Features
|
## Additional Features
|
||||||
- Concurrent requests from a single client.
|
- Concurrent requests from a single client.
|
||||||
|
- Any type that `impl`s `serde`'s `Serialize` and `Deserialize` can be used in the rpc signatures.
|
||||||
- Attributes can be specified on rpc methods. These will be included on both the `Service` trait
|
- Attributes can be specified on rpc methods. These will be included on both the `Service` trait
|
||||||
methods as well as on the `Client`'s stub methods.
|
methods as well as on the `Client`'s stub methods.
|
||||||
- Just like regular fns, the return type can be left off when it's `-> ()`.
|
- Just like regular fns, the return type can be left off when it's `-> ()`.
|
||||||
|
|||||||
12
RELEASES.md
Normal file
12
RELEASES.md
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
## 1.3 (2016-02-20)
|
||||||
|
|
||||||
|
### Breaking Changes
|
||||||
|
* The timeout arg to `serve` was replaced with a `Config` struct, which
|
||||||
|
currently only contains one field, but will be expanded in the future
|
||||||
|
to allow configuring serialization protocol, and other things.
|
||||||
|
* `serve` was changed to be a default method on the generated `Service` traits,
|
||||||
|
and it was renamed `spawn_with_config`. A second `default fn` was added:
|
||||||
|
`spawn`, which takes no `Config` arg.
|
||||||
|
|
||||||
|
### Other Changes
|
||||||
|
* Expanded items will no longer generate unused warnings.
|
||||||
122
hooks/pre-commit
122
hooks/pre-commit
@@ -1,18 +1,41 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
# Copyright 2016 Google Inc. All Rights Reserved.
|
# Copyright 2016 Google Inc. All Rights Reserved.
|
||||||
#
|
#
|
||||||
# Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
|
# Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
|
||||||
# This file may not be copied, modified, or distributed except according to those terms.
|
# This file may not be copied, modified, or distributed except according to those terms.
|
||||||
|
|
||||||
#!/bin/sh
|
|
||||||
#
|
#
|
||||||
# An example hook script to verify what is about to be committed.
|
# Pre-commit hook for the tarpc repository. To use this hook, copy it to .git/hooks in your
|
||||||
# Called by "git commit" with no arguments. The hook should
|
# repository root.
|
||||||
# exit with non-zero status after issuing an appropriate message if
|
|
||||||
# it wants to stop the commit.
|
|
||||||
#
|
#
|
||||||
# To enable this hook, rename this file to "pre-commit".
|
# This precommit checks the following:
|
||||||
|
# 1. All filenames are ascii
|
||||||
|
# 2. There is no bad whitespace
|
||||||
|
# 3. rustfmt is installed
|
||||||
|
# 4. rustfmt is a noop on files that are in the index
|
||||||
|
#
|
||||||
|
# Options:
|
||||||
|
#
|
||||||
|
# - TARPC_SKIP_RUSTFMT, default = 0
|
||||||
|
#
|
||||||
|
# Set this to 1 to skip running rustfmt
|
||||||
|
#
|
||||||
|
# Note that these options are most useful for testing the hooks themselves. Use git commit
|
||||||
|
# --no-verify to skip the pre-commit hook altogether.
|
||||||
|
|
||||||
if git rev-parse --verify HEAD >/dev/null 2>&1
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[0;33m'
|
||||||
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
|
PREFIX="${GREEN}[PRECOMMIT]${NC}"
|
||||||
|
FAILURE="${RED}FAILED${NC}"
|
||||||
|
WARNING="${RED}[WARNING]${NC}"
|
||||||
|
SKIPPED="${YELLOW}SKIPPED${NC}"
|
||||||
|
SUCCESS="${GREEN}ok${NC}"
|
||||||
|
|
||||||
|
if git rev-parse --verify HEAD &>/dev/null
|
||||||
then
|
then
|
||||||
against=HEAD
|
against=HEAD
|
||||||
else
|
else
|
||||||
@@ -20,35 +43,70 @@ else
|
|||||||
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
|
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# If you want to allow non-ASCII filenames set this variable to true.
|
FAILED=0
|
||||||
allownonascii=$(git config --bool hooks.allownonascii)
|
|
||||||
|
|
||||||
# Redirect output to stderr.
|
printf "${PREFIX} Checking that all filenames are ascii ... "
|
||||||
exec 1>&2
|
# Note that the use of brackets around a tr range is ok here, (it's
|
||||||
|
# even required, for portability to Solaris 10's /usr/bin/tr), since
|
||||||
# Cross platform projects tend to avoid non-ASCII filenames; prevent
|
# the square bracket bytes happen to fall in the designated range.
|
||||||
# them from being added to the repository. We exploit the fact that the
|
if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
|
||||||
# printable range starts at the space character and ends with tilde.
|
|
||||||
if [ "$allownonascii" != "true" ] &&
|
|
||||||
# Note that the use of brackets around a tr range is ok here, (it's
|
|
||||||
# even required, for portability to Solaris 10's /usr/bin/tr), since
|
|
||||||
# the square bracket bytes happen to fall in the designated range.
|
|
||||||
test $(git diff --cached --name-only --diff-filter=A -z $against |
|
|
||||||
LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
|
|
||||||
then
|
then
|
||||||
cat <<\EOF
|
FAILED=1
|
||||||
Error: Attempt to add a non-ASCII file name.
|
printf "${FAILURE}\n"
|
||||||
|
else
|
||||||
|
printf "${SUCCESS}\n"
|
||||||
|
fi
|
||||||
|
|
||||||
This can cause problems if you want to work with people on other platforms.
|
printf "${PREFIX} Checking for bad whitespace ... "
|
||||||
|
git diff-index --check --cached $against -- &>/dev/null
|
||||||
|
if [ "$?" != 0 ]; then
|
||||||
|
FAILED=1
|
||||||
|
printf "${FAILURE}\n"
|
||||||
|
else
|
||||||
|
printf "${SUCCESS}\n"
|
||||||
|
fi
|
||||||
|
|
||||||
To be portable it is advisable to rename the file.
|
printf "${PREFIX} Checking for rustfmt ... "
|
||||||
|
command -v rustfmt &>/dev/null
|
||||||
If you know what you are doing you can disable this check using:
|
if [ $? == 0 ]; then
|
||||||
|
printf "${SUCCESS}\n"
|
||||||
git config hooks.allownonascii true
|
else
|
||||||
EOF
|
printf "${FAILURE}\n"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# If there are whitespace errors, print the offending file names and fail.
|
printf "${PREFIX} Checking for shasum ... "
|
||||||
exec git diff-index --check --cached $against --
|
command -v shasum &>/dev/null
|
||||||
|
if [ $? == 0 ]; then
|
||||||
|
printf "${SUCCESS}\n"
|
||||||
|
else
|
||||||
|
printf "${FAILURE}\n"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Just check that running rustfmt doesn't do anything to the file. I do this instead of
|
||||||
|
# modifying the file because I don't want to mess with the developer's index, which may
|
||||||
|
# not only contain discrete files.
|
||||||
|
printf "${PREFIX} Checking formatting ... "
|
||||||
|
FMTRESULT=0
|
||||||
|
for file in $(git diff --name-only --cached);
|
||||||
|
do
|
||||||
|
if [ ${file: -3} == ".rs" ]; then
|
||||||
|
diff=$(rustfmt --skip-children --write-mode=diff $file)
|
||||||
|
if grep --quiet "^Diff at line" <<< "$diff"; then
|
||||||
|
FMTRESULT=1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "${TARPC_SKIP_RUSTFMT}" == 1 ]; then
|
||||||
|
printf "${SKIPPED}\n"$?
|
||||||
|
elif [ ${FMTRESULT} != 0 ]; then
|
||||||
|
FAILED=1
|
||||||
|
printf "${FAILURE}\n"
|
||||||
|
echo "$diff" | sed '/Using rustfmt.*$/d'
|
||||||
|
else
|
||||||
|
printf "${SUCCESS}\n"
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit ${FAILED}
|
||||||
|
|||||||
136
hooks/pre-push
136
hooks/pre-push
@@ -1,39 +1,127 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
# Copyright 2016 Google Inc. All Rights Reserved.
|
# Copyright 2016 Google Inc. All Rights Reserved.
|
||||||
#
|
#
|
||||||
# Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
|
# Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
|
||||||
# This file may not be copied, modified, or distributed except according to those terms.
|
# This file may not be copied, modified, or distributed except according to those terms.
|
||||||
|
|
||||||
#!/bin/sh
|
# Pre-push hook for the tarpc repository. To use this hook, copy it to .git/hooks in your repository
|
||||||
|
# root.
|
||||||
|
#
|
||||||
|
# This hook runs tests to make sure only working code is being pushed. If present, multirust is used
|
||||||
|
# to build and test the code on the appropriate toolchains. The working copy must not contain
|
||||||
|
# uncommitted changes, since the script currently just runs cargo build/test in the working copy.
|
||||||
|
#
|
||||||
|
# Options:
|
||||||
|
#
|
||||||
|
# - TARPC_ALLOW_DIRTY, default = 0
|
||||||
|
#
|
||||||
|
# Setting this variable to 1 will run tests even though there are code changes in the working
|
||||||
|
# copy. Set to 0 by default, since the intent is to test the code that's being pushed, not changes
|
||||||
|
# still in the working copy.
|
||||||
|
#
|
||||||
|
# - TARPC_USE_CURRENT_TOOLCHAIN, default = 0
|
||||||
|
#
|
||||||
|
# Setting this variable to 1 will just run cargo build and cargo test, rather than running
|
||||||
|
# stable/beta/nightly.
|
||||||
|
#
|
||||||
|
# Note that these options are most useful for testing the hooks themselves. Use git push --no-verify
|
||||||
|
# to skip the pre-push hook altogether.
|
||||||
|
|
||||||
RED='\033[0;31m'
|
RED='\033[0;31m'
|
||||||
GREEN='\033[0;32m'
|
GREEN='\033[0;32m'
|
||||||
YELLOW='\033[0;33m'
|
YELLOW='\033[0;33m'
|
||||||
NC='\033[0m' # No Color
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
|
PREFIX="${GREEN}[PREPUSH]${NC}"
|
||||||
|
FAILURE="${RED}FAILED${NC}"
|
||||||
|
WARNING="${YELLOW}[WARNING]${NC}"
|
||||||
|
SKIPPED="${YELLOW}SKIPPED${NC}"
|
||||||
|
SUCCESS="${GREEN}ok${NC}"
|
||||||
|
|
||||||
|
printf "${PREFIX} Clean working copy ... "
|
||||||
git diff --exit-code &>/dev/null
|
git diff --exit-code &>/dev/null
|
||||||
if [ "$?" != 0 ];
|
if [ "$?" == 0 ]; then
|
||||||
then
|
printf "${SUCCESS}\n"
|
||||||
echo ${RED}ERROR${NC} You have uncommitted changes please commit or stash them before pushing so that I can run tests!
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
printf "${YELLOW}[PRESUBMIT]${NC} Running tests ... "
|
|
||||||
|
|
||||||
TEST_RESULT=0
|
|
||||||
cargo test --manifest-path tarpc/Cargo.toml &>/dev/null
|
|
||||||
if [ "$?" != "0" ];
|
|
||||||
then
|
|
||||||
printf "${RED}FAILED${NC}"
|
|
||||||
TEST_RESULT=1
|
|
||||||
else
|
else
|
||||||
printf "${GREEN}ok${NC}"
|
if [ "${TARPC_ALLOW_DIRTY}" == "1" ]
|
||||||
fi
|
then
|
||||||
printf "\n"
|
printf "${SKIPPED}\n"
|
||||||
|
else
|
||||||
RESULT=0
|
printf "${FAILURE}\n"
|
||||||
if [ "$TEST_RESULT" == "1" ];
|
exit 1
|
||||||
then
|
fi
|
||||||
RESULT=1
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
exit $RESULT
|
PREPUSH_RESULT=0
|
||||||
|
|
||||||
|
# args:
|
||||||
|
# 1 - cargo command to run (build/test)
|
||||||
|
# 2 - directory name of crate to build
|
||||||
|
# 3 - rust toolchain (nightly/stable/beta)
|
||||||
|
run_cargo() {
|
||||||
|
if [ "$1" == "build" ]; then
|
||||||
|
VERB=Building
|
||||||
|
else
|
||||||
|
VERB=Testing
|
||||||
|
fi
|
||||||
|
if [ "$3" != "" ]; then
|
||||||
|
printf "${PREFIX} $VERB $2 on $3 ... "
|
||||||
|
multirust run $3 cargo $1 --manifest-path $2/Cargo.toml &>/dev/null
|
||||||
|
else
|
||||||
|
printf "${PREFIX} $VERB $2 ... "
|
||||||
|
cargo $1 --manifest-path $2/Cargo.toml &>/dev/null
|
||||||
|
fi
|
||||||
|
if [ "$?" != "0" ]; then
|
||||||
|
printf "${FAILURE}\n"
|
||||||
|
PREPUSH_RESULT=1
|
||||||
|
else
|
||||||
|
printf "${SUCCESS}\n"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
TOOLCHAIN_RESULT=0
|
||||||
|
check_toolchain() {
|
||||||
|
printf "${PREFIX} Checking for $1 toolchain ... "
|
||||||
|
if [[ $(multirust list-toolchain) =~ $1 ]]; then
|
||||||
|
printf "${SUCCESS}\n"
|
||||||
|
else
|
||||||
|
TOOLCHAIN_RESULT=1
|
||||||
|
PREPUSH_RESULT=1
|
||||||
|
printf "${FAILURE}\n"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
printf "${PREFIX} Checking for multirust ... "
|
||||||
|
command -v multirust &>/dev/null
|
||||||
|
if [ "$?" == 0 ] && [ "${TARPC_USE_CURRENT_TOOLCHAIN}" == "" ]; then
|
||||||
|
printf "${SUCCESS}\n"
|
||||||
|
|
||||||
|
check_toolchain stable
|
||||||
|
check_toolchain beta
|
||||||
|
check_toolchain nightly
|
||||||
|
if [ ${TOOLCHAIN_RESULT} == 1 ]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
run_cargo build tarpc stable
|
||||||
|
run_cargo build tarpc_examples stable
|
||||||
|
|
||||||
|
run_cargo build tarpc beta
|
||||||
|
run_cargo build tarpc_examples beta
|
||||||
|
|
||||||
|
run_cargo build tarpc nightly
|
||||||
|
run_cargo build tarpc_examples nightly
|
||||||
|
|
||||||
|
# We still rely on some nightly stuff for tests
|
||||||
|
run_cargo test tarpc nightly
|
||||||
|
run_cargo test tarpc_examples nightly
|
||||||
|
else
|
||||||
|
printf "${YELLOW}NOT FOUND${NC}\n"
|
||||||
|
printf "${WARNING} Falling back to current toolchain: $(rustc -V)\n"
|
||||||
|
|
||||||
|
run_cargo test tarpc
|
||||||
|
run_cargo test tarpc_examples
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit $PREPUSH_RESULT
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tarpc"
|
name = "tarpc"
|
||||||
version = "0.2.0"
|
version = "0.4.0"
|
||||||
authors = ["Adam Wright <adam.austin.wright@gmail.com>", "Tim Kuehn <timothy.j.kuehn@gmail.com>"]
|
authors = ["Adam Wright <adam.austin.wright@gmail.com>", "Tim Kuehn <timothy.j.kuehn@gmail.com>"]
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
documentation = "https://google.github.io/tarpc"
|
documentation = "https://google.github.io/tarpc"
|
||||||
@@ -11,11 +11,11 @@ readme = "../README.md"
|
|||||||
description = "An RPC framework for Rust with a focus on ease of use."
|
description = "An RPC framework for Rust with a focus on ease of use."
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bincode = "^0.4.0"
|
bincode = "^0.5"
|
||||||
log = "^0.3.5"
|
log = "^0.3"
|
||||||
scoped-pool = "^0.1.4"
|
scoped-pool = "^0.1"
|
||||||
serde = "^0.6.13"
|
serde = "^0.7"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
lazy_static = "^0.1.15"
|
lazy_static = "^0.1"
|
||||||
env_logger = "^0.3.2"
|
env_logger = "^0.3"
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
# Copyright 2016 Google Inc. All Rights Reserved.
|
|
||||||
#
|
|
||||||
# Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
|
|
||||||
# This file may not be copied, modified, or distributed except according to those terms.
|
|
||||||
|
|
||||||
#!/bin/sh
|
|
||||||
ln -s ../../hooks/pre-commit .git/hooks/pre-commit
|
|
||||||
ln -s ../../hooks/pre-push .git/hooks/pre-push
|
|
||||||
@@ -1 +1,2 @@
|
|||||||
|
ideal_width = 100
|
||||||
reorder_imports = true
|
reorder_imports = true
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
//! Example usage:
|
//! Example usage:
|
||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[macro_use] extern crate tarpc;
|
//! #[macro_use] extern crate tarpc;
|
||||||
//! mod my_server {
|
//! mod my_server {
|
||||||
//! service! {
|
//! service! {
|
||||||
//! rpc hello(name: String) -> String;
|
//! rpc hello(name: String) -> String;
|
||||||
@@ -31,11 +31,8 @@
|
|||||||
//!
|
//!
|
||||||
//! fn main() {
|
//! fn main() {
|
||||||
//! let addr = "127.0.0.1:9000";
|
//! let addr = "127.0.0.1:9000";
|
||||||
//! let shutdown = my_server::serve(addr,
|
//! let shutdown = Server.spawn(addr).unwrap();
|
||||||
//! Server,
|
//! let client = Client::new(addr).unwrap();
|
||||||
//! Some(Duration::from_secs(30)))
|
|
||||||
//! .unwrap();
|
|
||||||
//! let client = Client::new(addr, None).unwrap();
|
|
||||||
//! assert_eq!(3, client.add(1, 2).unwrap());
|
//! assert_eq!(3, client.add(1, 2).unwrap());
|
||||||
//! assert_eq!("Hello, Mom!".to_string(),
|
//! assert_eq!("Hello, Mom!".to_string(),
|
||||||
//! client.hello("Mom".to_string()).unwrap());
|
//! client.hello("Mom".to_string()).unwrap());
|
||||||
@@ -63,4 +60,4 @@ pub mod protocol;
|
|||||||
/// Provides the macro used for constructing rpc services and client stubs.
|
/// Provides the macro used for constructing rpc services and client stubs.
|
||||||
pub mod macros;
|
pub mod macros;
|
||||||
|
|
||||||
pub use protocol::{Error, Result, ServeHandle};
|
pub use protocol::{Config, Error, Result, ServeHandle};
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ pub mod serde {
|
|||||||
pub use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
pub use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||||
/// Deserialization re-exports required by macros. Not for general use.
|
/// Deserialization re-exports required by macros. Not for general use.
|
||||||
pub mod de {
|
pub mod de {
|
||||||
pub use serde::de::{EnumVisitor, Error, Visitor, VariantVisitor};
|
pub use serde::de::{EnumVisitor, Error, VariantVisitor, Visitor};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,6 +21,7 @@ macro_rules! client_methods {
|
|||||||
{ $(#[$attr:meta])* }
|
{ $(#[$attr:meta])* }
|
||||||
$fn_name:ident( ($($arg:ident,)*) : ($($in_:ty,)*) ) -> $out:ty
|
$fn_name:ident( ($($arg:ident,)*) : ($($in_:ty,)*) ) -> $out:ty
|
||||||
) => (
|
) => (
|
||||||
|
#[allow(unused)]
|
||||||
$(#[$attr])*
|
$(#[$attr])*
|
||||||
pub fn $fn_name(&self, $($arg: $in_),*) -> $crate::Result<$out> {
|
pub fn $fn_name(&self, $($arg: $in_),*) -> $crate::Result<$out> {
|
||||||
let reply = try!((self.0).rpc(__Request::$fn_name(($($arg,)*))));
|
let reply = try!((self.0).rpc(__Request::$fn_name(($($arg,)*))));
|
||||||
@@ -32,13 +33,17 @@ macro_rules! client_methods {
|
|||||||
{ $(#[$attr:meta])* }
|
{ $(#[$attr:meta])* }
|
||||||
$fn_name:ident( ($( $arg:ident,)*) : ($($in_:ty, )*) ) -> $out:ty
|
$fn_name:ident( ($( $arg:ident,)*) : ($($in_:ty, )*) ) -> $out:ty
|
||||||
)*) => ( $(
|
)*) => ( $(
|
||||||
|
#[allow(unused)]
|
||||||
$(#[$attr])*
|
$(#[$attr])*
|
||||||
pub fn $fn_name(&self, $($arg: $in_),*) -> $crate::Result<$out> {
|
pub fn $fn_name(&self, $($arg: $in_),*) -> $crate::Result<$out> {
|
||||||
let reply = try!((self.0).rpc(__Request::$fn_name(($($arg,)*))));
|
let reply = try!((self.0).rpc(__Request::$fn_name(($($arg,)*))));
|
||||||
if let __Reply::$fn_name(reply) = reply {
|
if let __Reply::$fn_name(reply) = reply {
|
||||||
::std::result::Result::Ok(reply)
|
::std::result::Result::Ok(reply)
|
||||||
} else {
|
} else {
|
||||||
panic!("Incorrect reply variant returned from protocol::Clientrpc; expected `{}`, but got {:?}", stringify!($fn_name), reply);
|
panic!("Incorrect reply variant returned from rpc; expected `{}`, \
|
||||||
|
but got {:?}",
|
||||||
|
stringify!($fn_name),
|
||||||
|
reply);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)*);
|
)*);
|
||||||
@@ -53,6 +58,7 @@ macro_rules! async_client_methods {
|
|||||||
{ $(#[$attr:meta])* }
|
{ $(#[$attr:meta])* }
|
||||||
$fn_name:ident( ($( $arg:ident, )*) : ($( $in_:ty, )*) ) -> $out:ty
|
$fn_name:ident( ($( $arg:ident, )*) : ($( $in_:ty, )*) ) -> $out:ty
|
||||||
) => (
|
) => (
|
||||||
|
#[allow(unused)]
|
||||||
$(#[$attr])*
|
$(#[$attr])*
|
||||||
pub fn $fn_name(&self, $($arg: $in_),*) -> Future<$out> {
|
pub fn $fn_name(&self, $($arg: $in_),*) -> Future<$out> {
|
||||||
fn mapper(reply: __Reply) -> $out {
|
fn mapper(reply: __Reply) -> $out {
|
||||||
@@ -70,13 +76,17 @@ macro_rules! async_client_methods {
|
|||||||
{ $(#[$attr:meta])* }
|
{ $(#[$attr:meta])* }
|
||||||
$fn_name:ident( ($( $arg:ident, )*) : ($( $in_:ty, )*) ) -> $out:ty
|
$fn_name:ident( ($( $arg:ident, )*) : ($( $in_:ty, )*) ) -> $out:ty
|
||||||
)*) => ( $(
|
)*) => ( $(
|
||||||
|
#[allow(unused)]
|
||||||
$(#[$attr])*
|
$(#[$attr])*
|
||||||
pub fn $fn_name(&self, $($arg: $in_),*) -> Future<$out> {
|
pub fn $fn_name(&self, $($arg: $in_),*) -> Future<$out> {
|
||||||
fn mapper(reply: __Reply) -> $out {
|
fn mapper(reply: __Reply) -> $out {
|
||||||
if let __Reply::$fn_name(reply) = reply {
|
if let __Reply::$fn_name(reply) = reply {
|
||||||
reply
|
reply
|
||||||
} else {
|
} else {
|
||||||
panic!("Incorrect reply variant returned from protocol::Clientrpc; expected `{}`, but got {:?}", stringify!($fn_name), reply);
|
panic!("Incorrect reply variant returned from rpc; expected `{}`, but got \
|
||||||
|
{:?}",
|
||||||
|
stringify!($fn_name),
|
||||||
|
reply);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let reply = (self.0).rpc_async(__Request::$fn_name(($($arg,)*)));
|
let reply = (self.0).rpc_async(__Request::$fn_name(($($arg,)*)));
|
||||||
@@ -100,7 +110,7 @@ macro_rules! impl_serialize {
|
|||||||
match *self {
|
match *self {
|
||||||
$(
|
$(
|
||||||
$impler::$name(ref field) =>
|
$impler::$name(ref field) =>
|
||||||
$crate::macros::serde::Serializer::visit_newtype_variant(
|
$crate::macros::serde::Serializer::serialize_newtype_variant(
|
||||||
serializer,
|
serializer,
|
||||||
stringify!($impler),
|
stringify!($impler),
|
||||||
$n,
|
$n,
|
||||||
@@ -130,7 +140,7 @@ macro_rules! impl_deserialize {
|
|||||||
-> ::std::result::Result<$impler, D::Error>
|
-> ::std::result::Result<$impler, D::Error>
|
||||||
where D: $crate::macros::serde::Deserializer
|
where D: $crate::macros::serde::Deserializer
|
||||||
{
|
{
|
||||||
#[allow(non_camel_case_types)]
|
#[allow(non_camel_case_types, unused)]
|
||||||
enum __Field {
|
enum __Field {
|
||||||
$($name),*
|
$($name),*
|
||||||
}
|
}
|
||||||
@@ -144,6 +154,7 @@ macro_rules! impl_deserialize {
|
|||||||
impl $crate::macros::serde::de::Visitor for __FieldVisitor {
|
impl $crate::macros::serde::de::Visitor for __FieldVisitor {
|
||||||
type Value = __Field;
|
type Value = __Field;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn visit_usize<E>(&mut self, value: usize)
|
fn visit_usize<E>(&mut self, value: usize)
|
||||||
-> ::std::result::Result<__Field, E>
|
-> ::std::result::Result<__Field, E>
|
||||||
where E: $crate::macros::serde::de::Error,
|
where E: $crate::macros::serde::de::Error,
|
||||||
@@ -154,11 +165,12 @@ macro_rules! impl_deserialize {
|
|||||||
}
|
}
|
||||||
)*
|
)*
|
||||||
return ::std::result::Result::Err(
|
return ::std::result::Result::Err(
|
||||||
$crate::macros::serde::de::Error::syntax("expected a field")
|
$crate::macros::serde::de::Error::custom(
|
||||||
|
format!("No variants have a value of {}!", value))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
deserializer.visit_struct_field(__FieldVisitor)
|
deserializer.deserialize_struct_field(__FieldVisitor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,6 +178,7 @@ macro_rules! impl_deserialize {
|
|||||||
impl $crate::macros::serde::de::EnumVisitor for __Visitor {
|
impl $crate::macros::serde::de::EnumVisitor for __Visitor {
|
||||||
type Value = $impler;
|
type Value = $impler;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn visit<__V>(&mut self, mut visitor: __V)
|
fn visit<__V>(&mut self, mut visitor: __V)
|
||||||
-> ::std::result::Result<$impler, __V::Error>
|
-> ::std::result::Result<$impler, __V::Error>
|
||||||
where __V: $crate::macros::serde::de::VariantVisitor
|
where __V: $crate::macros::serde::de::VariantVisitor
|
||||||
@@ -185,7 +198,7 @@ macro_rules! impl_deserialize {
|
|||||||
stringify!($name)
|
stringify!($name)
|
||||||
),*
|
),*
|
||||||
];
|
];
|
||||||
deserializer.visit_enum(stringify!($impler), VARIANTS, __Visitor)
|
deserializer.deserialize_enum(stringify!($impler), VARIANTS, __Visitor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -210,17 +223,22 @@ macro_rules! impl_deserialize {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
|
/// There are two rpc names reserved for the default fns `spawn` and `spawn_with_config`.
|
||||||
|
///
|
||||||
/// Attributes can be attached to each rpc. These attributes
|
/// Attributes can be attached to each rpc. These attributes
|
||||||
/// will then be attached to the generated `Service` trait's
|
/// will then be attached to the generated `Service` trait's
|
||||||
/// corresponding method, as well as to the `Client` stub's rpcs methods.
|
/// corresponding method, as well as to the `Client` stub's rpcs methods.
|
||||||
///
|
///
|
||||||
/// The following items are expanded in the enclosing module:
|
/// The following items are expanded in the enclosing module:
|
||||||
///
|
///
|
||||||
/// * `Service` -- the trait defining the RPC service
|
/// * `Service` -- the trait defining the RPC service. It comes with two default methods for
|
||||||
|
/// starting the server:
|
||||||
|
/// 1. `spawn` starts the service in another thread using default configuration.
|
||||||
|
/// 2. `spawn_with_config` starts the service in another thread using the specified
|
||||||
|
/// `Config`.
|
||||||
/// * `Client` -- a client that makes synchronous requests to the RPC server
|
/// * `Client` -- a client that makes synchronous requests to the RPC server
|
||||||
/// * `AsyncClient` -- a client that makes asynchronous requests to the RPC server
|
/// * `AsyncClient` -- a client that makes asynchronous requests to the RPC server
|
||||||
/// * `Future` -- a handle for asynchronously retrieving the result of an RPC
|
/// * `Future` -- a handle for asynchronously retrieving the result of an RPC
|
||||||
/// * `serve` -- the function that starts the RPC server
|
|
||||||
///
|
///
|
||||||
/// **Warning**: In addition to the above items, there are a few expanded items that
|
/// **Warning**: In addition to the above items, there are a few expanded items that
|
||||||
/// are considered implementation details. As with the above items, shadowing
|
/// are considered implementation details. As with the above items, shadowing
|
||||||
@@ -291,15 +309,34 @@ macro_rules! service_inner {
|
|||||||
)*
|
)*
|
||||||
) => {
|
) => {
|
||||||
#[doc="Defines the RPC service"]
|
#[doc="Defines the RPC service"]
|
||||||
pub trait Service: Send + Sync {
|
pub trait Service: Send + Sync + Sized {
|
||||||
$(
|
$(
|
||||||
$(#[$attr])*
|
$(#[$attr])*
|
||||||
fn $fn_name(&self, $($arg:$in_),*) -> $out;
|
fn $fn_name(&self, $($arg:$in_),*) -> $out;
|
||||||
)*
|
)*
|
||||||
|
|
||||||
|
#[doc="Spawn a running service."]
|
||||||
|
fn spawn<A>(self, addr: A) -> $crate::Result<$crate::protocol::ServeHandle>
|
||||||
|
where A: ::std::net::ToSocketAddrs,
|
||||||
|
Self: 'static,
|
||||||
|
{
|
||||||
|
self.spawn_with_config(addr, $crate::Config::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc="Spawn a running service."]
|
||||||
|
fn spawn_with_config<A>(self, addr: A, config: $crate::Config)
|
||||||
|
-> $crate::Result<$crate::protocol::ServeHandle>
|
||||||
|
where A: ::std::net::ToSocketAddrs,
|
||||||
|
Self: 'static,
|
||||||
|
{
|
||||||
|
let server = ::std::sync::Arc::new(__Server(self));
|
||||||
|
let handle = try!($crate::protocol::Serve::spawn_with_config(server, addr, config));
|
||||||
|
::std::result::Result::Ok(handle)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<P, S> Service for P
|
impl<P, S> Service for P
|
||||||
where P: Send + Sync + ::std::ops::Deref<Target=S>,
|
where P: Send + Sync + Sized + 'static + ::std::ops::Deref<Target=S>,
|
||||||
S: Service
|
S: Service
|
||||||
{
|
{
|
||||||
$(
|
$(
|
||||||
@@ -310,7 +347,7 @@ macro_rules! service_inner {
|
|||||||
)*
|
)*
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(non_camel_case_types)]
|
#[allow(non_camel_case_types, unused)]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum __Request {
|
enum __Request {
|
||||||
$(
|
$(
|
||||||
@@ -321,7 +358,7 @@ macro_rules! service_inner {
|
|||||||
impl_serialize!(__Request, $($fn_name(($($in_),*)))*);
|
impl_serialize!(__Request, $($fn_name(($($in_),*)))*);
|
||||||
impl_deserialize!(__Request, $($fn_name(($($in_),*)))*);
|
impl_deserialize!(__Request, $($fn_name(($($in_),*)))*);
|
||||||
|
|
||||||
#[allow(non_camel_case_types)]
|
#[allow(non_camel_case_types, unused)]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum __Reply {
|
enum __Reply {
|
||||||
$(
|
$(
|
||||||
@@ -332,29 +369,42 @@ macro_rules! service_inner {
|
|||||||
impl_serialize!(__Reply, $($fn_name($out))*);
|
impl_serialize!(__Reply, $($fn_name($out))*);
|
||||||
impl_deserialize!(__Reply, $($fn_name($out))*);
|
impl_deserialize!(__Reply, $($fn_name($out))*);
|
||||||
|
|
||||||
/// An asynchronous RPC call
|
#[allow(unused)]
|
||||||
|
#[doc="An asynchronous RPC call"]
|
||||||
pub struct Future<T> {
|
pub struct Future<T> {
|
||||||
future: $crate::protocol::Future<__Reply>,
|
future: $crate::protocol::Future<__Reply>,
|
||||||
mapper: fn(__Reply) -> T,
|
mapper: fn(__Reply) -> T,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Future<T> {
|
impl<T> Future<T> {
|
||||||
/// Block until the result of the RPC call is available
|
#[allow(unused)]
|
||||||
|
#[doc="Block until the result of the RPC call is available"]
|
||||||
pub fn get(self) -> $crate::Result<T> {
|
pub fn get(self) -> $crate::Result<T> {
|
||||||
self.future.get().map(self.mapper)
|
self.future.get().map(self.mapper)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
#[doc="The client stub that makes RPC calls to the server."]
|
#[doc="The client stub that makes RPC calls to the server."]
|
||||||
pub struct Client($crate::protocol::Client<__Request, __Reply>);
|
pub struct Client($crate::protocol::Client<__Request, __Reply>);
|
||||||
|
|
||||||
impl Client {
|
impl Client {
|
||||||
#[doc="Create a new client that connects to the given address."]
|
#[allow(unused)]
|
||||||
pub fn new<A>(addr: A, timeout: ::std::option::Option<::std::time::Duration>)
|
#[doc="Create a new client with default configuration that connects to the given \
|
||||||
-> $crate::Result<Self>
|
address."]
|
||||||
|
pub fn new<A>(addr: A) -> $crate::Result<Self>
|
||||||
where A: ::std::net::ToSocketAddrs,
|
where A: ::std::net::ToSocketAddrs,
|
||||||
{
|
{
|
||||||
let inner = try!($crate::protocol::Client::new(addr, timeout));
|
Self::with_config(addr, $crate::Config::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
|
#[doc="Create a new client with the specified configuration that connects to the \
|
||||||
|
given address."]
|
||||||
|
pub fn with_config<A>(addr: A, config: $crate::Config) -> $crate::Result<Self>
|
||||||
|
where A: ::std::net::ToSocketAddrs,
|
||||||
|
{
|
||||||
|
let inner = try!($crate::protocol::Client::with_config(addr, config));
|
||||||
::std::result::Result::Ok(Client(inner))
|
::std::result::Result::Ok(Client(inner))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -365,6 +415,7 @@ macro_rules! service_inner {
|
|||||||
)*
|
)*
|
||||||
);
|
);
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
#[doc="Attempt to clone the client object. This might fail if the underlying TcpStream \
|
#[doc="Attempt to clone the client object. This might fail if the underlying TcpStream \
|
||||||
clone fails."]
|
clone fails."]
|
||||||
pub fn try_clone(&self) -> ::std::io::Result<Self> {
|
pub fn try_clone(&self) -> ::std::io::Result<Self> {
|
||||||
@@ -372,16 +423,27 @@ macro_rules! service_inner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
#[doc="The client stub that makes asynchronous RPC calls to the server."]
|
#[doc="The client stub that makes asynchronous RPC calls to the server."]
|
||||||
pub struct AsyncClient($crate::protocol::Client<__Request, __Reply>);
|
pub struct AsyncClient($crate::protocol::Client<__Request, __Reply>);
|
||||||
|
|
||||||
impl AsyncClient {
|
impl AsyncClient {
|
||||||
|
#[allow(unused)]
|
||||||
|
#[doc="Create a new asynchronous client with default configuration that connects to \
|
||||||
|
the given address."]
|
||||||
|
pub fn new<A>(addr: A) -> $crate::Result<Self>
|
||||||
|
where A: ::std::net::ToSocketAddrs,
|
||||||
|
{
|
||||||
|
Self::with_config(addr, $crate::Config::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
#[doc="Create a new asynchronous client that connects to the given address."]
|
#[doc="Create a new asynchronous client that connects to the given address."]
|
||||||
pub fn new<A>(addr: A, timeout: ::std::option::Option<::std::time::Duration>)
|
pub fn with_config<A>(addr: A, config: $crate::Config)
|
||||||
-> $crate::Result<Self>
|
-> $crate::Result<Self>
|
||||||
where A: ::std::net::ToSocketAddrs,
|
where A: ::std::net::ToSocketAddrs,
|
||||||
{
|
{
|
||||||
let inner = try!($crate::protocol::Client::new(addr, timeout));
|
let inner = try!($crate::protocol::Client::with_config(addr, config));
|
||||||
::std::result::Result::Ok(AsyncClient(inner))
|
::std::result::Result::Ok(AsyncClient(inner))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,6 +454,7 @@ macro_rules! service_inner {
|
|||||||
)*
|
)*
|
||||||
);
|
);
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
#[doc="Attempt to clone the client object. This might fail if the underlying TcpStream \
|
#[doc="Attempt to clone the client object. This might fail if the underlying TcpStream \
|
||||||
clone fails."]
|
clone fails."]
|
||||||
pub fn try_clone(&self) -> ::std::io::Result<Self> {
|
pub fn try_clone(&self) -> ::std::io::Result<Self> {
|
||||||
@@ -399,6 +462,7 @@ macro_rules! service_inner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
struct __Server<S: 'static + Service>(S);
|
struct __Server<S: 'static + Service>(S);
|
||||||
|
|
||||||
impl<S> $crate::protocol::Serve for __Server<S>
|
impl<S> $crate::protocol::Serve for __Server<S>
|
||||||
@@ -415,18 +479,6 @@ macro_rules! service_inner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc="Start a running service."]
|
|
||||||
pub fn serve<A, S>(addr: A,
|
|
||||||
service: S,
|
|
||||||
read_timeout: ::std::option::Option<::std::time::Duration>)
|
|
||||||
-> $crate::Result<$crate::protocol::ServeHandle>
|
|
||||||
where A: ::std::net::ToSocketAddrs,
|
|
||||||
S: 'static + Service
|
|
||||||
{
|
|
||||||
let server = ::std::sync::Arc::new(__Server(service));
|
|
||||||
::std::result::Result::Ok(try!($crate::protocol::serve_async(addr, server, read_timeout)))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -461,14 +513,10 @@ mod syntax_test {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod functional_test {
|
mod functional_test {
|
||||||
extern crate env_logger;
|
extern crate env_logger;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
fn test_timeout() -> Option<Duration> {
|
|
||||||
Some(Duration::from_secs(5))
|
|
||||||
}
|
|
||||||
|
|
||||||
service! {
|
service! {
|
||||||
rpc add(x: i32, y: i32) -> i32;
|
rpc add(x: i32, y: i32) -> i32;
|
||||||
|
rpc hey(name: String) -> String;
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Server;
|
struct Server;
|
||||||
@@ -477,14 +525,18 @@ mod functional_test {
|
|||||||
fn add(&self, x: i32, y: i32) -> i32 {
|
fn add(&self, x: i32, y: i32) -> i32 {
|
||||||
x + y
|
x + y
|
||||||
}
|
}
|
||||||
|
fn hey(&self, name: String) -> String {
|
||||||
|
format!("Hey, {}.", name)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn simple() {
|
fn simple() {
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
let handle = serve( "localhost:0", Server, test_timeout()).unwrap();
|
let handle = Server.spawn("localhost:0").unwrap();
|
||||||
let client = Client::new(handle.local_addr(), None).unwrap();
|
let client = Client::new(handle.local_addr()).unwrap();
|
||||||
assert_eq!(3, client.add(1, 2).unwrap());
|
assert_eq!(3, client.add(1, 2).unwrap());
|
||||||
|
assert_eq!("Hey, Tim.", client.hey("Tim".into()).unwrap());
|
||||||
drop(client);
|
drop(client);
|
||||||
handle.shutdown();
|
handle.shutdown();
|
||||||
}
|
}
|
||||||
@@ -492,17 +544,18 @@ mod functional_test {
|
|||||||
#[test]
|
#[test]
|
||||||
fn simple_async() {
|
fn simple_async() {
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
let handle = serve("localhost:0", Server, test_timeout()).unwrap();
|
let handle = Server.spawn("localhost:0").unwrap();
|
||||||
let client = AsyncClient::new(handle.local_addr(), None).unwrap();
|
let client = AsyncClient::new(handle.local_addr()).unwrap();
|
||||||
assert_eq!(3, client.add(1, 2).get().unwrap());
|
assert_eq!(3, client.add(1, 2).get().unwrap());
|
||||||
|
assert_eq!("Hey, Adam.", client.hey("Adam".into()).get().unwrap());
|
||||||
drop(client);
|
drop(client);
|
||||||
handle.shutdown();
|
handle.shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn try_clone() {
|
fn try_clone() {
|
||||||
let handle = serve( "localhost:0", Server, test_timeout()).unwrap();
|
let handle = Server.spawn("localhost:0").unwrap();
|
||||||
let client1 = Client::new(handle.local_addr(), None).unwrap();
|
let client1 = Client::new(handle.local_addr()).unwrap();
|
||||||
let client2 = client1.try_clone().unwrap();
|
let client2 = client1.try_clone().unwrap();
|
||||||
assert_eq!(3, client1.add(1, 2).unwrap());
|
assert_eq!(3, client1.add(1, 2).unwrap());
|
||||||
assert_eq!(3, client2.add(1, 2).unwrap());
|
assert_eq!(3, client2.add(1, 2).unwrap());
|
||||||
@@ -510,8 +563,8 @@ mod functional_test {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn async_try_clone() {
|
fn async_try_clone() {
|
||||||
let handle = serve("localhost:0", Server, test_timeout()).unwrap();
|
let handle = Server.spawn("localhost:0").unwrap();
|
||||||
let client1 = AsyncClient::new(handle.local_addr(), None).unwrap();
|
let client1 = AsyncClient::new(handle.local_addr()).unwrap();
|
||||||
let client2 = client1.try_clone().unwrap();
|
let client2 = client1.try_clone().unwrap();
|
||||||
assert_eq!(3, client1.add(1, 2).get().unwrap());
|
assert_eq!(3, client1.add(1, 2).get().unwrap());
|
||||||
assert_eq!(3, client2.add(1, 2).get().unwrap());
|
assert_eq!(3, client2.add(1, 2).get().unwrap());
|
||||||
@@ -520,7 +573,7 @@ mod functional_test {
|
|||||||
// Tests that a server can be wrapped in an Arc; no need to run, just compile
|
// Tests that a server can be wrapped in an Arc; no need to run, just compile
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn serve_arc_server() {
|
fn serve_arc_server() {
|
||||||
let _ = serve("localhost:0", ::std::sync::Arc::new(Server), None);
|
let _ = ::std::sync::Arc::new(Server).spawn("localhost:0");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -12,9 +12,8 @@ use std::net::{TcpStream, ToSocketAddrs};
|
|||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use super::{Serialize, Deserialize, Error, Packet, Result};
|
use super::{Config, Deserialize, Error, Packet, Result, Serialize};
|
||||||
|
|
||||||
/// A client stub that connects to a server to run rpcs.
|
/// A client stub that connects to a server to run rpcs.
|
||||||
pub struct Client<Request, Reply>
|
pub struct Client<Request, Reply>
|
||||||
@@ -33,10 +32,16 @@ impl<Request, Reply> Client<Request, Reply>
|
|||||||
{
|
{
|
||||||
/// Create a new client that connects to `addr`. The client uses the given timeout
|
/// Create a new client that connects to `addr`. The client uses the given timeout
|
||||||
/// for both reads and writes.
|
/// for both reads and writes.
|
||||||
pub fn new<A: ToSocketAddrs>(addr: A, timeout: Option<Duration>) -> io::Result<Self> {
|
pub fn new<A: ToSocketAddrs>(addr: A) -> io::Result<Self> {
|
||||||
|
Self::with_config(addr, Config::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new client that connects to `addr`. The client uses the given timeout
|
||||||
|
/// for both reads and writes.
|
||||||
|
pub fn with_config<A: ToSocketAddrs>(addr: A, config: Config) -> io::Result<Self> {
|
||||||
let stream = try!(TcpStream::connect(addr));
|
let stream = try!(TcpStream::connect(addr));
|
||||||
try!(stream.set_read_timeout(timeout));
|
try!(stream.set_read_timeout(config.timeout));
|
||||||
try!(stream.set_write_timeout(timeout));
|
try!(stream.set_write_timeout(config.timeout));
|
||||||
let reader_stream = try!(stream.try_clone());
|
let reader_stream = try!(stream.try_clone());
|
||||||
let writer_stream = try!(stream.try_clone());
|
let writer_stream = try!(stream.try_clone());
|
||||||
let requests = Arc::new(Mutex::new(RpcFutures::new()));
|
let requests = Arc::new(Mutex::new(RpcFutures::new()));
|
||||||
@@ -100,15 +105,16 @@ impl<Request, Reply> Drop for Client<Request, Reply>
|
|||||||
if let Some(reader_guard) = Arc::get_mut(&mut self.reader_guard) {
|
if let Some(reader_guard) = Arc::get_mut(&mut self.reader_guard) {
|
||||||
debug!("Attempting to shut down writer and reader threads.");
|
debug!("Attempting to shut down writer and reader threads.");
|
||||||
if let Err(e) = self.shutdown.shutdown(::std::net::Shutdown::Both) {
|
if let Err(e) = self.shutdown.shutdown(::std::net::Shutdown::Both) {
|
||||||
warn!("Client: couldn't shutdown writer and reader threads: {:?}", e);
|
warn!("Client: couldn't shutdown writer and reader threads: {:?}",
|
||||||
|
e);
|
||||||
} else {
|
} else {
|
||||||
// We only join if we know the TcpStream was shut down. Otherwise we might never
|
// We only join if we know the TcpStream was shut down. Otherwise we might never
|
||||||
// finish.
|
// finish.
|
||||||
debug!("Joining writer and reader.");
|
debug!("Joining writer and reader.");
|
||||||
reader_guard.take()
|
reader_guard.take()
|
||||||
.expect(pos!())
|
.expect(pos!())
|
||||||
.join()
|
.join()
|
||||||
.expect(pos!());
|
.expect(pos!());
|
||||||
debug!("Successfully joined writer and reader.");
|
debug!("Successfully joined writer and reader.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -118,14 +124,15 @@ impl<Request, Reply> Drop for Client<Request, Reply>
|
|||||||
/// An asynchronous RPC call
|
/// An asynchronous RPC call
|
||||||
pub struct Future<T> {
|
pub struct Future<T> {
|
||||||
rx: Receiver<Result<T>>,
|
rx: Receiver<Result<T>>,
|
||||||
requests: Arc<Mutex<RpcFutures<T>>>
|
requests: Arc<Mutex<RpcFutures<T>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Future<T> {
|
impl<T> Future<T> {
|
||||||
/// Block until the result of the RPC call is available
|
/// Block until the result of the RPC call is available
|
||||||
pub fn get(self) -> Result<T> {
|
pub fn get(self) -> Result<T> {
|
||||||
let requests = self.requests;
|
let requests = self.requests;
|
||||||
self.rx.recv()
|
self.rx
|
||||||
|
.recv()
|
||||||
.map_err(|_| requests.lock().expect(pos!()).get_error())
|
.map_err(|_| requests.lock().expect(pos!()).get_error())
|
||||||
.and_then(|reply| reply)
|
.and_then(|reply| reply)
|
||||||
}
|
}
|
||||||
@@ -164,7 +171,8 @@ impl<Reply> RpcFutures<Reply> {
|
|||||||
info!("Reader: could not complete reply: {:?}", e);
|
info!("Reader: could not complete reply: {:?}", e);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
warn!("RpcFutures: expected sender for id {} but got None!", packet.rpc_id);
|
warn!("RpcFutures: expected sender for id {} but got None!",
|
||||||
|
packet.rpc_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,10 +186,10 @@ impl<Reply> RpcFutures<Reply> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn write<Request, Reply>(outbound: Receiver<(Request, Sender<Result<Reply>>)>,
|
fn write<Request, Reply>(outbound: Receiver<(Request, Sender<Result<Reply>>)>,
|
||||||
requests: Arc<Mutex<RpcFutures<Reply>>>,
|
requests: Arc<Mutex<RpcFutures<Reply>>>,
|
||||||
stream: TcpStream)
|
stream: TcpStream)
|
||||||
where Request: serde::Serialize,
|
where Request: serde::Serialize,
|
||||||
Reply: serde::Deserialize,
|
Reply: serde::Deserialize
|
||||||
{
|
{
|
||||||
let mut next_id = 0;
|
let mut next_id = 0;
|
||||||
let mut stream = BufWriter::new(stream);
|
let mut stream = BufWriter::new(stream);
|
||||||
@@ -221,8 +229,8 @@ fn write<Request, Reply>(outbound: Receiver<(Request, Sender<Result<Reply>>)>,
|
|||||||
{
|
{
|
||||||
// Clone the err so we can log it if sending fails
|
// Clone the err so we can log it if sending fails
|
||||||
if let Err(e2) = tx.send(Err(e.clone())) {
|
if let Err(e2) = tx.send(Err(e.clone())) {
|
||||||
debug!("Error encountered while trying to send an error. \
|
debug!("Error encountered while trying to send an error. Initial error: {:?}; Send \
|
||||||
Initial error: {:?}; Send error: {:?}",
|
error: {:?}",
|
||||||
e,
|
e,
|
||||||
e2);
|
e2);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,11 @@
|
|||||||
use bincode::{self, SizeLimit};
|
use bincode::{self, SizeLimit};
|
||||||
use bincode::serde::{deserialize_from, serialize_into};
|
use bincode::serde::{deserialize_from, serialize_into};
|
||||||
use serde;
|
use serde;
|
||||||
|
use serde::de::value::Error::EndOfStream;
|
||||||
use std::io::{self, Read, Write};
|
use std::io::{self, Read, Write};
|
||||||
use std::convert;
|
use std::convert;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
mod client;
|
mod client;
|
||||||
mod server;
|
mod server;
|
||||||
@@ -16,7 +18,7 @@ mod packet;
|
|||||||
|
|
||||||
pub use self::packet::Packet;
|
pub use self::packet::Packet;
|
||||||
pub use self::client::{Client, Future};
|
pub use self::client::{Client, Future};
|
||||||
pub use self::server::{Serve, ServeHandle, serve_async};
|
pub use self::server::{Serve, ServeHandle};
|
||||||
|
|
||||||
/// Client errors that can occur during rpc calls
|
/// Client errors that can occur during rpc calls
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -39,10 +41,14 @@ impl convert::From<bincode::serde::SerializeError> for Error {
|
|||||||
impl convert::From<bincode::serde::DeserializeError> for Error {
|
impl convert::From<bincode::serde::DeserializeError> for Error {
|
||||||
fn from(err: bincode::serde::DeserializeError) -> Error {
|
fn from(err: bincode::serde::DeserializeError) -> Error {
|
||||||
match err {
|
match err {
|
||||||
bincode::serde::DeserializeError::IoError(ref err)
|
bincode::serde::DeserializeError::Serde(EndOfStream) => Error::ConnectionBroken,
|
||||||
if err.kind() == io::ErrorKind::ConnectionReset => Error::ConnectionBroken,
|
bincode::serde::DeserializeError::IoError(err) => {
|
||||||
bincode::serde::DeserializeError::EndOfStreamError => Error::ConnectionBroken,
|
match err.kind() {
|
||||||
bincode::serde::DeserializeError::IoError(err) => Error::Io(Arc::new(err)),
|
io::ErrorKind::ConnectionReset |
|
||||||
|
io::ErrorKind::UnexpectedEof => Error::ConnectionBroken,
|
||||||
|
_ => Error::Io(Arc::new(err)),
|
||||||
|
}
|
||||||
|
}
|
||||||
err => panic!("Unexpected error during deserialization: {:?}", err),
|
err => panic!("Unexpected error during deserialization: {:?}", err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -54,13 +60,19 @@ impl convert::From<io::Error> for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Configuration for client and server.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct Config {
|
||||||
|
/// Request/Response timeout between packet delivery.
|
||||||
|
pub timeout: Option<Duration>,
|
||||||
|
}
|
||||||
|
|
||||||
/// Return type of rpc calls: either the successful return value, or a client error.
|
/// Return type of rpc calls: either the successful return value, or a client error.
|
||||||
pub type Result<T> = ::std::result::Result<T, Error>;
|
pub type Result<T> = ::std::result::Result<T, Error>;
|
||||||
|
|
||||||
trait Deserialize: Read + Sized {
|
trait Deserialize: Read + Sized {
|
||||||
fn deserialize<T: serde::Deserialize>(&mut self) -> Result<T> {
|
fn deserialize<T: serde::Deserialize>(&mut self) -> Result<T> {
|
||||||
deserialize_from(self, SizeLimit::Infinite)
|
deserialize_from(self, SizeLimit::Infinite).map_err(Error::from)
|
||||||
.map_err(Error::from)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +91,7 @@ impl<W: Write> Serialize for W {}
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
extern crate env_logger;
|
extern crate env_logger;
|
||||||
use super::{Client, Serve, serve_async};
|
use super::{Client, Config, Serve};
|
||||||
use scoped_pool::Pool;
|
use scoped_pool::Pool;
|
||||||
use std::sync::{Arc, Barrier, Mutex};
|
use std::sync::{Arc, Barrier, Mutex};
|
||||||
use std::thread;
|
use std::thread;
|
||||||
@@ -119,8 +131,8 @@ mod test {
|
|||||||
fn handle() {
|
fn handle() {
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
let server = Arc::new(Server::new());
|
let server = Arc::new(Server::new());
|
||||||
let serve_handle = serve_async("localhost:0", server.clone(), test_timeout()).unwrap();
|
let serve_handle = server.spawn("localhost:0").unwrap();
|
||||||
let client: Client<(), u64> = Client::new(serve_handle.local_addr(), None).unwrap();
|
let client: Client<(), u64> = Client::new(serve_handle.local_addr()).unwrap();
|
||||||
drop(client);
|
drop(client);
|
||||||
serve_handle.shutdown();
|
serve_handle.shutdown();
|
||||||
}
|
}
|
||||||
@@ -129,10 +141,10 @@ mod test {
|
|||||||
fn simple() {
|
fn simple() {
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
let server = Arc::new(Server::new());
|
let server = Arc::new(Server::new());
|
||||||
let serve_handle = serve_async("localhost:0", server.clone(), test_timeout()).unwrap();
|
let serve_handle = server.clone().spawn("localhost:0").unwrap();
|
||||||
let addr = serve_handle.local_addr().clone();
|
let addr = serve_handle.local_addr().clone();
|
||||||
// The explicit type is required so that it doesn't deserialize a u32 instead of u64
|
// The explicit type is required so that it doesn't deserialize a u32 instead of u64
|
||||||
let client: Client<(), u64> = Client::new(addr, None).unwrap();
|
let client: Client<(), u64> = Client::new(addr).unwrap();
|
||||||
assert_eq!(0, client.rpc(()).unwrap());
|
assert_eq!(0, client.rpc(()).unwrap());
|
||||||
assert_eq!(1, server.count());
|
assert_eq!(1, server.count());
|
||||||
assert_eq!(1, client.rpc(()).unwrap());
|
assert_eq!(1, client.rpc(()).unwrap());
|
||||||
@@ -172,9 +184,11 @@ mod test {
|
|||||||
fn force_shutdown() {
|
fn force_shutdown() {
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
let server = Arc::new(Server::new());
|
let server = Arc::new(Server::new());
|
||||||
let serve_handle = serve_async("localhost:0", server, Some(Duration::new(0, 10))).unwrap();
|
let serve_handle = server.spawn_with_config("localhost:0",
|
||||||
|
Config { timeout: Some(Duration::new(0, 10)) })
|
||||||
|
.unwrap();
|
||||||
let addr = serve_handle.local_addr().clone();
|
let addr = serve_handle.local_addr().clone();
|
||||||
let client: Client<(), u64> = Client::new(addr, None).unwrap();
|
let client: Client<(), u64> = Client::new(addr).unwrap();
|
||||||
let thread = thread::spawn(move || serve_handle.shutdown());
|
let thread = thread::spawn(move || serve_handle.shutdown());
|
||||||
info!("force_shutdown:: rpc1: {:?}", client.rpc(()));
|
info!("force_shutdown:: rpc1: {:?}", client.rpc(()));
|
||||||
thread.join().unwrap();
|
thread.join().unwrap();
|
||||||
@@ -184,9 +198,11 @@ mod test {
|
|||||||
fn client_failed_rpc() {
|
fn client_failed_rpc() {
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
let server = Arc::new(Server::new());
|
let server = Arc::new(Server::new());
|
||||||
let serve_handle = serve_async("localhost:0", server, test_timeout()).unwrap();
|
let serve_handle = server.spawn_with_config("localhost:0",
|
||||||
|
Config { timeout: test_timeout() })
|
||||||
|
.unwrap();
|
||||||
let addr = serve_handle.local_addr().clone();
|
let addr = serve_handle.local_addr().clone();
|
||||||
let client: Arc<Client<(), u64>> = Arc::new(Client::new(addr, None).unwrap());
|
let client: Arc<Client<(), u64>> = Arc::new(Client::new(addr).unwrap());
|
||||||
client.rpc(()).unwrap();
|
client.rpc(()).unwrap();
|
||||||
serve_handle.shutdown();
|
serve_handle.shutdown();
|
||||||
match client.rpc(()) {
|
match client.rpc(()) {
|
||||||
@@ -202,13 +218,15 @@ mod test {
|
|||||||
let concurrency = 10;
|
let concurrency = 10;
|
||||||
let pool = Pool::new(concurrency);
|
let pool = Pool::new(concurrency);
|
||||||
let server = Arc::new(BarrierServer::new(concurrency));
|
let server = Arc::new(BarrierServer::new(concurrency));
|
||||||
let serve_handle = serve_async("localhost:0", server.clone(), test_timeout()).unwrap();
|
let serve_handle = server.clone().spawn("localhost:0").unwrap();
|
||||||
let addr = serve_handle.local_addr().clone();
|
let addr = serve_handle.local_addr().clone();
|
||||||
let client: Client<(), u64> = Client::new(addr, None).unwrap();
|
let client: Client<(), u64> = Client::new(addr).unwrap();
|
||||||
pool.scoped(|scope| {
|
pool.scoped(|scope| {
|
||||||
for _ in 0..concurrency {
|
for _ in 0..concurrency {
|
||||||
let client = client.try_clone().unwrap();
|
let client = client.try_clone().unwrap();
|
||||||
scope.execute(move || { client.rpc(()).unwrap(); });
|
scope.execute(move || {
|
||||||
|
client.rpc(()).unwrap();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
assert_eq!(concurrency as u64, server.count());
|
assert_eq!(concurrency as u64, server.count());
|
||||||
@@ -220,9 +238,9 @@ mod test {
|
|||||||
fn async() {
|
fn async() {
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
let server = Arc::new(Server::new());
|
let server = Arc::new(Server::new());
|
||||||
let serve_handle = serve_async("localhost:0", server.clone(), None).unwrap();
|
let serve_handle = server.spawn("localhost:0").unwrap();
|
||||||
let addr = serve_handle.local_addr().clone();
|
let addr = serve_handle.local_addr().clone();
|
||||||
let client: Client<(), u64> = Client::new(addr, None).unwrap();
|
let client: Client<(), u64> = Client::new(addr).unwrap();
|
||||||
|
|
||||||
// Drop future immediately; does the reader channel panic when sending?
|
// Drop future immediately; does the reader channel panic when sending?
|
||||||
client.rpc_async(());
|
client.rpc_async(());
|
||||||
|
|||||||
@@ -19,10 +19,11 @@ impl<T: Serialize> Serialize for Packet<T> {
|
|||||||
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
|
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
|
||||||
where S: Serializer
|
where S: Serializer
|
||||||
{
|
{
|
||||||
serializer.visit_struct(PACKET, MapVisitor {
|
serializer.serialize_struct(PACKET,
|
||||||
value: self,
|
MapVisitor {
|
||||||
state: 0,
|
value: self,
|
||||||
})
|
state: 0,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,32 +32,37 @@ struct MapVisitor<'a, T: 'a> {
|
|||||||
state: u8,
|
state: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl <'a, T: Serialize> ser::MapVisitor for MapVisitor<'a, T> {
|
impl<'a, T: Serialize> ser::MapVisitor for MapVisitor<'a, T> {
|
||||||
|
#[inline]
|
||||||
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
|
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
|
||||||
where S: Serializer
|
where S: Serializer
|
||||||
{
|
{
|
||||||
match self.state {
|
match self.state {
|
||||||
0 => {
|
0 => {
|
||||||
self.state += 1;
|
self.state += 1;
|
||||||
Ok(Some(try!(serializer.visit_struct_elt(RPC_ID, &self.value.rpc_id))))
|
Ok(Some(try!(serializer.serialize_struct_elt(RPC_ID, &self.value.rpc_id))))
|
||||||
}
|
}
|
||||||
1 => {
|
1 => {
|
||||||
self.state += 1;
|
self.state += 1;
|
||||||
Ok(Some(try!(serializer.visit_struct_elt(MESSAGE, &self.value.message))))
|
Ok(Some(try!(serializer.serialize_struct_elt(MESSAGE, &self.value.message))))
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
Ok(None)
|
|
||||||
}
|
}
|
||||||
|
_ => Ok(None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn len(&self) -> Option<usize> {
|
||||||
|
Some(2)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Deserialize> Deserialize for Packet<T> {
|
impl<T: Deserialize> Deserialize for Packet<T> {
|
||||||
|
#[inline]
|
||||||
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
|
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
|
||||||
where D: Deserializer
|
where D: Deserializer
|
||||||
{
|
{
|
||||||
const FIELDS: &'static [&'static str] = &[RPC_ID, MESSAGE];
|
const FIELDS: &'static [&'static str] = &[RPC_ID, MESSAGE];
|
||||||
deserializer.visit_struct(PACKET, FIELDS, Visitor(PhantomData))
|
deserializer.deserialize_struct(PACKET, FIELDS, Visitor(PhantomData))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,6 +71,7 @@ struct Visitor<T>(PhantomData<T>);
|
|||||||
impl<T: Deserialize> de::Visitor for Visitor<T> {
|
impl<T: Deserialize> de::Visitor for Visitor<T> {
|
||||||
type Value = Packet<T>;
|
type Value = Packet<T>;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Packet<T>, V::Error>
|
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Packet<T>, V::Error>
|
||||||
where V: de::SeqVisitor
|
where V: de::SeqVisitor
|
||||||
{
|
{
|
||||||
@@ -91,7 +98,10 @@ fn serde() {
|
|||||||
use bincode;
|
use bincode;
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
|
|
||||||
let packet = Packet { rpc_id: 1, message: () };
|
let packet = Packet {
|
||||||
|
rpc_id: 1,
|
||||||
|
message: (),
|
||||||
|
};
|
||||||
let ser = bincode::serde::serialize(&packet, bincode::SizeLimit::Infinite).unwrap();
|
let ser = bincode::serde::serialize(&packet, bincode::SizeLimit::Infinite).unwrap();
|
||||||
let de = bincode::serde::deserialize(&ser);
|
let de = bincode::serde::deserialize(&ser);
|
||||||
assert_eq!(packet, de.unwrap());
|
assert_eq!(packet, de.unwrap());
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
|
|||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::thread::{self, JoinHandle};
|
use std::thread::{self, JoinHandle};
|
||||||
use super::{Deserialize, Error, Packet, Result, Serialize};
|
use super::{Config, Deserialize, Error, Packet, Result, Serialize};
|
||||||
|
|
||||||
struct ConnectionHandler<'a, S>
|
struct ConnectionHandler<'a, S>
|
||||||
where S: Serve
|
where S: Serve
|
||||||
@@ -44,7 +44,7 @@ impl<'a, S> ConnectionHandler<'a, S>
|
|||||||
let reply = server.serve(message);
|
let reply = server.serve(message);
|
||||||
let reply_packet = Packet {
|
let reply_packet = Packet {
|
||||||
rpc_id: rpc_id,
|
rpc_id: rpc_id,
|
||||||
message: reply
|
message: reply,
|
||||||
};
|
};
|
||||||
tx.send(reply_packet).expect(pos!());
|
tx.send(reply_packet).expect(pos!());
|
||||||
});
|
});
|
||||||
@@ -55,8 +55,8 @@ impl<'a, S> ConnectionHandler<'a, S>
|
|||||||
}
|
}
|
||||||
Err(Error::Io(ref err)) if Self::timed_out(err.kind()) => {
|
Err(Error::Io(ref err)) if Self::timed_out(err.kind()) => {
|
||||||
if !shutdown.load(Ordering::SeqCst) {
|
if !shutdown.load(Ordering::SeqCst) {
|
||||||
info!("ConnectionHandler: read timed out ({:?}). Server not \
|
info!("ConnectionHandler: read timed out ({:?}). Server not shutdown, so \
|
||||||
shutdown, so retrying read.",
|
retrying read.",
|
||||||
err);
|
err);
|
||||||
continue;
|
continue;
|
||||||
} else {
|
} else {
|
||||||
@@ -142,7 +142,9 @@ struct Server<'a, S: 'a> {
|
|||||||
impl<'a, S: 'a> Server<'a, S>
|
impl<'a, S: 'a> Server<'a, S>
|
||||||
where S: Serve + 'static
|
where S: Serve + 'static
|
||||||
{
|
{
|
||||||
fn serve<'b>(self, scope: &Scope<'b>) where 'a: 'b {
|
fn serve<'b>(self, scope: &Scope<'b>)
|
||||||
|
where 'a: 'b
|
||||||
|
{
|
||||||
for conn in self.listener.incoming() {
|
for conn in self.listener.incoming() {
|
||||||
match self.die_rx.try_recv() {
|
match self.die_rx.try_recv() {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
@@ -169,7 +171,7 @@ impl<'a, S: 'a> Server<'a, S>
|
|||||||
let read_conn = match conn.try_clone() {
|
let read_conn = match conn.try_clone() {
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("serve: could not clone tcp stream; possibly out of file descriptors? \
|
error!("serve: could not clone tcp stream; possibly out of file descriptors? \
|
||||||
Err: {:?}",
|
Err: {:?}",
|
||||||
err);
|
err);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -199,41 +201,8 @@ impl<'a, S> Drop for Server<'a, S> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start
|
|
||||||
pub fn serve_async<A, S>(addr: A,
|
|
||||||
server: S,
|
|
||||||
read_timeout: Option<Duration>)
|
|
||||||
-> io::Result<ServeHandle>
|
|
||||||
where A: ToSocketAddrs,
|
|
||||||
S: 'static + Serve
|
|
||||||
{
|
|
||||||
let listener = try!(TcpListener::bind(&addr));
|
|
||||||
let addr = try!(listener.local_addr());
|
|
||||||
info!("serve_async: spinning up server on {:?}", addr);
|
|
||||||
let (die_tx, die_rx) = channel();
|
|
||||||
let join_handle = thread::spawn(move || {
|
|
||||||
let pool = Pool::new(100); // TODO(tjk): make this configurable, and expire idle threads
|
|
||||||
let shutdown = AtomicBool::new(false);
|
|
||||||
let server = Server {
|
|
||||||
server: &server,
|
|
||||||
listener: listener,
|
|
||||||
read_timeout: read_timeout,
|
|
||||||
die_rx: die_rx,
|
|
||||||
shutdown: &shutdown,
|
|
||||||
};
|
|
||||||
pool.scoped(|scope| {
|
|
||||||
server.serve(scope);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
Ok(ServeHandle {
|
|
||||||
tx: die_tx,
|
|
||||||
join_handle: join_handle,
|
|
||||||
addr: addr.clone(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A service provided by a server
|
/// A service provided by a server
|
||||||
pub trait Serve: Send + Sync {
|
pub trait Serve: Send + Sync + Sized {
|
||||||
/// The type of request received by the server
|
/// The type of request received by the server
|
||||||
type Request: 'static + fmt::Debug + serde::ser::Serialize + serde::de::Deserialize + Send;
|
type Request: 'static + fmt::Debug + serde::ser::Serialize + serde::de::Deserialize + Send;
|
||||||
/// The type of reply sent by the server
|
/// The type of reply sent by the server
|
||||||
@@ -241,10 +210,49 @@ pub trait Serve: Send + Sync {
|
|||||||
|
|
||||||
/// Return a reply for a given request
|
/// Return a reply for a given request
|
||||||
fn serve(&self, request: Self::Request) -> Self::Reply;
|
fn serve(&self, request: Self::Request) -> Self::Reply;
|
||||||
|
|
||||||
|
/// spawn
|
||||||
|
fn spawn<A>(self, addr: A) -> io::Result<ServeHandle>
|
||||||
|
where A: ToSocketAddrs,
|
||||||
|
Self: 'static
|
||||||
|
{
|
||||||
|
self.spawn_with_config(addr, Config::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// spawn
|
||||||
|
fn spawn_with_config<A>(self, addr: A, config: Config) -> io::Result<ServeHandle>
|
||||||
|
where A: ToSocketAddrs,
|
||||||
|
Self: 'static
|
||||||
|
{
|
||||||
|
let listener = try!(TcpListener::bind(&addr));
|
||||||
|
let addr = try!(listener.local_addr());
|
||||||
|
info!("spawn_with_config: spinning up server on {:?}", addr);
|
||||||
|
let (die_tx, die_rx) = channel();
|
||||||
|
let join_handle = thread::spawn(move || {
|
||||||
|
let pool = Pool::new(100); // TODO(tjk): make this configurable, and expire idle threads
|
||||||
|
let shutdown = AtomicBool::new(false);
|
||||||
|
let server = Server {
|
||||||
|
server: &self,
|
||||||
|
listener: listener,
|
||||||
|
read_timeout: config.timeout,
|
||||||
|
die_rx: die_rx,
|
||||||
|
shutdown: &shutdown,
|
||||||
|
};
|
||||||
|
pool.scoped(|scope| {
|
||||||
|
server.serve(scope);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Ok(ServeHandle {
|
||||||
|
tx: die_tx,
|
||||||
|
join_handle: join_handle,
|
||||||
|
addr: addr.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<P, S> Serve for P
|
impl<P, S> Serve for P
|
||||||
where P: Send + Sync + ::std::ops::Deref<Target=S>,
|
where P: Send + Sync + ::std::ops::Deref<Target = S>,
|
||||||
S: Serve
|
S: Serve
|
||||||
{
|
{
|
||||||
type Request = S::Request;
|
type Request = S::Request;
|
||||||
|
|||||||
@@ -37,12 +37,12 @@ mod benchmark {
|
|||||||
// Prevents resource exhaustion when benching
|
// Prevents resource exhaustion when benching
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref HANDLE: Arc<Mutex<ServeHandle>> = {
|
static ref HANDLE: Arc<Mutex<ServeHandle>> = {
|
||||||
let handle = serve("localhost:0", HelloServer, None).unwrap();
|
let handle = HelloServer.spawn("localhost:0").unwrap();
|
||||||
Arc::new(Mutex::new(handle))
|
Arc::new(Mutex::new(handle))
|
||||||
};
|
};
|
||||||
static ref CLIENT: Arc<Mutex<AsyncClient>> = {
|
static ref CLIENT: Arc<Mutex<AsyncClient>> = {
|
||||||
let addr = HANDLE.lock().unwrap().local_addr().clone();
|
let addr = HANDLE.lock().unwrap().local_addr().clone();
|
||||||
let client = AsyncClient::new(addr, None).unwrap();
|
let client = AsyncClient::new(addr).unwrap();
|
||||||
Arc::new(Mutex::new(client))
|
Arc::new(Mutex::new(client))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user