use std::sync::Arc;
use async_trait::async_trait;
use modelexpress_common::grpc::refit_collective::{
CollectiveGroup, CollectiveGroupMembership, CollectiveTransfer,
CreateCollectiveTransferRequest, JoinCollectiveGroupRequest, PublishGroupBootstrapRequest,
ReportCollectiveTransferRequest,
};
use crate::backend_config::BackendConfig;
pub mod redis;
pub type CollectiveResult<T> = Result<T, CollectiveBackendError>;
#[derive(Debug, thiserror::Error)]
pub enum CollectiveBackendError {
#[error("{0}")]
InvalidArgument(String),
#[error("{0}")]
NotFound(String),
#[error("{0}")]
FailedPrecondition(String),
#[error("{0}")]
AlreadyExists(String),
#[error("{0}")]
Internal(String),
#[error("{0}")]
Unavailable(String),
}
#[async_trait]
pub trait CollectiveBackend: Send + Sync {
async fn join_group(
&self,
request: &JoinCollectiveGroupRequest,
) -> CollectiveResult<CollectiveGroupMembership>;
async fn get_group(&self, group_id: &str) -> CollectiveResult<CollectiveGroup>;
async fn publish_bootstrap(
&self,
request: &PublishGroupBootstrapRequest,
) -> CollectiveResult<CollectiveGroup>;
async fn create_transfer(
&self,
request: &CreateCollectiveTransferRequest,
) -> CollectiveResult<CollectiveTransfer>;
async fn get_transfer(&self, operation_id: &str) -> CollectiveResult<CollectiveTransfer>;
async fn delete_transfer(&self, operation_id: &str) -> CollectiveResult<CollectiveTransfer>;
async fn report_transfer(
&self,
request: &ReportCollectiveTransferRequest,
) -> CollectiveResult<CollectiveTransfer>;
}
pub async fn create_backend(
config: &BackendConfig,
) -> CollectiveResult<Option<Arc<dyn CollectiveBackend>>> {
match config {
BackendConfig::Redis { url } => Ok(Some(Arc::new(
redis::RedisCollectiveBackend::connect(url).await?,
))),
BackendConfig::Kubernetes { .. } => Ok(None),
#[cfg(feature = "memory-backend")]
BackendConfig::Memory => Ok(None),
}
}