mirror of
https://github.com/OMGeeky/tarpc.git
synced 2025-12-29 15:49:52 +01:00
* Rewrite tarpc on top of tokio. * Add examples * Move error types to their own module. Also, cull unused error variants. * Remove unused fn * Remove CanonicalRpcError* types. They're 100% useless. * Track tokio master (WIP) * The great error revamp. Removed the canonical rpc error type. Instead, the user declares the error type for each rpc: In the above example, the error type is Baz. Declaring an error is optional; if none is specified, it defaults to Never, a convenience struct that wraps the never type (exclamation mark) to impl Serialize, Deserialize, Error, etc. Also adds the convenience type StringError for easily using a String as an error type. * Add missing license header * Minor cleanup * Rename StringError => Message * Create a sync::Connect trait. Along with this, the existing Connect trait moves to future::Connect. The future and sync modules are reexported from the crate root. Additionally, the utility errors Never and Message are no longer reexported from the crate root. * Update readme * Track tokio/futures master. Add a Spawn utility trait to replace the removed forget. * Fix pre-push hook * Add doc comment to SyncServiceExt. * Fix up some documentation * Track tokio-proto master * Don't set tcp nodelay * Make future::Connect take an associated type for the future. * Unbox FutureClient::connect return type * Use type alias instead of newtype struct for ClientFuture * Fix benches/latency.rs * Write a plugin to convert lower_snake_case idents/types to UpperCamelCase. Use it to add associated types to FutureService instead of boxing the return futures. * Specify plugin = true in snake_to_camel/Cargo.toml. Weird things happen otherwise. * Add clippy.toml
133 lines
3.9 KiB
Rust
133 lines
3.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.
|
|
|
|
#![feature(conservative_impl_trait, plugin)]
|
|
#![plugin(snake_to_camel)]
|
|
|
|
extern crate env_logger;
|
|
extern crate futures;
|
|
#[macro_use]
|
|
extern crate tarpc;
|
|
extern crate tokio_proto as tokio;
|
|
|
|
use futures::{BoxFuture, Future};
|
|
use publisher::FutureServiceExt as PublisherExt;
|
|
use subscriber::FutureServiceExt as SubscriberExt;
|
|
use std::collections::HashMap;
|
|
use std::net::SocketAddr;
|
|
use std::sync::{Arc, Mutex};
|
|
use std::thread;
|
|
use std::time::Duration;
|
|
use tarpc::util::{Never, Message};
|
|
use tarpc::future::Connect as Fc;
|
|
use tarpc::sync::Connect as Sc;
|
|
|
|
pub mod subscriber {
|
|
service! {
|
|
rpc receive(message: String);
|
|
}
|
|
}
|
|
|
|
pub mod publisher {
|
|
use std::net::SocketAddr;
|
|
use tarpc::util::Message;
|
|
|
|
service! {
|
|
rpc broadcast(message: String);
|
|
rpc subscribe(id: u32, address: SocketAddr) | Message;
|
|
rpc unsubscribe(id: u32);
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
struct Subscriber {
|
|
id: u32,
|
|
publisher: publisher::SyncClient,
|
|
}
|
|
|
|
impl subscriber::FutureService for Subscriber {
|
|
type Receive = futures::Finished<(), Never>;
|
|
fn receive(&self, message: String) -> Self::Receive {
|
|
println!("{} received message: {}", self.id, message);
|
|
futures::finished(())
|
|
}
|
|
}
|
|
|
|
impl Subscriber {
|
|
fn new(id: u32, publisher: publisher::SyncClient) -> tokio::server::ServerHandle {
|
|
let subscriber = Subscriber {
|
|
id: id,
|
|
publisher: publisher.clone(),
|
|
}
|
|
.listen("localhost:0")
|
|
.unwrap();
|
|
publisher.subscribe(&id, &subscriber.local_addr()).unwrap();
|
|
subscriber
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
struct Publisher {
|
|
clients: Arc<Mutex<HashMap<u32, subscriber::FutureClient>>>,
|
|
}
|
|
|
|
impl Publisher {
|
|
fn new() -> Publisher {
|
|
Publisher { clients: Arc::new(Mutex::new(HashMap::new())) }
|
|
}
|
|
}
|
|
|
|
impl publisher::FutureService for Publisher {
|
|
type Broadcast = BoxFuture<(), Never>;
|
|
|
|
fn broadcast(&self, message: String) -> Self::Broadcast {
|
|
futures::collect(self.clients
|
|
.lock()
|
|
.unwrap()
|
|
.values()
|
|
// Ignore failing subscribers.
|
|
.map(move |client| client.receive(&message).then(|_| Ok(())))
|
|
.collect::<Vec<_>>())
|
|
.map(|_| ())
|
|
.boxed()
|
|
}
|
|
|
|
type Subscribe = BoxFuture<(), Message>;
|
|
|
|
fn subscribe(&self, id: u32, address: SocketAddr) -> BoxFuture<(), Message> {
|
|
let clients = self.clients.clone();
|
|
subscriber::FutureClient::connect(&address)
|
|
.map(move |subscriber| {
|
|
println!("Subscribing {}.", id);
|
|
clients.lock().unwrap().insert(id, subscriber);
|
|
()
|
|
})
|
|
.map_err(|e| e.to_string().into())
|
|
.boxed()
|
|
}
|
|
|
|
type Unsubscribe = BoxFuture<(), Never>;
|
|
|
|
fn unsubscribe(&self, id: u32) -> BoxFuture<(), Never> {
|
|
println!("Unsubscribing {}", id);
|
|
self.clients.lock().unwrap().remove(&id).unwrap();
|
|
futures::finished(()).boxed()
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
let _ = env_logger::init();
|
|
let publisher = Publisher::new().listen("localhost:0").unwrap();
|
|
let publisher = publisher::SyncClient::connect(publisher.local_addr()).unwrap();
|
|
let _subscriber1 = Subscriber::new(0, publisher.clone());
|
|
let _subscriber2 = Subscriber::new(1, publisher.clone());
|
|
|
|
println!("Broadcasting...");
|
|
publisher.broadcast(&"hello to all".to_string()).unwrap();
|
|
publisher.unsubscribe(&1).unwrap();
|
|
publisher.broadcast(&"hello again".to_string()).unwrap();
|
|
thread::sleep(Duration::from_millis(300));
|
|
}
|