keyfork/crates/daemon/keyforkd-models/src/lib.rs

85 lines
2.3 KiB
Rust
Raw Normal View History

//! All values that can be sent to and returned from Keyforkd.
//!
//! All Error values are stored as enum unit values.
use keyfork_derive_util::request::{DerivationRequest, DerivationResponse};
use serde::{Deserialize, Serialize};
/// A request made to Keyforkd.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum Request {
/// A derivation request.
Derivation(DerivationRequest),
/// A derivation request, with a TTY provided for pinentry if necessary.
DerivationWithTTY(DerivationRequest, String),
}
impl From<DerivationRequest> for Request {
fn from(value: DerivationRequest) -> Self {
Self::Derivation(value)
}
}
impl From<(DerivationRequest, String)> for Request {
fn from((request, tty): (DerivationRequest, String)) -> Self {
Self::DerivationWithTTY(request, tty)
}
}
#[derive(thiserror::Error, Clone, Debug, Serialize, Deserialize)]
pub enum DerivationError {
#[error("The provided TTY was not valid")]
InvalidTTY,
#[error("A TTY was required by the pinentry program but was not provided")]
NoTTY,
#[error("Invalid derivation length: Expected 2, actual: {0}")]
InvalidDerivationLength(usize),
#[error("Derivation error: {0}")]
Derivation(String),
}
#[derive(thiserror::Error, Clone, Debug, Serialize, Deserialize)]
pub enum Error {
#[error(transparent)]
Derivation(#[from] DerivationError),
}
/// Any response from a Keyforkd request.
///
/// Responses can be converted to their inner values without matching the Response type by
/// using a type annotation and [`TryInto::try_into`].
#[derive(Serialize, Deserialize, Clone, Debug)]
#[non_exhaustive]
pub enum Response {
/// A derivation response.
///
/// From:
/// * [`Request::Derivation`]
/// * [`Request::DerivationWithTTY`]
Derivation(DerivationResponse),
}
#[derive(thiserror::Error, Debug)]
#[error("Unable to downcast to {0}")]
pub struct Downcast(&'static str);
use std::any::type_name;
impl TryFrom<Response> for DerivationResponse {
type Error = Downcast;
fn try_from(value: Response) -> Result<Self, Self::Error> {
#[allow(irrefutable_let_patterns)]
if let Response::Derivation(response) = value {
Ok(response)
} else {
Err(Downcast(type_name::<Self>()))
}
}
}