use crate::config::GaiaClientConfig;
use crate::error::Result;
use crate::proto::gaia_client_client::GaiaClientClient;
use crate::proto::{
GetSecretRequest, Namespace, Secret,
};
use crate::tls::create_tls_channel;
use tonic::transport::Channel;
#[derive(Debug, Clone, Default)]
pub struct LoadEnvOptions {
pub prefix: Option<String>,
pub use_namespace: bool,
}
impl LoadEnvOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
pub fn with_namespace(mut self, use_namespace: bool) -> Self {
self.use_namespace = use_namespace;
self
}
}
pub struct GaiaClient {
inner: GaiaClientClient<Channel>,
}
impl GaiaClient {
pub async fn connect(config: GaiaClientConfig) -> Result<Self> {
let channel = create_tls_channel(&config).await?;
let inner = GaiaClientClient::new(channel);
Ok(Self { inner })
}
pub async fn get_secret(&mut self, namespace: &str, id: &str) -> Result<Secret> {
let request = tonic::Request::new(GetSecretRequest {
namespace: namespace.to_string(),
id: id.to_string(),
});
let response = self.inner.get_secret(request).await?;
Ok(response.into_inner())
}
pub async fn list_secrets(&mut self, namespace: Option<String>) -> Result<Vec<Namespace>> {
use crate::proto::ClientListSecretsRequest;
let request = tonic::Request::new(ClientListSecretsRequest {
namespace: namespace.unwrap_or_default(),
});
let response = self.inner.list_secrets(request).await?;
Ok(response.into_inner().namespaces)
}
pub async fn load_env(&mut self, options: Option<LoadEnvOptions>) -> Result<()> {
let opts = options.unwrap_or_default();
let namespaces = self.list_secrets(None).await?;
for ns in namespaces {
for secret in ns.secrets {
let mut parts = Vec::new();
if let Some(prefix) = &opts.prefix {
if !prefix.is_empty() {
parts.push(prefix.to_uppercase().replace("-", "_"));
}
}
if opts.use_namespace {
parts.push(ns.name.to_uppercase().replace("-", "_"));
}
parts.push(secret.id.to_uppercase().replace("-", "_"));
let env_var_name = parts.join("_");
std::env::set_var(env_var_name, secret.value);
}
}
Ok(())
}
}