Files
tarpc/src/server.rs
Tim be5f55c5f6 Extend snake_to_camel plugin to replace {} in the doc string with the original snake-cased ident. (#50)
* Extend snake_to_camel plugin to replace {} in the doc string with the origin snake-cased ident.

Also, track tokio-rs master.

This is really ad-hoc, undiscoverable, and unintuitive, but there's no way to programmatically create doc strings
in regular code, and I want to produce better doc strings for the associated types.

Given `fn foo_bar`:

Before: `/// The type of future returned by the function of the same name.`
After: ``/// The type of future returned by `{}`.``
    => `/// The type of future returned by foo_bar.`

* Fix some docs

* Use a helper fn on pipeline::Frame instead of handrolled match.

* Don't hide docs for ClientFuture.

It's exposed in the Connect impl of FutureService -- the tradeoff for not generating *another* item -- and hiding it breaks doc links.

* Formatting

* Rename snake_to_camel plugin => tarpc-plugins

* Update README

* Mangle a lot of names in macro expansion.

To lower the chance of any issues, prefix idents in service expansion with __tarpc_service.
In future_enum, prefix with __future_enum. The pattern is basically __macro_name_ident.

Any imported enum variant will conflict with a let binding or a function arg, so we basically
can't use any generic idents at all. Example:

    enum Req { request(..) }
    use self::Req::request;

    fn make_request(request: Request) { ... }

                    ^^^^^^^ conflict here

Additionally, suffix generated associated types with Fut to avoid conflicts with camelcased rpcs.
Why someone would do that, I don't know, but we shouldn't allow that wart.
2016-09-14 01:19:24 -07:00

87 lines
2.9 KiB
Rust

// 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.
use errors::{SerializableError, WireError};
use futures::{self, Async, Future};
use futures::stream::Empty;
use futures_cpupool::{CpuFuture, CpuPool};
use protocol::{LOOP_HANDLE, TarpcTransport};
use protocol::writer::Packet;
use serde::Serialize;
use std::io;
use std::net::ToSocketAddrs;
use tokio_proto::pipeline;
use tokio_proto::server::{self, ServerHandle};
use tokio_service::NewService;
use util::Never;
/// Spawns a service that binds to the given address and runs on the default tokio `Loop`.
pub fn listen<A, T>(addr: A, new_service: T) -> ListenFuture
where T: NewService<Request = Vec<u8>,
Response = pipeline::Message<Packet, Empty<Never, io::Error>>,
Error = io::Error> + Send + 'static,
A: ToSocketAddrs
{
// TODO(tikue): don't use ToSocketAddrs, or don't unwrap.
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let (tx, rx) = futures::oneshot();
LOOP_HANDLE.spawn(move |handle| {
Ok(tx.complete(server::listen(handle, addr, move |stream| {
pipeline::Server::new(new_service.new_service()?, TarpcTransport::new(stream))
}).unwrap()))
});
ListenFuture { inner: rx }
}
/// A future that resolves to a `ServerHandle`.
pub struct ListenFuture {
inner: futures::Oneshot<ServerHandle>,
}
impl Future for ListenFuture {
type Item = ServerHandle;
type Error = Never;
fn poll(&mut self) -> futures::Poll<Self::Item, Self::Error> {
match self.inner.poll().unwrap() {
Async::Ready(server_handle) => Ok(Async::Ready(server_handle)),
Async::NotReady => Ok(Async::NotReady),
}
}
}
/// Returns a future containing the serialized reply.
///
/// Because serialization can take a non-trivial
/// amount of cpu time, it is run on a thread pool.
#[doc(hidden)]
#[inline]
pub fn serialize_reply<T: Serialize + Send + 'static,
E: SerializableError>(result: Result<T, WireError<E>>)
-> SerializeFuture
{
POOL.spawn(futures::lazy(move || {
let packet = match Packet::serialize(&result) {
Ok(packet) => packet,
Err(e) => {
let err: Result<T, WireError<E>> = Err(WireError::ServerSerialize(e.to_string()));
Packet::serialize(&err).unwrap()
}
};
futures::finished(pipeline::Message::WithoutBody(packet))
}))
}
#[doc(hidden)]
pub type SerializeFuture = CpuFuture<SerializedReply, io::Error>;
#[doc(hidden)]
pub type SerializedReply = pipeline::Message<Packet, Empty<Never, io::Error>>;
lazy_static! {
static ref POOL: CpuPool = { CpuPool::new_num_cpus() };
}