use std::path::Path;
use std::sync::OnceLock;
use serde_json::{Map, Value};
use trusty_secrets::server::{ClientError, OnDemandSecrets, PROJECT_FIELD};
mod get_ref;
pub use get_ref::{GetRefError, RefAnswer, get_ref};
pub fn with_project(project: &Path, params: Value) -> Option<Value> {
let project = project.to_str()?;
let mut fields = match params {
Value::Object(fields) => fields,
_ => Map::new(),
};
fields.insert(PROJECT_FIELD.to_owned(), Value::String(project.to_owned()));
Some(Value::Object(fields))
}
pub fn describe(prefix: &str, error: &ClientError, socket: &Path) -> String {
let socket = socket.display();
match error {
ClientError::Rpc(e) => format!("{prefix}: {}", e.message),
ClientError::Spawn(e) => format!("{prefix}: cannot start trusty-secrets: {e}"),
ClientError::Transport(_) => {
format!("{prefix}: the request did not cross the trusty-secrets socket {socket}")
}
ClientError::HomeUnavailable => format!("{prefix}: the home directory is unavailable"),
ClientError::EmptyResponse => {
format!("{prefix}: trusty-secrets at {socket} answered without a result")
}
_ => format!("{prefix}: trusty-secrets at {socket} failed"),
}
}
pub fn default_client() -> Result<&'static OnDemandSecrets, ClientError> {
static CLIENT: OnceLock<OnDemandSecrets> = OnceLock::new();
if let Some(client) = CLIENT.get() {
return Ok(client);
}
let client = OnDemandSecrets::new()?;
Ok(CLIENT.get_or_init(|| client))
}
#[cfg(test)]
mod tests;