send player_id through request metadata

This commit is contained in:
Ilion Beyst 2022-06-06 14:25:56 +02:00
parent d0faec7d1f
commit 2f915af919
2 changed files with 25 additions and 4 deletions

View file

@ -6,13 +6,21 @@ use pb::bot_api_service_client::BotApiServiceClient;
use tokio_stream::wrappers::UnboundedReceiverStream;
use tokio::sync::mpsc;
use tonic::{metadata::MetadataValue, transport::Channel, Request};
#[tokio::main]
async fn main() {
let mut client = BotApiServiceClient::connect("http://localhost:50051")
let channel = Channel::from_static("http://localhost:50051")
.connect()
.await
.unwrap();
let mut client = BotApiServiceClient::with_interceptor(channel, |mut req: Request<()>| {
let player_id: MetadataValue<_> = "test_player".parse().unwrap();
req.metadata_mut().insert("player_id", player_id);
Ok(req)
});
let (tx, rx) = mpsc::unbounded_channel();
let mut stream = client
.connect_bot(UnboundedReceiverStream::new(rx))

View file

@ -62,10 +62,23 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer {
&self,
req: Request<Streaming<pb::PlayerRequestResponse>>,
) -> Result<Response<Self::ConnectBotStream>, Status> {
println!("bot connected");
// TODO: clean up errors
let player_id = req
.metadata()
.get("player_id")
.ok_or_else(|| Status::unauthenticated("no player_id provided"))?;
let player_id_str = player_id
.to_str()
.map_err(|_| Status::invalid_argument("unreadable string"))?;
let sync_data = self
.router
.get(player_id_str)
.ok_or_else(|| Status::not_found("player_id not found"))?;
let stream = req.into_inner();
// TODO: return error when player does not exist
let sync_data = self.router.get("test_player").unwrap();
sync_data.tx.send(stream).unwrap();
Ok(Response::new(UnboundedReceiverStream::new(
sync_data.server_messages,