use crate::groupcache::ValueBounds;
use crate::options::Options;
use crate::service_discovery::run_service_discovery;
use crate::{Groupcache, GroupcacheInner, GroupcachePeer, ServiceDiscovery, ValueLoader};
use moka::future::Cache;
use std::sync::Arc;
use tonic::transport::Endpoint;
pub struct GroupcacheBuilder<Value: ValueBounds> {
me: GroupcachePeer,
loader: Box<dyn ValueLoader<Value = Value>>,
options: Options<Value>,
}
impl<Value: ValueBounds> GroupcacheBuilder<Value> {
pub(crate) fn new(
me: GroupcachePeer,
loader: Box<impl ValueLoader<Value = Value> + Sized + 'static>,
) -> Self {
Self {
me,
loader,
options: Options::default(),
}
}
pub fn main_cache(mut self, main_cache: Cache<String, Value>) -> Self {
self.options.main_cache = main_cache;
self
}
pub fn hot_cache(mut self, hot_cache: Cache<String, Value>) -> Self {
self.options.hot_cache = hot_cache;
self
}
pub fn https(mut self) -> Self {
self.options.https = true;
self
}
pub fn grpc_endpoint_builder(
mut self,
builder: impl Fn(Endpoint) -> Endpoint + Send + Sync + 'static,
) -> Self {
self.options.grpc_endpoint_builder = Box::new(builder);
self
}
pub fn service_discovery(mut self, service_discovery: impl ServiceDiscovery + 'static) -> Self {
self.options.service_discovery = Some(Box::new(service_discovery));
self
}
pub fn build(mut self) -> Groupcache<Value> {
let service_discovery = self.options.service_discovery.take();
let cache = Groupcache(Arc::new(GroupcacheInner::new(
self.me,
self.loader,
self.options,
)));
if let Some(service_discovery) = service_discovery {
tokio::spawn(run_service_discovery(
Arc::downgrade(&cache.0),
service_discovery,
));
}
cache
}
}