|
| 1 | +pub mod service; |
| 2 | + |
| 3 | +use async_trait::async_trait; |
| 4 | +use common::*; |
| 5 | +use mbus_api::{v0::*, *}; |
| 6 | +use service::*; |
| 7 | +use std::{convert::TryInto, marker::PhantomData}; |
| 8 | +use structopt::StructOpt; |
| 9 | +use tracing::info; |
| 10 | + |
| 11 | +#[derive(Debug, StructOpt)] |
| 12 | +struct CliArgs { |
| 13 | + /// The Nats Server URL to connect to |
| 14 | + /// (supports the nats schema) |
| 15 | + /// Default: nats://127.0.0.1:4222 |
| 16 | + #[structopt(long, short, default_value = "nats://127.0.0.1:4222")] |
| 17 | + nats: String, |
| 18 | +} |
| 19 | + |
| 20 | +/// Needed so we can implement the ServiceSubscriber trait for |
| 21 | +/// the message types external to the crate |
| 22 | +#[derive(Clone, Default)] |
| 23 | +struct ServiceHandler<T> { |
| 24 | + data: PhantomData<T>, |
| 25 | +} |
| 26 | + |
| 27 | +macro_rules! impl_service_handler { |
| 28 | + // RequestType is the message bus request type |
| 29 | + // ServiceFnName is the name of the service function to route the request |
| 30 | + // into |
| 31 | + ($RequestType:ident, $ServiceFnName:ident) => { |
| 32 | + #[async_trait] |
| 33 | + impl ServiceSubscriber for ServiceHandler<$RequestType> { |
| 34 | + async fn handler(&self, args: Arguments<'_>) -> Result<(), Error> { |
| 35 | + let request: ReceivedMessage<$RequestType> = |
| 36 | + args.request.try_into()?; |
| 37 | + |
| 38 | + let reply = JsonGrpcSvc::$ServiceFnName(&request.inner()) |
| 39 | + .await |
| 40 | + .map_err(|error| Error::ServiceError { |
| 41 | + message: error.full_string(), |
| 42 | + })?; |
| 43 | + request.reply(reply).await |
| 44 | + } |
| 45 | + fn filter(&self) -> Vec<MessageId> { |
| 46 | + vec![$RequestType::default().id()] |
| 47 | + } |
| 48 | + } |
| 49 | + }; |
| 50 | +} |
| 51 | + |
| 52 | +impl_service_handler!(JsonGrpcRequest, json_grpc_call); |
| 53 | + |
| 54 | +fn init_tracing() { |
| 55 | + if let Ok(filter) = tracing_subscriber::EnvFilter::try_from_default_env() { |
| 56 | + tracing_subscriber::fmt().with_env_filter(filter).init(); |
| 57 | + } else { |
| 58 | + tracing_subscriber::fmt().with_env_filter("info").init(); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +#[tokio::main] |
| 63 | +async fn main() { |
| 64 | + init_tracing(); |
| 65 | + |
| 66 | + let cli_args = CliArgs::from_args(); |
| 67 | + info!("Using options: {:?}", &cli_args); |
| 68 | + |
| 69 | + server(cli_args).await; |
| 70 | +} |
| 71 | + |
| 72 | +async fn server(cli_args: CliArgs) { |
| 73 | + Service::builder(cli_args.nats, ChannelVs::JsonGrpc) |
| 74 | + .connect() |
| 75 | + .await |
| 76 | + .with_subscription(ServiceHandler::<JsonGrpcRequest>::default()) |
| 77 | + .run() |
| 78 | + .await; |
| 79 | +} |
0 commit comments