|
| 1 | +use async_trait::async_trait; |
| 2 | +use std::{collections::HashMap, error::Error, fmt, sync::Arc}; |
| 3 | + |
| 4 | +use crate::{ |
| 5 | + alien, |
| 6 | + rpc::{HttpMethod, Target}, |
| 7 | +}; |
| 8 | + |
| 9 | +#[async_trait] |
| 10 | +pub trait GrpcTransport: Send + Sync + fmt::Debug { |
| 11 | + async fn unary(&self, endpoint: &str, path: &str, body: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>>; |
| 12 | +} |
| 13 | + |
| 14 | +fn unary_target(endpoint: &str, path: &str, body: Vec<u8>) -> Target { |
| 15 | + Target { |
| 16 | + url: format!("{}{}", endpoint.trim_end_matches('/'), path), |
| 17 | + method: HttpMethod::Post, |
| 18 | + headers: Some(grpc_headers()), |
| 19 | + body: Some(body), |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +fn ensure_success_status(status: Option<u16>) -> Result<(), Box<dyn Error + Send + Sync>> { |
| 24 | + if let Some(status) = status |
| 25 | + && !(200..300).contains(&status) |
| 26 | + { |
| 27 | + return Err(format!("gRPC HTTP error: status {status}").into()); |
| 28 | + } |
| 29 | + Ok(()) |
| 30 | +} |
| 31 | + |
| 32 | +fn grpc_headers() -> HashMap<String, String> { |
| 33 | + HashMap::from([ |
| 34 | + ("Content-Type".into(), "application/grpc+proto".into()), |
| 35 | + ("Accept".into(), "application/grpc+proto".into()), |
| 36 | + ("TE".into(), "trailers".into()), |
| 37 | + ]) |
| 38 | +} |
| 39 | + |
| 40 | +#[derive(Clone)] |
| 41 | +pub struct AlienGrpcTransport { |
| 42 | + provider: Arc<dyn alien::RpcProvider>, |
| 43 | +} |
| 44 | + |
| 45 | +impl AlienGrpcTransport { |
| 46 | + pub fn new(provider: Arc<dyn alien::RpcProvider>) -> Self { |
| 47 | + Self { provider } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl fmt::Debug for AlienGrpcTransport { |
| 52 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 53 | + f.debug_struct("AlienGrpcTransport").finish_non_exhaustive() |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#[async_trait] |
| 58 | +impl GrpcTransport for AlienGrpcTransport { |
| 59 | + async fn unary(&self, endpoint: &str, path: &str, body: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>> { |
| 60 | + let response = self.provider.request(unary_target(endpoint, path, body)).await?; |
| 61 | + ensure_success_status(response.status)?; |
| 62 | + Ok(response.data) |
| 63 | + } |
| 64 | +} |
0 commit comments