use crate::plugin_service::FizzBeeServiceImpl;
use crate::pb::fizz_bee_mbt_plugin_service_server::FizzBeeMbtPluginServiceServer;
use crate::error::MbtError;
use crate::traits::{Model, DispatchModel};
use tokio::runtime::Builder;
use tonic::transport::Server;
// Imports for UDS
use tokio::net::UnixListener;
use tokio_stream::wrappers::UnixListenerStream;
use std::path::Path;
use std::fs;
// The function signature is now generic and accepts the model and dispatcher
pub fn start_grpc_server<D>(
dispatcher: D,
) -> Result<(), MbtError>
where
D: Model + DispatchModel + Send + Sync + 'static,
{
let rt = Builder::new_multi_thread()
.enable_all()
.build()
.map_err(MbtError::from_err)?;
rt.block_on(async {
// --- UDS Configuration ---
let path = Path::new("/tmp/fizzbee_mbt.sock");
// IMPORTANT: Clean up the old socket file if it exists, otherwise bind() will fail.
if path.exists() {
fs::remove_file(path).map_err(MbtError::from_err)?;
}
// Bind to the Unix socket
let uds = UnixListener::bind(path).map_err(MbtError::from_err)?;
// Wrap the listener in a stream to use with tonic
let incoming = UnixListenerStream::new(uds);
println!("gRPC server listening on UDS socket: {}", path.display());
// --- End UDS Configuration ---
let service = FizzBeeServiceImpl::new(dispatcher);
Server::builder()
.add_service(FizzBeeMbtPluginServiceServer::new(service))
// Use serve_with_incoming for Unix Domain Sockets
.serve_with_incoming(incoming)
.await
.map_err(MbtError::from_err)
})
}