use crate::error;
use crate::sign::{parse_keypair, Sign};
use async_trait::async_trait;
use snafu::ResultExt;
use std::fmt::Debug;
use std::path::PathBuf;
use std::result::Result;
#[async_trait]
pub trait KeySource: Debug + Send + Sync {
async fn as_sign(
&self,
) -> Result<Box<dyn Sign>, Box<dyn std::error::Error + Send + Sync + 'static>>;
async fn write(
&self,
value: &str,
key_id_hex: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>>;
}
#[derive(Debug)]
pub struct LocalKeySource {
pub path: PathBuf,
}
#[async_trait]
impl KeySource for LocalKeySource {
async fn as_sign(
&self,
) -> Result<Box<dyn Sign>, Box<dyn std::error::Error + Send + Sync + 'static>> {
let data = tokio::fs::read(&self.path)
.await
.context(error::FileReadSnafu { path: &self.path })?;
Ok(Box::new(parse_keypair(&data)?))
}
async fn write(
&self,
value: &str,
_key_id_hex: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
Ok(tokio::fs::write(&self.path, value.as_bytes())
.await
.context(error::FileWriteSnafu { path: &self.path })?)
}
}